diff --git a/.gitignore b/.gitignore index 1bf4259af7a73274c7c11d281143be9c2675a873..215737b5f545a2ec4f6fed0826d292faf5bf370e 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ config.js +node_modules \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver deleted file mode 120000 index 317eb293d8e125968256d4819f26caf2343475c4..0000000000000000000000000000000000000000 --- a/node_modules/.bin/semver +++ /dev/null @@ -1 +0,0 @@ -../semver/bin/semver \ No newline at end of file diff --git a/node_modules/@types/bluebird/LICENSE b/node_modules/@types/bluebird/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4b1ad51b2f0efc36f38aa3349a9f30fbd9217547 --- /dev/null +++ b/node_modules/@types/bluebird/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. 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/@types/bluebird/README.md b/node_modules/@types/bluebird/README.md new file mode 100644 index 0000000000000000000000000000000000000000..29ece90130c05a8b7d6e089c149385ff8ba9793c --- /dev/null +++ b/node_modules/@types/bluebird/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/bluebird` + +# Summary +This package contains type definitions for bluebird (https://github.com/petkaantonov/bluebird). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/bluebird + +Additional Details + * Last updated: Thu, 13 Dec 2018 21:05:14 GMT + * Dependencies: none + * Global values: none + +# Credits +These definitions were written by Leonard Hecker <https://github.com/lhecker>. diff --git a/node_modules/@types/bluebird/index.d.ts b/node_modules/@types/bluebird/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..24c2b79a3299e84de9fd2db921bfaea7c74c2e45 --- /dev/null +++ b/node_modules/@types/bluebird/index.d.ts @@ -0,0 +1,1240 @@ +// Type definitions for bluebird 3.5 +// Project: https://github.com/petkaantonov/bluebird +// Definitions by: Leonard Hecker <https://github.com/lhecker> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/*! + * The code following this comment originates from: + * https://github.com/types/npm-bluebird + * + * Note for browser users: use bluebird-global typings instead of this one + * if you want to use Bluebird via the global Promise symbol. + * + * Licensed under: + * The MIT License (MIT) + * + * Copyright (c) 2016 unional + * + * 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. + */ + +type Constructor<E> = new (...args: any[]) => E; +type CatchFilter<E> = ((error: E) => boolean) | (object & E); +type IterableItem<R> = R extends Iterable<infer U> ? U : never; +type IterableOrNever<R> = Extract<R, Iterable<any>>; +type Resolvable<R> = R | PromiseLike<R>; +type IterateFunction<T, R> = (item: T, index: number, arrayLength: number) => Resolvable<R>; + +declare class Bluebird<R> implements PromiseLike<R>, Bluebird.Inspection<R> { + /** + * Create a new promise. The passed in function will receive functions + * `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. + * + * If promise cancellation is enabled, passed in function will receive + * one more function argument `onCancel` that allows to register an optional cancellation callback. + */ + constructor(callback: (resolve: (thenableOrResult?: Resolvable<R>) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void); + + /** + * Promises/A+ `.then()`. Returns a new promise chained from this promise. + * + * The new promise will be rejected or resolved depending on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + */ + // Based on PromiseLike.then, but returns a Bluebird instance. + then<U>(onFulfill?: (value: R) => Resolvable<U>, onReject?: (error: any) => Resolvable<U>): Bluebird<U>; // For simpler signature help. + then<TResult1 = R, TResult2 = never>( + onfulfilled?: ((value: R) => Resolvable<TResult1>) | null, + onrejected?: ((reason: any) => Resolvable<TResult2>) | null + ): Bluebird<TResult1 | TResult2>; + + /** + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. + * + * Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch<U = R>(onReject: ((error: any) => Resolvable<U>) | undefined | null): Bluebird<U | R>; + + /** + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. + * + * Instead of manually checking `instanceof` or `.name === "SomeError"`, + * you may specify a number of error constructors which are eligible for this catch handler. + * The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. + * If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. + * The return result of the predicate will be used determine whether the error handler should be called. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch<U, E1, E2, E3, E4, E5>( + filter1: Constructor<E1>, + filter2: Constructor<E2>, + filter3: Constructor<E3>, + filter4: Constructor<E4>, + filter5: Constructor<E5>, + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<U>, + ): Bluebird<U | R>; + + catch<U, E1, E2, E3, E4, E5>( + filter1: Constructor<E1> | CatchFilter<E1>, + filter2: Constructor<E2> | CatchFilter<E2>, + filter3: Constructor<E3> | CatchFilter<E3>, + filter4: Constructor<E4> | CatchFilter<E4>, + filter5: Constructor<E5> | CatchFilter<E5>, + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<U>, + ): Bluebird<U | R>; + + catch<U, E1, E2, E3, E4>( + filter1: Constructor<E1>, + filter2: Constructor<E2>, + filter3: Constructor<E3>, + filter4: Constructor<E4>, + onReject: (error: E1 | E2 | E3 | E4) => Resolvable<U>, + ): Bluebird<U | R>; + + catch<U, E1, E2, E3, E4>( + filter1: Constructor<E1> | CatchFilter<E1>, + filter2: Constructor<E2> | CatchFilter<E2>, + filter3: Constructor<E3> | CatchFilter<E3>, + filter4: Constructor<E4> | CatchFilter<E4>, + onReject: (error: E1 | E2 | E3 | E4) => Resolvable<U>, + ): Bluebird<U | R>; + + catch<U, E1, E2, E3>( + filter1: Constructor<E1>, + filter2: Constructor<E2>, + filter3: Constructor<E3>, + onReject: (error: E1 | E2 | E3) => Resolvable<U>, + ): Bluebird<U | R>; + + catch<U, E1, E2, E3>( + filter1: Constructor<E1> | CatchFilter<E1>, + filter2: Constructor<E2> | CatchFilter<E2>, + filter3: Constructor<E3> | CatchFilter<E3>, + onReject: (error: E1 | E2 | E3) => Resolvable<U>, + ): Bluebird<U | R>; + + catch<U, E1, E2>( + filter1: Constructor<E1>, + filter2: Constructor<E2>, + onReject: (error: E1 | E2) => Resolvable<U>, + ): Bluebird<U | R>; + + catch<U, E1, E2>( + filter1: Constructor<E1> | CatchFilter<E1>, + filter2: Constructor<E2> | CatchFilter<E2>, + onReject: (error: E1 | E2) => Resolvable<U>, + ): Bluebird<U | R>; + + catch<U, E1>( + filter1: Constructor<E1>, + onReject: (error: E1) => Resolvable<U>, + ): Bluebird<U | R>; + + catch<U, E1>( + // tslint:disable-next-line:unified-signatures + filter1: Constructor<E1> | CatchFilter<E1>, + onReject: (error: E1) => Resolvable<U>, + ): Bluebird<U | R>; + + /** + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. + * + * Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + caught: Bluebird<R>["catch"]; + + /** + * Like `.catch` but instead of catching all types of exceptions, + * it only catches those that don't originate from thrown errors but rather from explicit rejections. + */ + error<U>(onReject: (reason: any) => Resolvable<U>): Bluebird<U>; + + /** + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. + * + * There are special semantics for `.finally()` in that the final value cannot be modified from the handler. + * + * Alias `.lastly();` for compatibility with earlier ECMAScript version. + */ + finally(handler: () => Resolvable<any>): Bluebird<R>; + + lastly: Bluebird<R>["finally"]; + + /** + * Create a promise that follows this promise, but is bound to the given `thisArg` value. + * A bound promise will call its handlers with the bound value set to `this`. + * + * Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + */ + bind(thisArg: any): Bluebird<R>; + + /** + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. + */ + done<U>(onFulfilled?: (value: R) => Resolvable<U>, onRejected?: (error: any) => Resolvable<U>): void; + + /** + * Like `.finally()`, but not called for rejections. + */ + tap(onFulFill: (value: R) => Resolvable<any>): Bluebird<R>; + + /** + * Like `.catch()` but rethrows the error + */ + tapCatch(onReject: (error?: any) => Resolvable<any>): Bluebird<R>; + + tapCatch<E1, E2, E3, E4, E5>( + filter1: Constructor<E1>, + filter2: Constructor<E2>, + filter3: Constructor<E3>, + filter4: Constructor<E4>, + filter5: Constructor<E5>, + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<any>, + ): Bluebird<R>; + tapCatch<E1, E2, E3, E4, E5>( + filter1: Constructor<E1> | CatchFilter<E1>, + filter2: Constructor<E2> | CatchFilter<E2>, + filter3: Constructor<E3> | CatchFilter<E3>, + filter4: Constructor<E4> | CatchFilter<E4>, + filter5: Constructor<E5> | CatchFilter<E5>, + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<any>, + ): Bluebird<R>; + tapCatch<E1, E2, E3, E4>( + filter1: Constructor<E1>, + filter2: Constructor<E2>, + filter3: Constructor<E3>, + filter4: Constructor<E4>, + onReject: (error: E1 | E2 | E3 | E4) => Resolvable<any>, + ): Bluebird<R>; + tapCatch<E1, E2, E3, E4>( + filter1: Constructor<E1> | CatchFilter<E1>, + filter2: Constructor<E2> | CatchFilter<E2>, + filter3: Constructor<E3> | CatchFilter<E3>, + filter4: Constructor<E4> | CatchFilter<E4>, + onReject: (error: E1 | E2 | E3 | E4) => Resolvable<any>, + ): Bluebird<R>; + tapCatch<E1, E2, E3>( + filter1: Constructor<E1>, + filter2: Constructor<E2>, + filter3: Constructor<E3>, + onReject: (error: E1 | E2 | E3) => Resolvable<any>, + ): Bluebird<R>; + tapCatch<E1, E2, E3>( + filter1: Constructor<E1> | CatchFilter<E1>, + filter2: Constructor<E2> | CatchFilter<E2>, + filter3: Constructor<E3> | CatchFilter<E3>, + onReject: (error: E1 | E2 | E3) => Resolvable<any>, + ): Bluebird<R>; + tapCatch<E1, E2>( + filter1: Constructor<E1>, + filter2: Constructor<E2>, + onReject: (error: E1 | E2) => Resolvable<any>, + ): Bluebird<R>; + tapCatch<E1, E2>( + filter1: Constructor<E1> | CatchFilter<E1>, + filter2: Constructor<E2> | CatchFilter<E2>, + onReject: (error: E1 | E2) => Resolvable<any>, + ): Bluebird<R>; + tapCatch<E1>( + filter1: Constructor<E1>, + onReject: (error: E1) => Resolvable<any>, + ): Bluebird<R>; + tapCatch<E1>( + // tslint:disable-next-line:unified-signatures + filter1: Constructor<E1> | CatchFilter<E1>, + onReject: (error: E1) => Resolvable<any>, + ): Bluebird<R>; + + /** + * Same as calling `Promise.delay(ms, this)`. + */ + delay(ms: number): Bluebird<R>; + + /** + * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. + * However, if this promise is not fulfilled or rejected within ms milliseconds, the returned promise + * is rejected with a TimeoutError or the error as the reason. + * + * You may specify a custom error message with the `message` parameter. + */ + timeout(ms: number, message?: string | Error): Bluebird<R>; + + /** + * Register a node-style callback on this promise. + * + * When this promise is is either fulfilled or rejected, + * the node callback will be called back with the node.js convention + * where error reason is the first argument and success value is the second argument. + * + * The error argument will be `null` in case of success. + * If the `callback` argument is not a function, this method does not do anything. + */ + nodeify(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; + nodeify(...sink: any[]): this; + asCallback(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; + asCallback(...sink: any[]): this; + + /** + * See if this `promise` has been fulfilled. + */ + isFulfilled(): boolean; + + /** + * See if this `promise` has been rejected. + */ + isRejected(): boolean; + + /** + * See if this `promise` is still defer. + */ + isPending(): boolean; + + /** + * See if this `promise` has been cancelled. + */ + isCancelled(): boolean; + + /** + * See if this `promise` is resolved -> either fulfilled or rejected. + */ + isResolved(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. + * + * throws `TypeError` + */ + value(): R; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. + * + * throws `TypeError` + */ + reason(): any; + + /** + * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of + * the promise as snapshotted at the time of calling `.reflect()`. + */ + reflect(): Bluebird<Bluebird.Inspection<R>>; + reflect(): Bluebird<Bluebird.Inspection<any>>; + + /** + * This is a convenience method for doing: + * + * <code> + * promise.then(function(obj){ + * return obj[propertyName].call(obj, arg...); + * }); + * </code> + */ + call<U extends keyof R>(propertyName: U, ...args: any[]): Bluebird<R[U] extends (...args: any[]) => any ? ReturnType<R[U]> : never>; + + /** + * This is a convenience method for doing: + * + * <code> + * promise.then(function(obj){ + * return obj[propertyName]; + * }); + * </code> + */ + get<U extends keyof R>(key: U): Bluebird<R[U]>; + + /** + * Convenience method for: + * + * <code> + * .then(function() { + * return value; + * }); + * </code> + * + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` + * + * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. + */ + return(): Bluebird<void>; + return<U>(value: U): Bluebird<U>; + thenReturn(): Bluebird<void>; + thenReturn<U>(value: U): Bluebird<U>; + + /** + * Convenience method for: + * + * <code> + * .then(function() { + * throw reason; + * }); + * </code> + * Same limitations apply as with `.return()`. + * + * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. + */ + throw(reason: Error): Bluebird<never>; + thenThrow(reason: Error): Bluebird<never>; + + /** + * Convenience method for: + * + * <code> + * .catch(function() { + * return value; + * }); + * </code> + * + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.catchReturn()` + */ + catchReturn<U>(value: U): Bluebird<R | U>; + + // No need to be specific about Error types in these overrides, since there's no handler function + catchReturn<U>( + filter1: Constructor<Error>, + filter2: Constructor<Error>, + filter3: Constructor<Error>, + filter4: Constructor<Error>, + filter5: Constructor<Error>, + value: U, + ): Bluebird<R | U>; + catchReturn<U>( + filter1: Constructor<Error> | CatchFilter<Error>, + filter2: Constructor<Error> | CatchFilter<Error>, + filter3: Constructor<Error> | CatchFilter<Error>, + filter4: Constructor<Error> | CatchFilter<Error>, + filter5: Constructor<Error> | CatchFilter<Error>, + value: U, + ): Bluebird<R | U>; + catchReturn<U>( + filter1: Constructor<Error>, + filter2: Constructor<Error>, + filter3: Constructor<Error>, + filter4: Constructor<Error>, + value: U, + ): Bluebird<R | U>; + catchReturn<U>( + filter1: Constructor<Error> | CatchFilter<Error>, + filter2: Constructor<Error> | CatchFilter<Error>, + filter3: Constructor<Error> | CatchFilter<Error>, + filter4: Constructor<Error> | CatchFilter<Error>, + value: U, + ): Bluebird<R | U>; + catchReturn<U>( + filter1: Constructor<Error>, + filter2: Constructor<Error>, + filter3: Constructor<Error>, + value: U, + ): Bluebird<R | U>; + catchReturn<U>( + filter1: Constructor<Error> | CatchFilter<Error>, + filter2: Constructor<Error> | CatchFilter<Error>, + filter3: Constructor<Error> | CatchFilter<Error>, + value: U, + ): Bluebird<R | U>; + catchReturn<U>( + filter1: Constructor<Error>, + filter2: Constructor<Error>, + value: U, + ): Bluebird<R | U>; + catchReturn<U>( + filter1: Constructor<Error> | CatchFilter<Error>, + filter2: Constructor<Error> | CatchFilter<Error>, + value: U, + ): Bluebird<R | U>; + catchReturn<U>( + filter1: Constructor<Error>, + value: U, + ): Bluebird<R | U>; + catchReturn<U>( + // tslint:disable-next-line:unified-signatures + filter1: Constructor<Error> | CatchFilter<Error>, + value: U, + ): Bluebird<R | U>; + + /** + * Convenience method for: + * + * <code> + * .catch(function() { + * throw reason; + * }); + * </code> + * Same limitations apply as with `.catchReturn()`. + */ + catchThrow(reason: Error): Bluebird<R>; + + // No need to be specific about Error types in these overrides, since there's no handler function + catchThrow( + filter1: Constructor<Error>, + filter2: Constructor<Error>, + filter3: Constructor<Error>, + filter4: Constructor<Error>, + filter5: Constructor<Error>, + reason: Error, + ): Bluebird<R>; + catchThrow( + filter1: Constructor<Error> | CatchFilter<Error>, + filter2: Constructor<Error> | CatchFilter<Error>, + filter3: Constructor<Error> | CatchFilter<Error>, + filter4: Constructor<Error> | CatchFilter<Error>, + filter5: Constructor<Error> | CatchFilter<Error>, + reason: Error, + ): Bluebird<R>; + catchThrow( + filter1: Constructor<Error>, + filter2: Constructor<Error>, + filter3: Constructor<Error>, + filter4: Constructor<Error>, + reason: Error, + ): Bluebird<R>; + catchThrow( + filter1: Constructor<Error> | CatchFilter<Error>, + filter2: Constructor<Error> | CatchFilter<Error>, + filter3: Constructor<Error> | CatchFilter<Error>, + filter4: Constructor<Error> | CatchFilter<Error>, + reason: Error, + ): Bluebird<R>; + catchThrow( + filter1: Constructor<Error>, + filter2: Constructor<Error>, + filter3: Constructor<Error>, + reason: Error, + ): Bluebird<R>; + catchThrow( + filter1: Constructor<Error> | CatchFilter<Error>, + filter2: Constructor<Error> | CatchFilter<Error>, + filter3: Constructor<Error> | CatchFilter<Error>, + reason: Error, + ): Bluebird<R>; + catchThrow( + filter1: Constructor<Error>, + filter2: Constructor<Error>, + reason: Error, + ): Bluebird<R>; + catchThrow( + filter1: Constructor<Error> | CatchFilter<Error>, + filter2: Constructor<Error> | CatchFilter<Error>, + reason: Error, + ): Bluebird<R>; + catchThrow( + filter1: Constructor<Error>, + reason: Error, + ): Bluebird<R>; + catchThrow( + // tslint:disable-next-line:unified-signatures + filter1: Constructor<Error> | CatchFilter<Error>, + reason: Error, + ): Bluebird<R>; + + /** + * Convert to String. + */ + toString(): string; + + /** + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. + */ + toJSON(): object; + + /** + * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. + */ + spread<U>(fulfilledHandler: (...values: Array<IterableItem<R>>) => Resolvable<U>): Bluebird<U>; + + /** + * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + all(): Bluebird<IterableOrNever<R>>; + + /** + * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + props<K, V>(this: PromiseLike<Map<K, Resolvable<V>>>): Bluebird<Map<K, V>>; + props<T>(this: PromiseLike<Bluebird.ResolvableProps<T>>): Bluebird<T>; + + /** + * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + any(): Bluebird<IterableItem<R>>; + + /** + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + some(count: number): Bluebird<IterableOrNever<R>>; + + /** + * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + race(): Bluebird<IterableItem<R>>; + + /** + * Same as calling `Bluebird.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + map<U>(mapper: IterateFunction<IterableItem<R>, U>, options?: Bluebird.ConcurrencyOption): Bluebird<R extends Iterable<any> ? U[] : never>; + + /** + * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + reduce<U>(reducer: (memo: U, item: IterableItem<R>, index: number, arrayLength: number) => Resolvable<U>, initialValue?: U): Bluebird<R extends Iterable<any> ? U : never>; + + /** + * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + filter(filterer: IterateFunction<IterableItem<R>, boolean>, options?: Bluebird.ConcurrencyOption): Bluebird<IterableOrNever<R>>; + + /** + * Same as calling ``Bluebird.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + each(iterator: IterateFunction<IterableItem<R>, any>): Bluebird<IterableOrNever<R>>; + + /** + * Same as calling ``Bluebird.mapSeries(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + mapSeries<U>(iterator: IterateFunction<IterableItem<R>, U>): Bluebird<R extends Iterable<any> ? U[] : never>; + + /** + * Cancel this `promise`. Will not do anything if this promise is already settled or if the cancellation feature has not been enabled + */ + cancel(): void; + + /** + * Basically sugar for doing: somePromise.catch(function(){}); + * + * Which is needed in case error handlers are attached asynchronously to the promise later, which would otherwise result in premature unhandled rejection reporting. + */ + suppressUnhandledRejections(): void; + + /** + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. + * + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. + * Otherwise it is passed as is as the first argument for the function call. + * + * Alias for `attempt();` for compatibility with earlier ECMAScript version. + */ + static try<R>(fn: () => Resolvable<R>): Bluebird<R>; + static attempt<R>(fn: () => Resolvable<R>): Bluebird<R>; + + /** + * Returns a new function that wraps the given function `fn`. + * The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * This method is convenient when a function can sometimes return synchronously or throw synchronously. + */ + static method<R>(fn: () => Resolvable<R>): () => Bluebird<R>; + static method<R, A1>(fn: (arg1: A1) => Resolvable<R>): (arg1: A1) => Bluebird<R>; + static method<R, A1, A2>(fn: (arg1: A1, arg2: A2) => Resolvable<R>): (arg1: A1, arg2: A2) => Bluebird<R>; + static method<R, A1, A2, A3>(fn: (arg1: A1, arg2: A2, arg3: A3) => Resolvable<R>): (arg1: A1, arg2: A2, arg3: A3) => Bluebird<R>; + static method<R, A1, A2, A3, A4>(fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Resolvable<R>): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird<R>; + static method<R, A1, A2, A3, A4, A5>(fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Resolvable<R>): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird<R>; + static method<R>(fn: (...args: any[]) => Resolvable<R>): (...args: any[]) => Bluebird<R>; + + /** + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. + */ + static resolve(): Bluebird<void>; + static resolve<R>(value: Resolvable<R>): Bluebird<R>; + + /** + * Create a promise that is rejected with the given `reason`. + */ + static reject(reason: any): Bluebird<never>; + + /** + * @deprecated + * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). + * @see http://bluebirdjs.com/docs/deprecated-apis.html#promise-resolution + */ + static defer<R>(): Bluebird.Resolver<R>; // tslint:disable-line no-unnecessary-generics + + /** + * Cast the given `value` to a trusted promise. + * + * If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. + * If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. + */ + static cast<R>(value: Resolvable<R>): Bluebird<R>; + + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + static bind(thisArg: any): Bluebird<void>; + + /** + * See if `value` is a trusted Promise. + */ + static is(value: any): boolean; + + /** + * Call this right after the library is loaded to enabled long stack traces. + * + * 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, around 4-5x for throughput and 0.5x for latency. + */ + static longStackTraces(): void; + + /** + * Returns a promise that will be resolved with value (or undefined) after given ms milliseconds. + * If value is a promise, the delay will start counting down when it is fulfilled and the returned + * promise will be fulfilled with the fulfillment value of the value promise. + */ + static delay<R>(ms: number, value: Resolvable<R>): Bluebird<R>; + static delay(ms: number): Bluebird<void>; + + /** + * Returns a function that will wrap the given `nodeFunction`. + * + * Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. + * The node function should conform to node.js convention of accepting a callback as last argument and + * calling that callback with error as the first argument and success value on the second argument. + * + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. + * + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. + */ + static promisify<T>( + func: (callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): () => Bluebird<T>; + static promisify<T, A1>( + func: (arg1: A1, callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): (arg1: A1) => Bluebird<T>; + static promisify<T, A1, A2>( + func: (arg1: A1, arg2: A2, callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): (arg1: A1, arg2: A2) => Bluebird<T>; + static promisify<T, A1, A2, A3>( + func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): (arg1: A1, arg2: A2, arg3: A3) => Bluebird<T>; + static promisify<T, A1, A2, A3, A4>( + func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird<T>; + static promisify<T, A1, A2, A3, A4, A5>( + func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird<T>; + static promisify(nodeFunction: (...args: any[]) => void, options?: Bluebird.PromisifyOptions): (...args: any[]) => Bluebird<any>; + + /** + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. + * + * The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, + * if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + */ + // TODO how to model promisifyAll? + static promisifyAll<T extends object>(target: T, options?: Bluebird.PromisifyAllOptions<T>): T; + + /** + * Returns a promise that is resolved by a node style callback function. + */ + static fromNode<T>(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird<T>; + static fromCallback<T>(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird<T>; + + /** + * Returns a function that can use `yield` to run asynchronous code synchronously. + * + * This feature requires the support of generators which are drafted in the next version of the language. + * Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO: After https://github.com/Microsoft/TypeScript/issues/2983 is implemented, we can use + // the return type propagation of generators to automatically infer the return type T. + static coroutine<T>( + generatorFunction: () => IterableIterator<any>, + options?: Bluebird.CoroutineOptions + ): () => Bluebird<T>; + static coroutine<T, A1>( + generatorFunction: (a1: A1) => IterableIterator<any>, + options?: Bluebird.CoroutineOptions + ): (a1: A1) => Bluebird<T>; + static coroutine<T, A1, A2>( + generatorFunction: (a1: A1, a2: A2) => IterableIterator<any>, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2) => Bluebird<T>; + static coroutine<T, A1, A2, A3>( + generatorFunction: (a1: A1, a2: A2, a3: A3) => IterableIterator<any>, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3) => Bluebird<T>; + static coroutine<T, A1, A2, A3, A4>( + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4) => IterableIterator<any>, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3, a4: A4) => Bluebird<T>; + static coroutine<T, A1, A2, A3, A4, A5>( + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => IterableIterator<any>, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => Bluebird<T>; + static coroutine<T, A1, A2, A3, A4, A5, A6>( + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => IterableIterator<any>, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => Bluebird<T>; + static coroutine<T, A1, A2, A3, A4, A5, A6, A7>( + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => IterableIterator<any>, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => Bluebird<T>; + static coroutine<T, A1, A2, A3, A4, A5, A6, A7, A8>( + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => IterableIterator<any>, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => Bluebird<T>; + + /** + * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + */ + static onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + + /** + * Add handler as the handler to call when there is a possibly unhandled rejection. + * The default handler logs the error stack to stderr or console.error in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + * + * Note: this hook is specific to the bluebird instance its called on, application developers should use global rejection events. + */ + static onPossiblyUnhandledRejection(handler?: (error: Error, promise: Bluebird<any>) => void): void; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. + * The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. + * If any promise in the array rejects, the returned promise is rejected with the rejection reason. + */ + // TODO enable more overloads + // array with promises of different types + static all<T1, T2, T3, T4, T5>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>]): Bluebird<[T1, T2, T3, T4, T5]>; + static all<T1, T2, T3, T4>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>]): Bluebird<[T1, T2, T3, T4]>; + static all<T1, T2, T3>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>]): Bluebird<[T1, T2, T3]>; + static all<T1, T2>(values: [Resolvable<T1>, Resolvable<T2>]): Bluebird<[T1, T2]>; + static all<T1>(values: [Resolvable<T1>]): Bluebird<[T1]>; + // array with values + static all<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R[]>; + + /** + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. + * + * The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. + * If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. + * All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * + * *The original object is not modified.* + */ + // map + static props<K, V>(map: Resolvable<Map<K, Resolvable<V>>>): Bluebird<Map<K, V>>; + // trusted promise for object + static props<T>(object: PromiseLike<Bluebird.ResolvableProps<T>>): Bluebird<T>; // tslint:disable-line:unified-signatures + // object + static props<T>(object: Bluebird.ResolvableProps<T>): Bluebird<T>; // tslint:disable-line:unified-signatures + + /** + * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. + */ + static any<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R>; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is + * fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. + * + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. + */ + static race<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R>; + + /** + * Initiate a competitive race between multiple promises or values (values will become immediately fulfilled promises). + * When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of + * the winners in order of resolution. + * + * If too many promises are rejected so that the promise can never become fulfilled, + * it will be immediately rejected with an array of rejection reasons in the order they were thrown in. + * + * *The original array is not modified.* + */ + static some<R>(values: Resolvable<Iterable<Resolvable<R>>>, count: number): Bluebird<R[]>; + + /** + * Promise.join( + * Promise<any>|any values..., + * function handler + * ) -> Promise + * For coordinating multiple concurrent discrete promises. + * + * Note: In 1.x and 0.x Promise.join used to be a Promise.all that took the values in as arguments instead in an array. + * This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply + */ + static join<R, A1>( + arg1: Resolvable<A1>, + handler: (arg1: A1) => Resolvable<R> + ): Bluebird<R>; + static join<R, A1, A2>( + arg1: Resolvable<A1>, + arg2: Resolvable<A2>, + handler: (arg1: A1, arg2: A2) => Resolvable<R> + ): Bluebird<R>; + static join<R, A1, A2, A3>( + arg1: Resolvable<A1>, + arg2: Resolvable<A2>, + arg3: Resolvable<A3>, + handler: (arg1: A1, arg2: A2, arg3: A3) => Resolvable<R> + ): Bluebird<R>; + static join<R, A1, A2, A3, A4>( + arg1: Resolvable<A1>, + arg2: Resolvable<A2>, + arg3: Resolvable<A3>, + arg4: Resolvable<A4>, + handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Resolvable<R> + ): Bluebird<R>; + static join<R, A1, A2, A3, A4, A5>( + arg1: Resolvable<A1>, + arg2: Resolvable<A2>, + arg3: Resolvable<A3>, + arg4: Resolvable<A4>, + arg5: Resolvable<A5>, + handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Resolvable<R> + ): Bluebird<R>; + + // variadic array + /** @deprecated use .all instead */ + static join<R>(...values: Array<Resolvable<R>>): Bluebird<R[]>; + + /** + * Map an array, or a promise of an array, + * which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` + * where `item` is the resolved value of a respective promise in the input array. + * If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + static map<R, U>( + values: Resolvable<Iterable<Resolvable<R>>>, + mapper: IterateFunction<R, U>, + options?: Bluebird.ConcurrencyOption + ): Bluebird<U[]>; + + /** + * Reduce an array, or a promise of an array, + * which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` + * where `item` is the resolved value of a respective promise in the input array. + * If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * + * *The original array is not modified. If no `initialValue` is given and the array doesn't contain at least 2 items, + * the callback will not be called and `undefined` is returned. + * + * If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + */ + static reduce<R, U>( + values: Resolvable<Iterable<Resolvable<R>>>, + reducer: (total: U, current: R, index: number, arrayLength: number) => Resolvable<U>, + initialValue?: U + ): Bluebird<U>; + + /** + * Filter an array, or a promise of an array, + * which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` + * where `item` is the resolved value of a respective promise in the input array. + * If any promise in the input array is rejected the returned promise is rejected as well. + * + * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. + * + * *The original array is not modified. + */ + static filter<R>( + values: Resolvable<Iterable<Resolvable<R>>>, + filterer: IterateFunction<R, boolean>, + option?: Bluebird.ConcurrencyOption + ): Bluebird<R[]>; + + /** + * Iterate over an array, or a promise of an array, + * which contains promises (or a mix of promises and values) with the given iterator function with the signature `(item, index, value)` + * where item is the resolved value of a respective promise in the input array. + * Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. + * + * Resolves to the original array unmodified, this method is meant to be used for side effects. + * If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + */ + static each<R>( + values: Resolvable<Iterable<Resolvable<R>>>, + iterator: IterateFunction<R, any> + ): Bluebird<R[]>; + + /** + * Given an Iterable(arrays are Iterable), or a promise of an Iterable, which produces promises (or a mix of promises and values), + * iterate over all the values in the Iterable into an array and iterate over the array serially, in-order. + * + * Returns a promise for an array that contains the values returned by the iterator function in their respective positions. + * The iterator won't be called for an item until its previous item, and the promise returned by the iterator for that item are fulfilled. + * This results in a mapSeries kind of utility but it can also be used simply as a side effect iterator similar to Array#forEach. + * + * If any promise in the input array is rejected or any promise returned by the iterator function is rejected, the result will be rejected as well. + */ + static mapSeries<R, U>( + values: Resolvable<Iterable<Resolvable<R>>>, + iterator: IterateFunction<R, U> + ): Bluebird<U[]>; + + /** + * A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`. + * + * Returns a Disposer object which encapsulates both the resource as well as the method to clean it up. + * The user can pass this object to `Promise.using` to get access to the resource when it becomes available, + * as well as to ensure its automatically cleaned up. + * + * The second argument passed to a disposer is the result promise of the using block, which you can + * inspect synchronously. + */ + disposer(disposeFn: (arg: R, promise: Bluebird<R>) => Resolvable<void>): Bluebird.Disposer<R>; + + /** + * In conjunction with `.disposer`, using will make sure that no matter what, the specified disposer + * will be called when the promise returned by the callback passed to using has settled. The disposer is + * necessary because there is no standard interface in node for disposing resources. + */ + static using<R, T>( + disposer: Bluebird.Disposer<R>, + executor: (transaction: R) => PromiseLike<T> + ): Bluebird<T>; + static using<R1, R2, T>( + disposer: Bluebird.Disposer<R1>, + disposer2: Bluebird.Disposer<R2>, + executor: (transaction1: R1, transaction2: R2 + ) => PromiseLike<T>): Bluebird<T>; + static using<R1, R2, R3, T>( + disposer: Bluebird.Disposer<R1>, + disposer2: Bluebird.Disposer<R2>, + disposer3: Bluebird.Disposer<R3>, + executor: (transaction1: R1, transaction2: R2, transaction3: R3) => PromiseLike<T> + ): Bluebird<T>; + + /** + * Configure long stack traces, warnings, monitoring and cancellation. + * Note that even though false is the default here, a development environment might be detected which automatically + * enables long stack traces and warnings. + */ + static config(options: { + /** Enable warnings */ + warnings?: boolean | { + /** Enables all warnings except forgotten return statements. */ + wForgottenReturn: boolean; + }; + /** Enable long stack traces */ + longStackTraces?: boolean; + /** Enable cancellation */ + cancellation?: boolean; + /** Enable monitoring */ + monitoring?: boolean; + }): void; + + /** + * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. + * If promise cancellation is enabled, passed in function will receive one more function argument `onCancel` that allows to register an optional cancellation callback. + */ + static Promise: typeof Bluebird; + + /** + * The version number of the library + */ + static version: string; +} + +declare namespace Bluebird { + interface ConcurrencyOption { + concurrency: number; + } + interface SpreadOption { + spread: boolean; + } + interface FromNodeOptions { + multiArgs?: boolean; + } + interface PromisifyOptions { + context?: any; + multiArgs?: boolean; + } + interface PromisifyAllOptions<T> extends PromisifyOptions { + suffix?: string; + filter?(name: string, func: (...args: any[]) => any, target?: any, passesDefaultFilter?: boolean): boolean; + // The promisifier gets a reference to the original method and should return a function which returns a promise + promisifier?(this: T, originalMethod: (...args: any[]) => any, defaultPromisifer: (...args: any[]) => (...args: any[]) => Bluebird<any>): () => PromiseLike<any>; + } + interface CoroutineOptions { + yieldHandler(value: any): any; + } + + /** + * Represents an error is an explicit promise rejection as opposed to a thrown error. + * For example, if an error is errbacked by a callback API promisified through undefined or undefined + * and is not a typed error, it will be converted to a `OperationalError` which has the original error in + * the `.cause` property. + * + * `OperationalError`s are caught in `.error` handlers. + */ + class OperationalError extends Error { } + + /** + * Signals that an operation has timed out. Used as a custom cancellation reason in `.timeout`. + */ + class TimeoutError extends Error { } + + /** + * Signals that an operation has been aborted or cancelled. The default reason used by `.cancel`. + */ + class CancellationError extends Error { } + + /** + * A collection of errors. `AggregateError` is an array-like object, with numeric indices and a `.length` property. + * It supports all generic array methods such as `.forEach` directly. + * + * `AggregateError`s are caught in `.error` handlers, even if the contained errors are not operational. + * + * `Promise.some` and `Promise.any` use `AggregateError` as rejection reason when they fail. + */ + class AggregateError extends Error implements ArrayLike<Error> { + length: number; + [index: number]: Error; + join(separator?: string): string; + pop(): Error; + push(...errors: Error[]): number; + shift(): Error; + unshift(...errors: Error[]): number; + slice(begin?: number, end?: number): AggregateError; + filter(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError; + forEach(callback: (element: Error, index: number, array: AggregateError) => void, thisArg?: any): undefined; + some(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean; + every(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean; + map(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError; + indexOf(searchElement: Error, fromIndex?: number): number; + lastIndexOf(searchElement: Error, fromIndex?: number): number; + reduce(callback: (accumulator: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any; + reduceRight(callback: (previousValue: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any; + sort(compareFunction?: (errLeft: Error, errRight: Error) => number): AggregateError; + reverse(): AggregateError; + } + + /** + * returned by `Bluebird.disposer()`. + */ + class Disposer<R> { } + + /** @deprecated Use PromiseLike<T> directly. */ + type Thenable<T> = PromiseLike<T>; + + type ResolvableProps<T> = object & {[K in keyof T]: Resolvable<T[K]>}; + + interface Resolver<R> { + /** + * Returns a reference to the controlled promise that can be passed to clients. + */ + promise: Bluebird<R>; + + /** + * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. + */ + resolve(value: R): void; + resolve(): void; + + /** + * Reject the underlying promise with `reason` as the rejection reason. + */ + reject(reason: any): void; + + /** + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. + * The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. + * + * If the the callback is called with multiple success values, the resolver fulfills its promise with an array of the values. + */ + // TODO specify resolver callback + callback(err: any, value: R, ...values: R[]): void; + } + + interface Inspection<R> { + /** + * See if the underlying promise was fulfilled at the creation time of this inspection object. + */ + isFulfilled(): boolean; + + /** + * See if the underlying promise was rejected at the creation time of this inspection object. + */ + isRejected(): boolean; + + /** + * See if the underlying promise was cancelled at the creation time of this inspection object. + */ + isCancelled(): boolean; + + /** + * See if the underlying promise was defer at the creation time of this inspection object. + */ + isPending(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. + * + * throws `TypeError` + */ + value(): R; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. + * + * throws `TypeError` + */ + reason(): any; + } + + /** + * Returns a new independent copy of the Bluebird library. + * + * This method should be used before you use any of the methods which would otherwise alter the global Bluebird object - to avoid polluting global state. + */ + function getNewLibraryCopy(): typeof Bluebird; + + /** + * This is relevant to browser environments with no module loader. + * + * Release control of the Promise namespace to whatever it was before this library was loaded. + * Returns a reference to the library namespace so you can attach it to something else. + */ + function noConflict(): typeof Bluebird; + + /** + * Changes how bluebird schedules calls a-synchronously. + * + * @param scheduler Should be a function that asynchronously schedules + * the calling of the passed in function + */ + function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; +} + +export = Bluebird; diff --git a/node_modules/@types/bluebird/package.json b/node_modules/@types/bluebird/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ad2a441396cec1009e7a605050bd7c4b9cb76062 --- /dev/null +++ b/node_modules/@types/bluebird/package.json @@ -0,0 +1,52 @@ +{ + "_from": "@types/bluebird@^3.5.19", + "_id": "@types/bluebird@3.5.25", + "_inBundle": false, + "_integrity": "sha512-yfhIBix+AIFTmYGtkC0Bi+XGjSkOINykqKvO/Wqdz/DuXlAKK7HmhLAXdPIGsV4xzKcL3ev/zYc4yLNo+OvGaw==", + "_location": "/@types/bluebird", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/bluebird@^3.5.19", + "name": "@types/bluebird", + "escapedName": "@types%2fbluebird", + "scope": "@types", + "rawSpec": "^3.5.19", + "saveSpec": null, + "fetchSpec": "^3.5.19" + }, + "_requiredBy": [ + "/promise-mysql" + ], + "_resolved": "https://registry.npmjs.org/@types/bluebird/-/bluebird-3.5.25.tgz", + "_shasum": "59188b871208092e37767e4b3d80c3b3eaae43bd", + "_spec": "@types/bluebird@^3.5.19", + "_where": "/home/capsule_man/developpement/happy-botday/node_modules/promise-mysql", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Leonard Hecker", + "url": "https://github.com/lhecker" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "TypeScript definitions for bluebird", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/bluebird", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.8", + "types": "index", + "typesPublisherContentHash": "84f287bba570664e8a87b6b30953506fa39d74685adb9b86fb0389dad064398f", + "version": "3.5.25" +} diff --git a/node_modules/@types/mysql/LICENSE b/node_modules/@types/mysql/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..21071075c24599ee98254f702bcfc504cdc275a6 --- /dev/null +++ b/node_modules/@types/mysql/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. 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/@types/mysql/README.md b/node_modules/@types/mysql/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6df98f2515860683ba0dd6388ea61d5b0d737979 --- /dev/null +++ b/node_modules/@types/mysql/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/mysql` + +# Summary +This package contains type definitions for mysql (https://github.com/mysqljs/mysql). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mysql + +Additional Details + * Last updated: Thu, 31 May 2018 20:09:03 GMT + * Dependencies: stream, tls, node + * Global values: none + +# Credits +These definitions were written by William Johnston <https://github.com/wjohnsto>, Kacper Polak <https://github.com/kacepe>, Krittanan Pingclasai <https://github.com/kpping>, James Munro <https://github.com/jdmunro>. diff --git a/node_modules/@types/mysql/index.d.ts b/node_modules/@types/mysql/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d98fe17ec5a9134cff80c1069cea5bede4c8f4f9 --- /dev/null +++ b/node_modules/@types/mysql/index.d.ts @@ -0,0 +1,586 @@ +// Type definitions for mysql 2.15 +// Project: https://github.com/mysqljs/mysql +// Definitions by: William Johnston <https://github.com/wjohnsto> +// Kacper Polak <https://github.com/kacepe> +// Krittanan Pingclasai <https://github.com/kpping> +// James Munro <https://github.com/jdmunro> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// <reference types="node" /> + +import stream = require("stream"); +import tls = require("tls"); + +export interface EscapeFunctions { + escape(value: any, stringifyObjects?: boolean, timeZone?: string): string; + + escapeId(value: string, forbidQualified?: boolean): string; + + format(sql: string, values: any[], stringifyObjects?: boolean, timeZone?: string): string; +} + +// implements EscapeFunctions +export function escape(value: any, stringifyObjects?: boolean, timeZone?: string): string; + +export function escapeId(value: string, forbidQualified?: boolean): string; + +export function format(sql: string, values: any[], stringifyObjects?: boolean, timeZone?: string): string; + +export function createConnection(connectionUri: string | ConnectionConfig): Connection; + +export function createPool(config: PoolConfig | string): Pool; + +export function createPoolCluster(config?: PoolClusterConfig): PoolCluster; + +export function raw(sql: string): () => string; + +export interface Connection extends EscapeFunctions { + config: ConnectionConfig; + + state: 'connected' | 'authenticated' | 'disconnected' | 'protocol_error' | string; + + threadId: number | null; + + createQuery: QueryFunction; + + connect(callback?: (err: MysqlError, ...args: any[]) => void): void; + + connect(options: any, callback?: (err: MysqlError, ...args: any[]) => void): void; + + changeUser(options: ConnectionOptions, callback?: (err: MysqlError) => void): void; + changeUser(callback: (err: MysqlError) => void): void; + + beginTransaction(options?: QueryOptions, callback?: (err: MysqlError) => void): void; + + beginTransaction(callback: (err: MysqlError) => void): void; + + commit(options?: QueryOptions, callback?: (err: MysqlError) => void): void; + commit(callback: (err: MysqlError) => void): void; + + rollback(options?: QueryOptions, callback?: (err: MysqlError) => void): void; + rollback(callback: (err: MysqlError) => void): void; + + query: QueryFunction; + + ping(options?: QueryOptions, callback?: (err: MysqlError) => void): void; + ping(callback: (err: MysqlError) => void): void; + + statistics(options?: QueryOptions, callback?: (err: MysqlError) => void): void; + statistics(callback: (err: MysqlError) => void): void; + + end(callback?: (err: MysqlError, ...args: any[]) => void): void; + end(options: any, callback: (err: MysqlError, ...args: any[]) => void): void; + + destroy(): void; + + pause(): void; + + resume(): void; + + on(ev: 'drain' | 'connect', callback: () => void): Connection; + + on(ev: 'end', callback: (err?: MysqlError) => void): Connection; + + on(ev: 'fields', callback: (fields: any[]) => void): Connection; + + on(ev: 'error', callback: (err: MysqlError) => void): Connection; + + on(ev: 'enqueue', callback: (...args: any[]) => void): Connection; + + on(ev: string, callback: (...args: any[]) => void): this; +} + +export interface PoolConnection extends Connection { + release(): void; + + end(): void; + + destroy(): void; +} + +export interface Pool extends EscapeFunctions { + config: PoolConfig; + + getConnection(callback: (err: MysqlError, connection: PoolConnection) => void): void; + + acquireConnection(connection: PoolConnection, callback: (err: MysqlError, connection: PoolConnection) => void): void; + + releaseConnection(connection: PoolConnection): void; + + end(callback?: (err: MysqlError) => void): void; + + query: QueryFunction; + + on(ev: 'connection' | 'acquire' | 'release', callback: (connection: PoolConnection) => void): Pool; + + on(ev: 'error', callback: (err: MysqlError) => void): Pool; + + on(ev: 'enqueue', callback: (err?: MysqlError) => void): Pool; + + on(ev: string, callback: (...args: any[]) => void): Pool; +} + +export interface PoolCluster { + config: PoolClusterConfig; + + add(config: PoolConfig): void; + + add(id: string, config: PoolConfig): void; + + end(callback?: (err: MysqlError) => void): void; + + of(pattern: string, selector?: string): Pool; + of(pattern: undefined | null | false, selector: string): Pool; + + /** + * remove all pools which match pattern + */ + remove(pattern: string): void; + + getConnection(callback: (err: MysqlError, connection: PoolConnection) => void): void; + + getConnection(pattern: string, callback: (err: MysqlError, connection: PoolConnection) => void): void; + + getConnection(pattern: string, selector: string, callback: (err: MysqlError, connection: PoolConnection) => void): void; + + on(ev: string, callback: (...args: any[]) => void): PoolCluster; + + on(ev: 'remove' | 'offline' | 'remove', callback: (nodeId: string) => void): PoolCluster; +} + +// related to Query +export type packetCallback = (packet: any) => void; + +export interface Query { + /** + * Template query + */ + sql: string; + + /** + * Values for template query + */ + values?: string[]; + + /** + * Default true + */ + typeCast?: TypeCast; + + /** + * Default false + */ + nestedTables: boolean; + + /** + * Emits a query packet to start the query + */ + start(): void; + + /** + * Determines the packet class to use given the first byte of the packet. + * + * @param byte The first byte of the packet + * @param parser The packet parser + */ + determinePacket(byte: number, parser: any): any; + + OkPacket: packetCallback; + ErrorPacket: packetCallback; + ResultSetHeaderPacket: packetCallback; + FieldPacket: packetCallback; + EofPacket: packetCallback; + + RowDataPacket(packet: any, parser: any, connection: Connection): void; + + /** + * Creates a Readable stream with the given options + * + * @param options The options for the stream. (see readable-stream package) + */ + stream(options?: stream.ReadableOptions): stream.Readable; + + on(ev: string, callback: (...args: any[]) => void): Query; + + on(ev: 'result', callback: (row: any, index: number) => void): Query; + + on(ev: 'error', callback: (err: MysqlError) => void): Query; + + on(ev: 'fields', callback: (fields: FieldInfo[], index: number) => void): Query; + + on(ev: 'packet', callback: (packet: any) => void): Query; + + on(ev: 'end', callback: () => void): Query; +} + +export interface GeometryType extends Array<{x: number, y: number} | GeometryType> { + x: number; + y: number; +} + +export type TypeCast = boolean | ( + (field: FieldInfo + & { type: string, length: number, string(): string, buffer(): Buffer, geometry(): null | GeometryType}, + next: () => void) => any); + +export type queryCallback = (err: MysqlError | null, results?: any, fields?: FieldInfo[]) => void; + +// values can be non [], see custom format (https://github.com/mysqljs/mysql#custom-format) +export interface QueryFunction { + (query: Query): Query; + + (options: string | QueryOptions, callback?: queryCallback): Query; + + (options: string, values: any, callback?: queryCallback): Query; +} + +export interface QueryOptions { + /** + * The SQL for the query + */ + sql: string; + + /** + * Values for template query + */ + values?: any; + + /** + * Every operation takes an optional inactivity timeout option. This allows you to specify appropriate timeouts for + * operations. It is important to note that these timeouts are not part of the MySQL protocol, and rather timeout + * operations through the client. This means that when a timeout is reached, the connection it occurred on will be + * destroyed and no further operations can be performed. + */ + timeout?: number; + + /** + * Either a boolean or string. If true, tables will be nested objects. If string (e.g. '_'), tables will be + * nested as tableName_fieldName + */ + nestTables?: any; + + /** + * Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future) + * to disable type casting, but you can currently do so on either the connection or query level. (Default: true) + * + * You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself. + * + * WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once. + * + * field.string() + * field.buffer() + * field.geometry() + * + * are aliases for + * + * parser.parseLengthCodedString() + * parser.parseLengthCodedBuffer() + * parser.parseGeometryValue() + * + * You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast + */ + typeCast?: TypeCast; +} + +export interface ConnectionOptions { + /** + * The MySQL user to authenticate as + */ + user?: string; + + /** + * The password of that MySQL user + */ + password?: string; + + /** + * Name of the database to use for this connection + */ + database?: string; + + /** + * The charset for the connection. This is called "collation" in the SQL-level of MySQL (like utf8_general_ci). + * If a SQL-level charset is specified (like utf8mb4) then the default collation for that charset is used. + * (Default: 'UTF8_GENERAL_CI') + */ + charset?: string; + + /** + * Number of milliseconds + */ + timeout?: number; +} + +export interface ConnectionConfig extends ConnectionOptions { + /** + * The hostname of the database you are connecting to. (Default: localhost) + */ + host?: string; + + /** + * The port number to connect to. (Default: 3306) + */ + port?: number; + + /** + * The source IP address to use for TCP connection + */ + localAddress?: string; + + /** + * The path to a unix domain socket to connect to. When used host and port are ignored + */ + socketPath?: string; + + /** + * The timezone used to store local dates. (Default: 'local') + */ + timezone?: string; + + /** + * The milliseconds before a timeout occurs during the initial connection to the MySQL server. (Default: 10 seconds) + */ + connectTimeout?: number; + + /** + * Stringify objects instead of converting to values. (Default: 'false') + */ + stringifyObjects?: boolean; + + /** + * Allow connecting to MySQL instances that ask for the old (insecure) authentication method. (Default: false) + */ + insecureAuth?: boolean; + + /** + * Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future) + * to disable type casting, but you can currently do so on either the connection or query level. (Default: true) + * + * You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself. + * + * WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once. + * + * field.string() + * field.buffer() + * field.geometry() + * + * are aliases for + * + * parser.parseLengthCodedString() + * parser.parseLengthCodedBuffer() + * parser.parseGeometryValue() + * + * You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast + */ + typeCast?: TypeCast; + + /** + * A custom query format function + */ + queryFormat?(query: string, values: any): void; + + /** + * When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option + * (Default: false) + */ + supportBigNumbers?: boolean; + + /** + * Enabling both supportBigNumbers and bigNumberStrings forces big numbers (BIGINT and DECIMAL columns) to be + * always returned as JavaScript String objects (Default: false). Enabling supportBigNumbers but leaving + * bigNumberStrings disabled will return big numbers as String objects only when they cannot be accurately + * represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5) + * (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects. + * This option is ignored if supportBigNumbers is disabled. + */ + bigNumberStrings?: boolean; + + /** + * Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript + * Date objects. Can be true/false or an array of type names to keep as strings. (Default: false) + */ + dateStrings?: boolean | Array<'TIMESTAMP' | 'DATETIME' | 'DATE'>; + + /** + * This will print all incoming and outgoing packets on stdout. + * You can also restrict debugging to packet types by passing an array of types (strings) to debug; + * + * (Default: false) + */ + debug?: boolean | string[] | Types[]; + + /** + * Generates stack traces on errors to include call site of library entrance ("long stack traces"). Slight + * performance penalty for most calls. (Default: true) + */ + trace?: boolean; + + /** + * Allow multiple mysql statements per query. Be careful with this, it exposes you to SQL injection attacks. (Default: false) + */ + multipleStatements?: boolean; + + /** + * List of connection flags to use other than the default ones. It is also possible to blacklist default ones + */ + flags?: string[]; + + /** + * object with ssl parameters or a string containing name of ssl profile + */ + ssl?: string | (tls.SecureContextOptions & { rejectUnauthorized?: boolean }); +} + +export interface PoolConfig extends ConnectionConfig { + /** + * The milliseconds before a timeout occurs during the connection acquisition. This is slightly different from connectTimeout, + * because acquiring a pool connection does not always involve making a connection. (Default: 10 seconds) + */ + acquireTimeout?: number; + + /** + * Determines the pool's action when no connections are available and the limit has been reached. If true, the pool will queue + * the connection request and call it when one becomes available. If false, the pool will immediately call back with an error. + * (Default: true) + */ + waitForConnections?: boolean; + + /** + * The maximum number of connections to create at once. (Default: 10) + */ + connectionLimit?: number; + + /** + * The maximum number of connection requests the pool will queue before returning an error from getConnection. If set to 0, there + * is no limit to the number of queued connection requests. (Default: 0) + */ + queueLimit?: number; +} + +export interface PoolClusterConfig { + /** + * If true, PoolCluster will attempt to reconnect when connection fails. (Default: true) + */ + canRetry?: boolean; + + /** + * If connection fails, node's errorCount increases. When errorCount is greater than removeNodeErrorCount, + * remove a node in the PoolCluster. (Default: 5) + */ + removeNodeErrorCount?: number; + + /** + * If connection fails, specifies the number of milliseconds before another connection attempt will be made. + * If set to 0, then node will be removed instead and never re-used. (Default: 0) + */ + restoreNodeTimeout?: number; + + /** + * The default selector. (Default: RR) + * RR: Select one alternately. (Round-Robin) + * RANDOM: Select the node by random function. + * ORDER: Select the first node available unconditionally. + */ + defaultSelector?: string; +} + +export interface MysqlError extends Error { + /** + * Either a MySQL server error (e.g. 'ER_ACCESS_DENIED_ERROR'), + * a node.js error (e.g. 'ECONNREFUSED') or an internal error + * (e.g. 'PROTOCOL_CONNECTION_LOST'). + */ + code: string; + + /** + * The error number for the error code + */ + errno: number; + + /** + * The sql state marker + */ + sqlStateMarker?: string; + + /** + * The sql state + */ + sqlState?: string; + + /** + * The field count + */ + fieldCount?: number; + + /** + * The stack trace for the error + */ + stack?: string; + + /** + * Boolean, indicating if this error is terminal to the connection object. + */ + fatal: boolean; + + /** + * SQL of failed query + */ + sql?: string; + + /** + * Error message from MySQL + */ + sqlMessage?: string; +} + +export const enum Types { + DECIMAL = 0x00, // aka DECIMAL (http://dev.mysql.com/doc/refman/5.0/en/precision-math-decimal-changes.html) + TINY = 0x01, // aka TINYINT, 1 byte + SHORT = 0x02, // aka SMALLINT, 2 bytes + LONG = 0x03, // aka INT, 4 bytes + FLOAT = 0x04, // aka FLOAT, 4-8 bytes + DOUBLE = 0x05, // aka DOUBLE, 8 bytes + NULL = 0x06, // NULL (used for prepared statements, I think) + TIMESTAMP = 0x07, // aka TIMESTAMP + LONGLONG = 0x08, // aka BIGINT, 8 bytes + INT24 = 0x09, // aka MEDIUMINT, 3 bytes + DATE = 0x0a, // aka DATE + TIME = 0x0b, // aka TIME + DATETIME = 0x0c, // aka DATETIME + YEAR = 0x0d, // aka YEAR, 1 byte (don't ask) + NEWDATE = 0x0e, // aka ? + VARCHAR = 0x0f, // aka VARCHAR (?) + BIT = 0x10, // aka BIT, 1-8 byte + TIMESTAMP2 = 0x11, // aka TIMESTAMP with fractional seconds + DATETIME2 = 0x12, // aka DATETIME with fractional seconds + TIME2 = 0x13, // aka TIME with fractional seconds + JSON = 0xf5, // aka JSON + NEWDECIMAL = 0xf6, // aka DECIMAL + ENUM = 0xf7, // aka ENUM + SET = 0xf8, // aka SET + TINY_BLOB = 0xf9, // aka TINYBLOB, TINYTEXT + MEDIUM_BLOB = 0xfa, // aka MEDIUMBLOB, MEDIUMTEXT + LONG_BLOB = 0xfb, // aka LONGBLOG, LONGTEXT + BLOB = 0xfc, // aka BLOB, TEXT + VAR_STRING = 0xfd, // aka VARCHAR, VARBINARY + STRING = 0xfe, // aka CHAR, BINARY + GEOMETRY = 0xff, // aka GEOMETRY +} + +export interface FieldInfo { + catalog: string; + db: string; + table: string; + orgTable: string; + name: string; + orgName: string; + charsetNr: number; + length: number; + type: Types; + flags: number; + decimals: number; + default?: string; + zeroFill: boolean; + protocol41: boolean; +} diff --git a/node_modules/@types/mysql/package.json b/node_modules/@types/mysql/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ad279cff4eca5ad5b6deaa1a01632f6800060a03 --- /dev/null +++ b/node_modules/@types/mysql/package.json @@ -0,0 +1,65 @@ +{ + "_from": "@types/mysql@^2.15.2", + "_id": "@types/mysql@2.15.5", + "_inBundle": false, + "_integrity": "sha512-4QAISTUGZbcFh7bqdndo08xRdES5OTU+JODy8VCZbe1yiXyGjqw1H83G43XjQ3IbC10wn9xlGd44A5RXJwNh0Q==", + "_location": "/@types/mysql", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/mysql@^2.15.2", + "name": "@types/mysql", + "escapedName": "@types%2fmysql", + "scope": "@types", + "rawSpec": "^2.15.2", + "saveSpec": null, + "fetchSpec": "^2.15.2" + }, + "_requiredBy": [ + "/promise-mysql" + ], + "_resolved": "https://registry.npmjs.org/@types/mysql/-/mysql-2.15.5.tgz", + "_shasum": "6d75afb5cc018c9d66b2f37a046924e397f85430", + "_spec": "@types/mysql@^2.15.2", + "_where": "/home/capsule_man/developpement/happy-botday/node_modules/promise-mysql", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "William Johnston", + "url": "https://github.com/wjohnsto" + }, + { + "name": "Kacper Polak", + "url": "https://github.com/kacepe" + }, + { + "name": "Krittanan Pingclasai", + "url": "https://github.com/kpping" + }, + { + "name": "James Munro", + "url": "https://github.com/jdmunro" + } + ], + "dependencies": { + "@types/node": "*" + }, + "deprecated": false, + "description": "TypeScript definitions for mysql", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/mysql", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.1", + "typesPublisherContentHash": "5ab0640250fb34af9e11026236c9009f506a78be9ddd17745a348947c3766d6f", + "version": "2.15.5" +} diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4b1ad51b2f0efc36f38aa3349a9f30fbd9217547 --- /dev/null +++ b/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. 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/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fdabc43e749771ccec113fac10e93a06ed81e309 --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for non-npm package Node.js ( http://nodejs.org/ ). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node + +Additional Details + * Last updated: Thu, 14 Feb 2019 16:52:07 GMT + * Dependencies: none + * Global values: Buffer, NodeJS, SharedArrayBuffer, Symbol, __dirname, __filename, clearImmediate, clearInterval, clearTimeout, console, exports, global, module, process, queueMicrotask, require, setImmediate, setInterval, setTimeout + +# Credits +These definitions were written by Microsoft TypeScript <https://github.com/Microsoft>, DefinitelyTyped <https://github.com/DefinitelyTyped>, Alberto Schiabel <https://github.com/jkomyno>, Alexander T. <https://github.com/a-tarasyuk>, Alvis HT Tang <https://github.com/alvis>, Andrew Makarov <https://github.com/r3nya>, Benjamin Toueg <https://github.com/btoueg>, Bruno Scheufler <https://github.com/brunoscheufler>, Chigozirim C. <https://github.com/smac89>, Christian Vaagland Tellnes <https://github.com/tellnes>, David Junger <https://github.com/touffy>, Deividas Bakanas <https://github.com/DeividasBakanas>, Eugene Y. Q. Shen <https://github.com/eyqs>, Flarna <https://github.com/Flarna>, Hannes Magnusson <https://github.com/Hannes-Magnusson-CK>, Hoàng Văn Khải <https://github.com/KSXGitHub>, Huw <https://github.com/hoo29>, Kelvin Jin <https://github.com/kjin>, Klaus Meinhardt <https://github.com/ajafff>, Lishude <https://github.com/islishude>, Mariusz Wiktorczyk <https://github.com/mwiktorczyk>, Matthieu Sieben <https://github.com/matthieusieben>, Mohsen Azimi <https://github.com/mohsen1>, Nicolas Even <https://github.com/n-e>, Nicolas Voigt <https://github.com/octo-sniffle>, Parambir Singh <https://github.com/parambirs>, Sebastian Silbermann <https://github.com/eps1lon>, Simon Schick <https://github.com/SimonSchick>, Thomas den Hollander <https://github.com/ThomasdenH>, Wilco Bakker <https://github.com/WilcoBakker>, wwwy3y3 <https://github.com/wwwy3y3>, Zane Hannan AU <https://github.com/ZaneHannanAU>, Jeremie Rodriguez <https://github.com/jeremiergz>, Samuel Ainsworth <https://github.com/samuela>, Kyle Uehlein <https://github.com/kuehlein>. diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d73353c5d8020f06e604b81cd27f4ae1108bcfa0 --- /dev/null +++ b/node_modules/@types/node/assert.d.ts @@ -0,0 +1,52 @@ +declare module "assert" { + function internal(value: any, message?: string | Error): void; + namespace internal { + class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFn?: Function + }); + } + + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never; + function ok(value: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + function equal(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + function notEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + function deepEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + function strictEqual(actual: any, expected: any, message?: string | Error): void; + function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; + + function throws(block: Function, message?: string | Error): void; + function throws(block: Function, error: RegExp | Function | Object | Error, message?: string | Error): void; + function doesNotThrow(block: Function, message?: string | Error): void; + function doesNotThrow(block: Function, error: RegExp | Function, message?: string | Error): void; + + function ifError(value: any): void; + + function rejects(block: Function | Promise<any>, message?: string | Error): Promise<void>; + function rejects(block: Function | Promise<any>, error: RegExp | Function | Object | Error, message?: string | Error): Promise<void>; + function doesNotReject(block: Function | Promise<any>, message?: string | Error): Promise<void>; + function doesNotReject(block: Function | Promise<any>, error: RegExp | Function, message?: string | Error): Promise<void>; + + const strict: typeof internal; + } + + export = internal; +} diff --git a/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c77932ecd71908a663ffe96ef690e9c10f4282f --- /dev/null +++ b/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,144 @@ +/** + * Async Hooks module: https://nodejs.org/api/async_hooks.html + */ +declare module "async_hooks" { + /** + * Returns the asyncId of the current execution context. + */ + function executionAsyncId(): number; + + /** + * Returns the ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: Object): void; + + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + + /** + * Registers functions to be called for different lifetime events of each async operation. + * @param options the callbacks to register + * @return an AsyncHooks instance used for disabling and enabling hooks + */ + function createHook(options: HookCallbacks): AsyncHook; + + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * Default: `executionAsyncId()` + */ + triggerAsyncId?: number; + + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * Default: `false` + */ + requireManualDestroy?: boolean; + } + + /** + * The class AsyncResource was designed to be extended by the embedder's async resources. + * Using this users can easily trigger the lifetime events of their own resources. + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since 9.3) + */ + constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); + + /** + * Call AsyncHooks before callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitBefore(): void; + + /** + * Call AsyncHooks after callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitAfter(): void; + + /** + * Call the provided function with the provided arguments in the + * execution context of the async resource. This will establish the + * context, trigger the AsyncHooks before callbacks, call the function, + * trigger the AsyncHooks after callbacks, and then restore the original + * execution context. + * @param fn The function to call in the execution context of this + * async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope<This, Result>(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + + /** + * Call AsyncHooks destroy callbacks. + */ + emitDestroy(): void; + + /** + * @return the unique ID assigned to this AsyncResource instance. + */ + asyncId(): number; + + /** + * @return the trigger ID for this AsyncResource instance. + */ + triggerAsyncId(): number; + } +} diff --git a/node_modules/@types/node/base.d.ts b/node_modules/@types/node/base.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..70983d951595013d8a8c5edd95e6308871c2c47a --- /dev/null +++ b/node_modules/@types/node/base.d.ts @@ -0,0 +1,41 @@ +// base definnitions for all NodeJS modules that are not specific to any version of TypeScript +/// <reference path="globals.d.ts" /> +/// <reference path="assert.d.ts" /> +/// <reference path="async_hooks.d.ts" /> +/// <reference path="buffer.d.ts" /> +/// <reference path="child_process.d.ts" /> +/// <reference path="cluster.d.ts" /> +/// <reference path="console.d.ts" /> +/// <reference path="constants.d.ts" /> +/// <reference path="crypto.d.ts" /> +/// <reference path="dgram.d.ts" /> +/// <reference path="dns.d.ts" /> +/// <reference path="domain.d.ts" /> +/// <reference path="events.d.ts" /> +/// <reference path="fs.d.ts" /> +/// <reference path="http.d.ts" /> +/// <reference path="http2.d.ts" /> +/// <reference path="https.d.ts" /> +/// <reference path="inspector.d.ts" /> +/// <reference path="module.d.ts" /> +/// <reference path="net.d.ts" /> +/// <reference path="os.d.ts" /> +/// <reference path="path.d.ts" /> +/// <reference path="perf_hooks.d.ts" /> +/// <reference path="process.d.ts" /> +/// <reference path="punycode.d.ts" /> +/// <reference path="querystring.d.ts" /> +/// <reference path="readline.d.ts" /> +/// <reference path="repl.d.ts" /> +/// <reference path="stream.d.ts" /> +/// <reference path="string_decoder.d.ts" /> +/// <reference path="timers.d.ts" /> +/// <reference path="tls.d.ts" /> +/// <reference path="trace_events.d.ts" /> +/// <reference path="tty.d.ts" /> +/// <reference path="url.d.ts" /> +/// <reference path="util.d.ts" /> +/// <reference path="v8.d.ts" /> +/// <reference path="vm.d.ts" /> +/// <reference path="worker_threads.d.ts" /> +/// <reference path="zlib.d.ts" /> diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d618f2c4b71c398c82b9a9e9b4337fe7d2c8f56 --- /dev/null +++ b/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,12 @@ +declare module "buffer" { + export const INSPECT_MAX_BYTES: number; + const BuffType: typeof Buffer; + + export const SlowBuffer: { + /** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */ + new(size: number): Buffer; + prototype: Buffer; + }; + + export { BuffType as Buffer }; +} diff --git a/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e10d4e0c71d8e08d0d4e072dd59f5c8a1fa6f63 --- /dev/null +++ b/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,338 @@ +declare module "child_process" { + import * as events from "events"; + import * as stream from "stream"; + import * as net from "net"; + + interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + killed: boolean; + pid: number; + kill(signal?: string): void; + send(message: any, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error) => void): boolean; + connected: boolean; + disconnect(): void; + unref(): void; + ref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number, signal: string) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number, signal: string): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: string | null): boolean; + emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number, signal: string) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number, signal: string) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number, signal: string) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + } + + interface MessageOptions { + keepOpen?: boolean; + } + + type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | stream.Stream | number | null | undefined)>; + + interface CommonOptions { + /** + * @default true + */ + windowsHide?: boolean; + uid?: number; + gid?: number; + cwd?: string; + env?: NodeJS.ProcessEnv; + /** + * @default 0 + */ + timeout?: number; + } + + interface SpawnOptions extends CommonOptions { + argv0?: string; + stdio?: StdioOptions; + detached?: boolean; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + } + + function spawn(command: string, options?: SpawnOptions): ChildProcess; + function spawn(command: string, args?: ReadonlyArray<string>, options?: SpawnOptions): ChildProcess; + + interface ExecOptions extends CommonOptions { + shell?: string; + maxBuffer?: number; + killSignal?: string; + } + + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string | null; // specify `null`. + } + + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: string; + } + + // no `options` definitely means stdout/stderr are `string`. + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ({ encoding?: string | null } & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exec { + function __promisify__(command: string): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: ExecOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ExecFileOptions extends CommonOptions { + maxBuffer?: number; + killSignal?: string; + windowsVerbatimArguments?: boolean; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: string; + } + + function execFile(file: string): ChildProcess; + function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray<string> | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray<string> | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray<string> | undefined | null, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: Error | null, stdout: string, stderr: string) => void, + ): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray<string> | undefined | null, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace execFile { + function __promisify__(file: string): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__( + file: string, + args: string[] | undefined | null, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + ): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ForkOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + stdio?: StdioOptions; + windowsVerbatimArguments?: boolean; + uid?: number; + gid?: number; + } + function fork(modulePath: string, args?: ReadonlyArray<string>, options?: ForkOptions): ChildProcess; + + interface SpawnSyncOptions extends CommonOptions { + argv0?: string; // Not specified in the docs + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + interface SpawnSyncReturns<T> { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + function spawnSync(command: string): SpawnSyncReturns<Buffer>; + function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>; + function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>; + function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>; + function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>; + function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>; + + interface ExecSyncOptions extends CommonOptions { + input?: string | Buffer | Uint8Array; + stdio?: StdioOptions; + shell?: string; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + function execSync(command: string): Buffer; + function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): Buffer; + + interface ExecFileSyncOptions extends CommonOptions { + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + function execFileSync(command: string): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptions): Buffer; +} diff --git a/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f089a41ebb4df30d9ad4c4140c154679d83a2797 --- /dev/null +++ b/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,260 @@ +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + import * as net from "net"; + + // interfaces + interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv + exec?: string; + args?: string[]; + silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + inspectPort?: number | (() => number); + } + + interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } + + class Worker extends events.EventEmitter { + id: number; + process: child.ChildProcess; + send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + + interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSettings): void; + worker?: Worker; + workers?: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: any): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + } + + function disconnect(callback?: Function): void; + function fork(env?: any): Worker; + const isMaster: boolean; + const isWorker: boolean; + // TODO: cluster.schedulingPolicy + const settings: ClusterSettings; + function setupMaster(settings?: ClusterSettings): void; + const worker: Worker; + const workers: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + function addListener(event: string, listener: (...args: any[]) => void): Cluster; + function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + function emit(event: string | symbol, ...args: any[]): boolean; + function emit(event: "disconnect", worker: Worker): boolean; + function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + function emit(event: "fork", worker: Worker): boolean; + function emit(event: "listening", worker: Worker, address: Address): boolean; + function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + function emit(event: "online", worker: Worker): boolean; + function emit(event: "setup", settings: any): boolean; + + function on(event: string, listener: (...args: any[]) => void): Cluster; + function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function on(event: "fork", listener: (worker: Worker) => void): Cluster; + function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function on(event: "online", listener: (worker: Worker) => void): Cluster; + function on(event: "setup", listener: (settings: any) => void): Cluster; + + function once(event: string, listener: (...args: any[]) => void): Cluster; + function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function once(event: "fork", listener: (worker: Worker) => void): Cluster; + function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function once(event: "online", listener: (worker: Worker) => void): Cluster; + function once(event: "setup", listener: (settings: any) => void): Cluster; + + function removeListener(event: string, listener: (...args: any[]) => void): Cluster; + function removeAllListeners(event?: string): Cluster; + function setMaxListeners(n: number): Cluster; + function getMaxListeners(): number; + function listeners(event: string): Function[]; + function listenerCount(type: string): number; + + function prependListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + function eventNames(): string[]; +} diff --git a/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d30d13f8712d6be1f553024f0a0107900531ad52 --- /dev/null +++ b/node_modules/@types/node/console.d.ts @@ -0,0 +1,3 @@ +declare module "console" { + export = console; +} diff --git a/node_modules/@types/node/constants.d.ts b/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c39d643467ba083e751f9a1d0d397784d7390a5 --- /dev/null +++ b/node_modules/@types/node/constants.d.ts @@ -0,0 +1,279 @@ +declare module "constants" { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + const SIGHUP: number; + const SIGINT: number; + const SIGILL: number; + const SIGABRT: number; + const SIGFPE: number; + const SIGKILL: number; + const SIGSEGV: number; + const SIGTERM: number; + const SIGBREAK: number; + const SIGWINCH: number; + const SSL_OP_ALL: number; + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + const SSL_OP_CISCO_ANYCONNECT: number; + const SSL_OP_COOKIE_EXCHANGE: number; + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + const SSL_OP_EPHEMERAL_RSA: number; + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + const SSL_OP_SINGLE_DH_USE: number; + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_ECDH: number; + const ENGINE_METHOD_ECDSA: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_STORE: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const NPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + const O_RDONLY: number; + const O_WRONLY: number; + const O_RDWR: number; + const S_IFMT: number; + const S_IFREG: number; + const S_IFDIR: number; + const S_IFCHR: number; + const S_IFBLK: number; + const S_IFIFO: number; + const S_IFSOCK: number; + const S_IRWXU: number; + const S_IRUSR: number; + const S_IWUSR: number; + const S_IXUSR: number; + const S_IRWXG: number; + const S_IRGRP: number; + const S_IWGRP: number; + const S_IXGRP: number; + const S_IRWXO: number; + const S_IROTH: number; + const S_IWOTH: number; + const S_IXOTH: number; + const S_IFLNK: number; + const O_CREAT: number; + const O_EXCL: number; + const O_NOCTTY: number; + const O_DIRECTORY: number; + const O_NOATIME: number; + const O_NOFOLLOW: number; + const O_SYNC: number; + const O_DSYNC: number; + const O_SYMLINK: number; + const O_DIRECT: number; + const O_NONBLOCK: number; + const O_TRUNC: number; + const O_APPEND: number; + const F_OK: number; + const R_OK: number; + const W_OK: number; + const X_OK: number; + const COPYFILE_EXCL: number; + const COPYFILE_FICLONE: number; + const COPYFILE_FICLONE_FORCE: number; + const UV_UDP_REUSEADDR: number; + const SIGQUIT: number; + const SIGTRAP: number; + const SIGIOT: number; + const SIGBUS: number; + const SIGUSR1: number; + const SIGUSR2: number; + const SIGPIPE: number; + const SIGALRM: number; + const SIGCHLD: number; + const SIGSTKFLT: number; + const SIGCONT: number; + const SIGSTOP: number; + const SIGTSTP: number; + const SIGTTIN: number; + const SIGTTOU: number; + const SIGURG: number; + const SIGXCPU: number; + const SIGXFSZ: number; + const SIGVTALRM: number; + const SIGPROF: number; + const SIGIO: number; + const SIGPOLL: number; + const SIGPWR: number; + const SIGSYS: number; + const SIGUNUSED: number; + const defaultCoreCipherList: string; + const defaultCipherList: string; + const ENGINE_METHOD_RSA: number; + const ALPN_ENABLED: number; +} diff --git a/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..27bf801c9f9a071531e5bbef88faa41db8d22cc1 --- /dev/null +++ b/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,512 @@ +declare module "crypto" { + import * as stream from "stream"; + + interface Certificate { + exportChallenge(spkac: BinaryLike): Buffer; + exportPublicKey(spkac: BinaryLike): Buffer; + verifySpkac(spkac: Binary): boolean; + } + const Certificate: { + new(): Certificate; + (): Certificate; + }; + + namespace constants { // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + const OPENSSL_VERSION_NUMBER: number; + + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + + const ALPN_ENABLED: number; + + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + + /** @deprecated since v10.0.0 */ + const fips: boolean; + + function createHash(algorithm: string, options?: stream.TransformOptions): Hash; + function createHmac(algorithm: string, key: BinaryLike, options?: stream.TransformOptions): Hmac; + + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + + interface Hash extends NodeJS.ReadWriteStream { + update(data: BinaryLike): Hash; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + interface Hmac extends NodeJS.ReadWriteStream { + update(data: BinaryLike): Hmac; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + + export type KeyObjectType = 'secret' | 'public' | 'private'; + + interface KeyObject { + asymmetricKeyType?: KeyType; + export(options?: { + type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1', + format: KeyFormat, + cipher?: string, + passphrase?: string | Buffer + }): string | Buffer; + symmetricSize?: number; + type: KeyObjectType; + } + + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + + type Binary = Buffer | NodeJS.TypedArray | DataView; + type BinaryLike = string | Binary; + + type CipherKey = BinaryLike | KeyObject; + + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions + ): CipherCCM; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions + ): CipherGCM; + function createCipheriv( + algorithm: string, key: CipherKey, iv: BinaryLike, options?: stream.TransformOptions + ): Cipher; + + interface Cipher extends NodeJS.ReadWriteStream { + update(data: BinaryLike): Buffer; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Binary, output_encoding: HexBase64BinaryEncoding): string; + update(data: Binary, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + // second arg ignored + update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // getAuthTag(): Buffer; + // setAAD(buffer: Buffer): this; // docs only say buffer + } + interface CipherCCM extends Cipher { + setAAD(buffer: Buffer, options: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD(buffer: Buffer, options?: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + + function createDecipheriv( + algorithm: CipherCCMTypes, + key: BinaryLike, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: BinaryLike, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv(algorithm: string, key: BinaryLike, iv: BinaryLike, options?: stream.TransformOptions): Decipher; + + interface Decipher extends NodeJS.ReadWriteStream { + update(data: Binary): Buffer; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Binary, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + // second arg is ignored + update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // setAuthTag(tag: Binary): this; + // setAAD(buffer: Binary): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: Binary): this; + setAAD(buffer: Binary, options: { plaintextLength: number }): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: Binary): this; + setAAD(buffer: Binary, options?: { plaintextLength: number }): this; + } + + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat; + type?: 'pkcs1' | 'pkcs8' | 'sec1'; + passphrase?: string | Buffer; + } + + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat; + type?: 'pkcs1' | 'spki'; + } + + function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject; + function createPublicKey(key: PublicKeyInput | string | Buffer): KeyObject; + function createSecretKey(key: Buffer): KeyObject; + + function createSign(algorithm: string, options?: stream.WritableOptions): Signer; + + interface SignPrivateKeyInput extends PrivateKeyInput { + padding?: number; + saltLength?: number; + } + + type KeyLike = string | Buffer | KeyObject; + + interface Signer extends NodeJS.WritableStream { + update(data: BinaryLike): Signer; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: SignPrivateKeyInput | KeyLike): Buffer; + sign(private_key: SignPrivateKeyInput | KeyLike, output_format: HexBase64Latin1Encoding): string; + } + + function createVerify(algorith: string, options?: stream.WritableOptions): Verify; + interface Verify extends NodeJS.WritableStream { + update(data: BinaryLike): Verify; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: Object | KeyLike, signature: Binary): boolean; + verify(object: Object | KeyLike, signature: string, signature_format: HexBase64Latin1Encoding): boolean; + // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format + // The signature field accepts a TypedArray type, but it is only available starting ES2017 + } + function createDiffieHellman(prime_length: number, generator?: number | Binary): DiffieHellman; + function createDiffieHellman(prime: Binary): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Binary): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; + interface DiffieHellman { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Binary): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Binary, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Binary): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Binary): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; + } + function getDiffieHellman(group_name: string): DiffieHellman; + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => any, + ): void; + function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; + + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + + function randomFillSync<T extends Binary>(buffer: T, offset?: number, size?: number): T; + function randomFill<T extends Binary>(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill<T extends Binary>(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill<T extends Binary>(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + + interface ScryptOptions { + N?: number; + r?: number; + p?: number; + maxmem?: number; + } + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + + interface RsaPublicKey { + key: KeyLike; + padding?: number; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string; + padding?: number; + } + function publicEncrypt(public_key: RsaPublicKey | KeyLike, buffer: Binary): Buffer; + function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: Binary): Buffer; + function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: Binary): Buffer; + function publicDecrypt(public_key: RsaPublicKey | KeyLike, buffer: Binary): Buffer; + function getCiphers(): string[]; + function getCurves(): string[]; + function getHashes(): string[]; + class ECDH { + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: HexBase64Latin1Encoding, + outputEncoding?: "latin1" | "hex" | "base64", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + computeSecret(other_public_key: Binary): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Binary, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + setPrivateKey(private_key: Binary): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + function createECDH(curve_name: string): ECDH; + function timingSafeEqual(a: Binary, b: Binary): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: string; + + export type KeyType = 'rsa' | 'dsa' | 'ec'; + export type KeyFormat = 'pem' | 'der'; + + interface BasePrivateKeyEncodingOptions<T extends KeyFormat> { + format: T; + cipher: string; + passphrase: string; + } + + interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: 'pkcs1' | 'pkcs8'; + }; + } + + interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: 'pkcs8'; + }; + } + + interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { + /** + * Name of the curve to use. + */ + namedCurve: string; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: 'sec1' | 'pkcs8'; + }; + } + + interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> { + publicKey: T1; + privateKey: T2; + } + + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; + + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; + + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; + + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + namespace generateKeyPair { + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + } +} diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..93759406c720b3881ae669e4da97e6c15fd23719 --- /dev/null +++ b/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,102 @@ +declare module "dgram" { + import { AddressInfo } from "net"; + import * as dns from "dns"; + import * as events from "events"; + + interface RemoteInfo { + address: string; + family: 'IPv4' | 'IPv6'; + port: number; + size: number; + } + + interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } + + type SocketType = "udp4" | "udp6"; + + interface SocketOptions { + type: SocketType; + reuseAddr?: boolean; + /** + * @default false + */ + ipv6Only?: boolean; + recvBufferSize?: number; + sendBufferSize?: number; + lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void) => void; + } + + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + class Socket extends events.EventEmitter { + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; + bind(port?: number, callback?: () => void): void; + bind(callback?: () => void): void; + bind(options: BindOptions, callback?: Function): void; + close(callback?: () => void): void; + address(): AddressInfo | string; + setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; + setMulticastTTL(ttl: number): void; + setMulticastInterface(multicastInterface: string): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): this; + unref(): this; + setRecvBufferSize(size: number): void; + setSendBufferSize(size: number): void; + getRecvBufferSize(): number; + getSendBufferSize(): number; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + } +} diff --git a/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a77216f797a60b1ac411bacbc409dddc962b4649 --- /dev/null +++ b/node_modules/@types/node/dns.d.ts @@ -0,0 +1,292 @@ +declare module "dns" { + // Supported getaddrinfo flags. + const ADDRCONFIG: number; + const V4MAPPED: number; + + interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + verbatim?: boolean; + } + + interface LookupOneOptions extends LookupOptions { + all?: false; + } + + interface LookupAllOptions extends LookupOptions { + all: true; + } + + interface LookupAddress { + address: string; + family: number; + } + + function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise<{ address: LookupAddress[] }>; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<{ address: string, family: number }>; + function __promisify__(hostname: string, options?: LookupOptions | number): Promise<{ address: string | LookupAddress[], family?: number }>; + } + + function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException, hostname: string, service: string) => void): void; + + namespace lookupService { + function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; + } + + interface ResolveOptions { + ttl: boolean; + } + + interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + + interface RecordWithTtl { + address: string; + ttl: number; + } + + /** @deprecated Use AnyARecord or AnyAaaaRecord instead. */ + type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + + interface AnyARecord extends RecordWithTtl { + type: "A"; + } + + interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + + interface MxRecord { + priority: number; + exchange: string; + } + + interface AnyMxRecord extends MxRecord { + type: "MX"; + } + + interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + + interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + + interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + + interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + + interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + + interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + + interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + + interface AnyNsRecord { + type: "NS"; + value: string; + } + + interface AnyPtrRecord { + type: "PTR"; + value: string; + } + + interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + + type AnyRecord = AnyARecord | + AnyAaaaRecord | + AnyCnameRecord | + AnyMxRecord | + AnyNaptrRecord | + AnyNsRecord | + AnyPtrRecord | + AnySoaRecord | + AnySrvRecord | + AnyTxtRecord; + + function resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException, addresses: SoaRecord) => void): void; + function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>; + function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>; + function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>; + function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>; + function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>; + function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>; + function __promisify__(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>; + } + + function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve4 { + function __promisify__(hostname: string): Promise<string[]>; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; + function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>; + } + + function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve6 { + function __promisify__(hostname: string): Promise<string[]>; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; + function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>; + } + + function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolveCname { + function __promisify__(hostname: string): Promise<string[]>; + } + + function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + namespace resolveMx { + function __promisify__(hostname: string): Promise<MxRecord[]>; + } + + function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + namespace resolveNaptr { + function __promisify__(hostname: string): Promise<NaptrRecord[]>; + } + + function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolveNs { + function __promisify__(hostname: string): Promise<string[]>; + } + + function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolvePtr { + function __promisify__(hostname: string): Promise<string[]>; + } + + function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; + namespace resolveSoa { + function __promisify__(hostname: string): Promise<SoaRecord>; + } + + function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + namespace resolveSrv { + function __promisify__(hostname: string): Promise<SrvRecord[]>; + } + + function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + namespace resolveTxt { + function __promisify__(hostname: string): Promise<string[][]>; + } + + function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + namespace resolveAny { + function __promisify__(hostname: string): Promise<AnyRecord[]>; + } + + function reverse(ip: string, callback: (err: NodeJS.ErrnoException, hostnames: string[]) => void): void; + function setServers(servers: string[]): void; + function getServers(): string[]; + + // Error codes + const NODATA: string; + const FORMERR: string; + const SERVFAIL: string; + const NOTFOUND: string; + const NOTIMP: string; + const REFUSED: string; + const BADQUERY: string; + const BADNAME: string; + const BADFAMILY: string; + const BADRESP: string; + const CONNREFUSED: string; + const TIMEOUT: string; + const EOF: string; + const FILE: string; + const NOMEM: string; + const DESTRUCTION: string; + const BADSTR: string; + const BADFLAGS: string; + const NONAME: string; + const BADHINTS: string; + const NOTINITIALIZED: string; + const LOADIPHLPAPI: string; + const ADDRGETNETWORKPARAMS: string; + const CANCELLED: string; + + class Resolver { + getServers: typeof getServers; + setServers: typeof setServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + cancel(): void; + } +} diff --git a/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a30decfa56d7a8106297b62590a734d411e111c --- /dev/null +++ b/node_modules/@types/node/domain.d.ts @@ -0,0 +1,16 @@ +declare module "domain" { + import * as events from "events"; + + class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + members: any[]; + enter(): void; + exit(): void; + } + + function create(): Domain; +} diff --git a/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd0d8d191b5352d12932121ef049b49aecd45a54 --- /dev/null +++ b/node_modules/@types/node/events.d.ts @@ -0,0 +1,29 @@ +declare module "events" { + class internal extends NodeJS.EventEmitter { } + + namespace internal { + class EventEmitter extends internal { + /** @deprecated since v4.0.0 */ + static listenerCount(emitter: EventEmitter, event: string | symbol): number; + static defaultMaxListeners: number; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): Array<string | symbol>; + listenerCount(type: string | symbol): number; + } + } + + export = internal; +} diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..105ce920364f9fb959e079058b94b8ef5c0bd8f3 --- /dev/null +++ b/node_modules/@types/node/fs.d.ts @@ -0,0 +1,2272 @@ +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + import { URL } from "url"; + + /** + * Valid types for path values in "fs". + */ + type PathLike = string | Buffer | URL; + + type BinaryData = Buffer | DataView | NodeJS.TypedArray; + class Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atimeMs: number; + mtimeMs: number; + ctimeMs: number; + birthtimeMs: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + + class ReadStream extends stream.Readable { + close(): void; + bytesRead: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + class WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise<void>; + } + + /** + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function truncate(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise<void>; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(fd: number, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise<void>; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise<void>; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise<void>; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise<void>; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise<void>; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: string | number): Promise<void>; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmodSync(fd: number, mode: string | number): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise<void>; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise<Stats>; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function statSync(path: PathLike): Stats; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise<Stats>; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstatSync(fd: number): Stats; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise<Stats>; + } + + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstatSync(path: PathLike): Stats; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise<void>; + } + + /** + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function linkSync(existingPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + function symlink(target: PathLike, path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise<void>; + + type Type = "dir" | "file" | "junction"; + } + + /** + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, linkString: Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string | Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + + function native(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + namespace realpathSync { + function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + } + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise<void>; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlinkSync(path: PathLike): void; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise<void>; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdirSync(path: PathLike): void; + + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777. + */ + mode?: number; + } + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function mkdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise<void>; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException, files: string[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, + callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: { withFileTypes: true }, callback: (err: NodeJS.ErrnoException, files: Dirent[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise<string[]>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise<Buffer[]>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise<string[] | Buffer[]>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__(path: PathLike, options: { withFileTypes: true }): Promise<Dirent[]>; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdirSync(path: PathLike, options: { withFileTypes: true }): Dirent[]; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise<void>; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function closeSync(fd: number): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise<number>; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise<void>; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise<void>; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise<void>; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsyncSync(fd: number): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write<TBuffer extends BinaryData>( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + function write<TBuffer extends BinaryData>( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + function write<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + function write<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write( + fd: number, + string: any, + position: number | undefined | null, + encoding: string | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, str: string) => void, + ): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + */ + function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__<TBuffer extends BinaryData>( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function writeSync(fd: number, buffer: BinaryData, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function read<TBuffer extends BinaryData>( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function readSync(fd: number, buffer: BinaryData, offset: number, length: number, position: number | null): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | number, + options: { encoding?: string | null; flag?: string; } | string | undefined | null, + callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise<Buffer>; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise<string>; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise<string | Buffer>; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; + + type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise<void>; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise<void>; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, + listener?: (event: string, filename: string) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, + listener?: (event: string, filename: string | Buffer) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise<boolean>; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function existsSync(path: PathLike): boolean; + + namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + + // File Copy Constants + + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode: number | undefined, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise<void>; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function accessSync(path: PathLike, mode?: number): void; + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createReadStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + highWaterMark?: number; + }): ReadStream; + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createWriteStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + }): WriteStream; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise<void>; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasyncSync(fd: number): void; + + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + */ + function copyFile(src: PathLike, dest: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace copyFile { + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, + * which causes the copy operation to fail if dest already exists. + */ + function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise<void>; + } + + /** + * Synchronously copies src to dest. By default, dest is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; + + namespace promises { + interface FileHandle { + /** + * Gets the file descriptor for this file handle. + */ + readonly fd: number; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for appending. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise<void>; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + */ + chown(uid: number, gid: number): Promise<void>; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + chmod(mode: string | number): Promise<void>; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + */ + datasync(): Promise<void>; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + */ + sync(): Promise<void>; + + /** + * Asynchronously reads data from the file. + * The `FileHandle` must have been opened for reading. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + read<TBuffer extends Buffer | Uint8Array>(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: null, flag?: string | number } | null): Promise<Buffer>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise<string>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise<string | Buffer>; + + /** + * Asynchronous fstat(2) - Get file status. + */ + stat(): Promise<Stats>; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param len If not specified, defaults to `0`. + */ + truncate(len?: number): Promise<void>; + + /** + * Asynchronously change file timestamps of the file. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise<void>; + + /** + * Asynchronously writes `buffer` to the file. + * The `FileHandle` must have been opened for writing. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + write<TBuffer extends Buffer | Uint8Array>(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise<void>; + + /** + * Asynchronous close(2) - close a `FileHandle`. + */ + close(): Promise<void>; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode?: number): Promise<void>; + + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only + * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if + * `dest` already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise<void>; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not + * supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode?: string | number): Promise<FileHandle>; + + /** + * Asynchronously reads data from the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If + * `null`, data will be read from the current position. + */ + function read<TBuffer extends Buffer | Uint8Array>( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write<TBuffer extends Buffer | Uint8Array>( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise<void>; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len?: number): Promise<void>; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param handle A `FileHandle`. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(handle: FileHandle, len?: number): Promise<void>; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike): Promise<void>; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param handle A `FileHandle`. + */ + function fdatasync(handle: FileHandle): Promise<void>; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param handle A `FileHandle`. + */ + function fsync(handle: FileHandle): Promise<void>; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise<void>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string[]>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer[]>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string[] | Buffer[]>; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise<void>; + + /** + * Asynchronous fstat(2) - Get file status. + * @param handle A `FileHandle`. + */ + function fstat(handle: FileHandle): Promise<Stats>; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike): Promise<Stats>; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike): Promise<Stats>; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise<void>; + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike): Promise<void>; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param handle A `FileHandle`. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(handle: FileHandle, mode: string | number): Promise<void>; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number): Promise<void>; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number): Promise<void>; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise<void>; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param handle A `FileHandle`. + */ + function fchown(handle: FileHandle, uid: number, gid: number): Promise<void>; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number): Promise<void>; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise<void>; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise<void>; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise<void>; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise<void>; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise<Buffer>; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise<string>; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise<string | Buffer>; + } +} diff --git a/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd7d67bbdfebdcd160221b8128398a066b27d001 --- /dev/null +++ b/node_modules/@types/node/globals.d.ts @@ -0,0 +1,1028 @@ +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * The console.markTimeline() method is the deprecated form of console.timeStamp(). + * + * @deprecated Use console.timeStamp() instead. + */ + markTimeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timeline() method is the deprecated form of console.time(). + * + * @deprecated Use console.time() instead. + */ + timeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timelineEnd() method is the deprecated form of console.timeEnd(). + * + * @deprecated Use console.timeEnd() instead. + */ + timelineEnd(label?: string): void; +} + +interface Error { + stack?: string; +} + +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +interface SymbolConstructor { + readonly observable: symbol; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise<void>; + function __promisify__<T>(ms: number, value: T): Promise<T>; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise<void>; + function __promisify__<T>(value: T): Promise<T>; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +/** + * @experimental + */ +declare function queueMicrotask(callback: () => void): void; + +// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. +interface NodeRequireFunction { + /* tslint:disable-next-line:callable-types */ + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve: RequireResolve; + cache: any; + /** + * @deprecated + */ + extensions: NodeExtensions; + main: NodeModule | undefined; +} + +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + +interface NodeExtensions { + '.js': (m: NodeModule, filename: string) => any; + '.json': (m: NodeModule, filename: string) => any; + '.node': (m: NodeModule, filename: string) => any; + [ext: string]: (m: NodeModule, filename: string) => any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: NodeModule | null; + children: NodeModule[]; + paths: string[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; +interface Buffer extends Uint8Array { + constructor: typeof Buffer; + write(string: string, encoding?: string): number; + write(string: string, offset: number, encoding?: string): number; + write(string: string, offset: number, length: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: number[] }; + equals(otherBuffer: Uint8Array): boolean; + compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number): number; + writeUIntBE(value: number, offset: number, byteLength: number): number; + writeIntLE(value: number, offset: number, byteLength: number): number; + writeIntBE(value: number, offset: number, byteLength: number): number; + readUIntLE(offset: number, byteLength: number): number; + readUIntBE(offset: number, byteLength: number): number; + readIntLE(offset: number, byteLength: number): number; + readIntBE(offset: number, byteLength: number): number; + readUInt8(offset: number): number; + readUInt16LE(offset: number): number; + readUInt16BE(offset: number): number; + readUInt32LE(offset: number): number; + readUInt32BE(offset: number): number; + readInt8(offset: number): number; + readInt16LE(offset: number): number; + readInt16BE(offset: number): number; + readInt32LE(offset: number): number; + readInt32BE(offset: number): number; + readFloatLE(offset: number): number; + readFloatBE(offset: number): number; + readDoubleLE(offset: number): number; + readDoubleBE(offset: number): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number): number; + writeUInt16LE(value: number, offset: number): number; + writeUInt16BE(value: number, offset: number): number; + writeUInt32LE(value: number, offset: number): number; + writeUInt32BE(value: number, offset: number): number; + writeInt8(value: number, offset: number): number; + writeInt16LE(value: number, offset: number): number; + writeInt16BE(value: number, offset: number): number; + writeInt32LE(value: number, offset: number): number; + writeInt32BE(value: number, offset: number): number; + writeFloatLE(value: number, offset: number): number; + writeFloatBE(value: number, offset: number): number; + writeDoubleLE(value: number, offset: number): number; + writeDoubleBE(value: number, offset: number): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator<number>; + values(): IterableIterator<number>; +} + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare const Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + prototype: Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() + */ + from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: any[]): Buffer; + from(data: Uint8Array): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from(str: string, encoding?: string): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean | undefined; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + poolSize: number; +}; + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean; + showHidden?: boolean; + /** + * @default 2 + */ + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + breakLength?: number; + compact?: boolean; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; + inspectOptions?: InspectOptions; + } + + interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + class EventEmitter { + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(type: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array<string | symbol>; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe<T extends WritableStream>(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface Events extends EventEmitter { } + + interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise<any>) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: any, promise: Promise<any>) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise<any>, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + interface ProcessEnv { + [key: string]: string | undefined; + } + + interface WriteStream extends Socket { + readonly writableHighWaterMark: number; + readonly writableLength: number; + columns?: number; + rows?: number; + _write(chunk: any, encoding: string, callback: Function): void; + _destroy(err: Error | null, callback: Function): void; + _final(callback: Function): void; + setDefaultEncoding(encoding: string): this; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + } + interface ReadStream extends Socket { + readonly readableHighWaterMark: number; + readonly readableLength: number; + isRaw?: boolean; + setRawMode?(mode: boolean): void; + _read(size: number): void; + _destroy(err: Error | null, callback: Function): void; + push(chunk: any, encoding?: string): boolean; + destroy(error?: Error): void; + } + + interface Process extends EventEmitter { + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ + stdout: WriteStream; + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ + stderr: WriteStream; + stdin: ReadStream; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array<string | number>): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + version: string; + versions: ProcessVersions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + ppid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + /** + * Can only be set if not in worker thread. + */ + umask(mask?: number): number; + uptime(): number; + hrtime(time?: [number, number]): [number, number]; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet<string>; + + /** + * EventEmitter + * 1. beforeExit + * 2. disconnect + * 3. exit + * 4. message + * 5. rejectionHandled + * 6. uncaughtException + * 7. unhandledRejection + * 8. warning + * 9. message + * 10. <All OS Signals> + * 11. newListener/removeListener inherited from EventEmitter + */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise<any>): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise<any>): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + queueMicrotask: typeof queueMicrotask; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + interface Timer { + ref(): void; + refresh(): void; + unref(): void; + } + + class Immediate { + ref(): void; + unref(): void; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + class Timeout implements Timer { + ref(): void; + refresh(): void; + unref(): void; + } + + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequireFromPath(path: string): (path: string) => any; + static builtinModules: string[]; + + static Module: typeof Module; + + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: Module | null; + children: Module[]; + paths: string[]; + + constructor(id: string, parent?: Module); + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; +} diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2557963a0692de7cb3ba94d50f8ef0e0336be94 --- /dev/null +++ b/node_modules/@types/node/http.d.ts @@ -0,0 +1,267 @@ +declare module "http" { + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; + import { URL } from "url"; + + // incoming headers will never contain number + interface IncomingHttpHeaders { + 'accept'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'authorization'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'cookie'?: string; + 'date'?: string; + 'expect'?: string; + 'expires'?: string; + 'forwarded'?: string; + 'from'?: string; + 'host'?: string; + 'if-match'?: string; + 'if-modified-since'?: string; + 'if-none-match'?: string; + 'if-unmodified-since'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'proxy-authorization'?: string; + 'public-key-pins'?: string; + 'range'?: string; + 'referer'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'tk'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'upgrade'?: string; + 'user-agent'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + + interface ClientRequestArgs { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number | string; + defaultPort?: number | string; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: OutgoingHttpHeaders; + auth?: string; + agent?: Agent | boolean; + _defaultAgent?: Agent; + timeout?: number; + setHost?: boolean; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: net.Socket) => void) => net.Socket; + } + + interface ServerOptions { + IncomingMessage?: typeof IncomingMessage; + ServerResponse?: typeof ServerResponse; + } + + type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; + + class Server extends net.Server { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + maxHeadersCount: number; + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP headers. + * @default 40000 + */ + headersTimeout: number; + keepAliveTimeout: number; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js + class OutgoingMessage extends stream.Writable { + upgrading: boolean; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + finished: boolean; + headersSent: boolean; + connection: net.Socket; + + constructor(); + + setTimeout(msecs: number, callback?: () => void): this; + setHeader(name: string, value: number | string | string[]): void; + getHeader(name: string): number | string | string[] | undefined; + getHeaders(): OutgoingHttpHeaders; + getHeaderNames(): string[]; + hasHeader(name: string): boolean; + removeHeader(name: string): void; + addTrailers(headers: OutgoingHttpHeaders | Array<[string, string]>): void; + flushHeaders(): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 + class ServerResponse extends OutgoingMessage { + statusCode: number; + statusMessage: string; + + constructor(req: IncomingMessage); + + assignSocket(socket: net.Socket): void; + detachSocket(socket: net.Socket): void; + // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 + // no args in writeContinue callback + writeContinue(callback?: () => void): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 + class ClientRequest extends OutgoingMessage { + connection: net.Socket; + socket: net.Socket; + aborted: number; + + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + + abort(): void; + onSocket(socket: net.Socket): void; + setTimeout(timeout: number, callback?: () => void): this; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + } + + class IncomingMessage extends stream.Readable { + constructor(socket: net.Socket); + + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + connection: net.Socket; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + trailers: { [key: string]: string | undefined }; + rawTrailers: string[]; + setTimeout(msecs: number, callback: () => void): this; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + destroy(error?: Error): void; + } + + interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number; + } + + class Agent { + maxFreeSockets: number; + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + const METHODS: string[]; + + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + + function createServer(requestListener?: RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: RequestListener): Server; + function createClient(port?: number, host?: string): any; + + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs { } + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; + + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 8KB. Configurable using the [`--max-http-header-size`][] CLI option. + */ + const maxHeaderSize: number; +} diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aecbca783faeadbae1efeda00c319ca3d74ded3a --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,861 @@ +declare module "http2" { + import * as events from "events"; + import * as fs from "fs"; + import * as net from "net"; + import * as stream from "stream"; + import * as tls from "tls"; + import * as url from "url"; + + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; + export { OutgoingHttpHeaders } from "http"; + + export interface IncomingHttpStatusHeader { + ":status"?: number; + } + + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string; + ":method"?: string; + ":authority"?: string; + ":scheme"?: string; + } + + // Http2Stream + + export interface StreamPriorityOptions { + exclusive?: boolean; + parent?: number; + weight?: number; + silent?: boolean; + } + + export interface StreamState { + localWindowSize?: number; + state?: number; + streamLocalClose?: number; + streamRemoteClose?: number; + sumDependencyWeight?: number; + weight?: number; + } + + export interface ServerStreamResponseOptions { + endStream?: boolean; + waitForTrailers?: boolean; + } + + export interface StatOptions { + offset: number; + length: number; + } + + export interface ServerStreamFileResponseOptions { + statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; + getTrailers?: (trailers: OutgoingHttpHeaders) => void; + offset?: number; + length?: number; + } + + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: (err: NodeJS.ErrnoException) => void; + } + + export interface Http2Stream extends stream.Duplex { + readonly aborted: boolean; + readonly closed: boolean; + readonly destroyed: boolean; + readonly pending: boolean; + readonly rstCode: number; + readonly sentHeaders: OutgoingHttpHeaders; + readonly sentInfoHeaders?: OutgoingHttpHeaders[]; + readonly sentTrailers?: OutgoingHttpHeaders; + readonly session: Http2Session; + readonly state: StreamState; + /** + * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, + * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. + */ + readonly endAfterHeaders: boolean; + close(code?: number, callback?: () => void): void; + priority(options: StreamPriorityOptions): void; + setTimeout(msecs: number, callback?: () => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + + sendTrailers(headers: OutgoingHttpHeaders): this; + } + + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + } + + export interface ServerHttp2Stream extends Http2Stream { + additionalHeaders(headers: OutgoingHttpHeaders): void; + readonly headersSent: boolean; + readonly pushAllowed: boolean; + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + respondWithFD(fd: number, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + + // Http2Session + + export interface Settings { + headerTableSize?: number; + enablePush?: boolean; + initialWindowSize?: number; + maxFrameSize?: number; + maxConcurrentStreams?: number; + maxHeaderListSize?: number; + } + + export interface ClientSessionRequestOptions { + endStream?: boolean; + exclusive?: boolean; + parent?: number; + weight?: number; + getTrailers?: (trailers: OutgoingHttpHeaders, flags: number) => void; + } + + export interface SessionState { + effectiveLocalWindowSize?: number; + effectiveRecvDataLength?: number; + nextStreamID?: number; + localWindowSize?: number; + lastProcStreamID?: number; + remoteWindowSize?: number; + outboundQueueSize?: number; + deflateDynamicTableSize?: number; + inflateDynamicTableSize?: number; + } + + export interface Http2Session extends events.EventEmitter { + readonly alpnProtocol?: string; + close(callback?: () => void): void; + readonly closed: boolean; + readonly connecting: boolean; + destroy(error?: Error, code?: number): void; + readonly destroyed: boolean; + readonly encrypted?: boolean; + goaway(code?: number, lastStreamID?: number, opaqueData?: Buffer | DataView | NodeJS.TypedArray): void; + readonly localSettings: Settings; + readonly originSet?: string[]; + readonly pendingSettingsAck: boolean; + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ref(): void; + readonly remoteSettings: Settings; + rstStream(stream: Http2Stream, code?: number): void; + setTimeout(msecs: number, callback?: () => void): void; + readonly socket: net.Socket | tls.TLSSocket; + readonly state: SessionState; + priority(stream: Http2Stream, options: StreamPriorityOptions): void; + settings(settings: Settings): void; + readonly type: number; + unref(): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "ping", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: "ping"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "ping", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "ping", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "ping", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + } + + export interface ClientHttp2Session extends Http2Session { + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + } + + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + + export interface ServerHttp2Session extends Http2Session { + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + readonly server: Http2Server | Http2SecureServer; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + } + + // Http2Server + + export interface SessionOptions { + maxDeflateDynamicTableSize?: number; + maxReservedRemoteStreams?: number; + maxSendHeaderBlockLength?: number; + paddingStrategy?: number; + peerMaxConcurrentStreams?: number; + selectPadding?: (frameLen: number, maxFrameLen: number) => number; + settings?: Settings; + createConnection?: (option: SessionOptions) => stream.Duplex; + } + + export type ClientSessionOptions = SessionOptions; + export type ServerSessionOptions = SessionOptions; + + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } + + export interface ServerOptions extends ServerSessionOptions { + allowHTTP1?: boolean; + } + + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean; + } + + export interface Http2Server extends net.Server { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + export interface Http2SecureServer extends tls.Server { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + } + + export class Http2ServerRequest extends stream.Readable { + private constructor(); + headers: IncomingHttpHeaders; + httpVersion: string; + method: string; + rawHeaders: string[]; + rawTrailers: string[]; + setTimeout(msecs: number, callback?: () => void): void; + socket: net.Socket | tls.TLSSocket; + stream: ServerHttp2Stream; + trailers: IncomingHttpHeaders; + url: string; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted", hadError: boolean, code: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + } + + export class Http2ServerResponse extends events.EventEmitter { + private constructor(); + addTrailers(trailers: OutgoingHttpHeaders): void; + connection: net.Socket | tls.TLSSocket; + end(callback?: () => void): void; + end(data?: string | Buffer, callback?: () => void): void; + end(data?: string | Buffer, encoding?: string, callback?: () => void): void; + readonly finished: boolean; + getHeader(name: string): string; + getHeaderNames(): string[]; + getHeaders(): OutgoingHttpHeaders; + hasHeader(name: string): boolean; + readonly headersSent: boolean; + removeHeader(name: string): void; + sendDate: boolean; + setHeader(name: string, value: number | string | string[]): void; + setTimeout(msecs: number, callback?: () => void): void; + socket: net.Socket | tls.TLSSocket; + statusCode: number; + statusMessage: ''; + stream: ServerHttp2Stream; + write(chunk: string | Buffer, callback?: (err: Error) => void): boolean; + write(chunk: string | Buffer, encoding?: string, callback?: (err: Error) => void): boolean; + writeContinue(): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): void; + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + } + + // Public API + + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + + export function getDefaultSettings(): Settings; + export function getPackedSettings(settings: Settings): Settings; + export function getUnpackedSettings(buf: Buffer | Uint8Array): Settings; + + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + + export function connect(authority: string | url.URL, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; +} diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c7064f4dfd71cc0d428c34ef5cb2a577f9dc1f0 --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,39 @@ +declare module "https" { + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + import { URL } from "url"; + + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + + type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { + rejectUnauthorized?: boolean; // Defaults to true + servername?: string; // SNI TLS Extension + }; + + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean; + maxCachedSessions?: number; + } + + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + + class Server extends tls.Server { + constructor(options: ServerOptions, requestListener?: http.RequestListener); + + setTimeout(callback: () => void): this; + setTimeout(msecs?: number, callback?: () => void): this; + timeout: number; + keepAliveTimeout: number; + } + + function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server; + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39db1d52fa3801d9f3a6933a85b6191de9ef5ec3 --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,88 @@ +// Type definitions for non-npm package Node.js 11.9 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript <https://github.com/Microsoft> +// DefinitelyTyped <https://github.com/DefinitelyTyped> +// Alberto Schiabel <https://github.com/jkomyno> +// Alexander T. <https://github.com/a-tarasyuk> +// Alvis HT Tang <https://github.com/alvis> +// Andrew Makarov <https://github.com/r3nya> +// Benjamin Toueg <https://github.com/btoueg> +// Bruno Scheufler <https://github.com/brunoscheufler> +// Chigozirim C. <https://github.com/smac89> +// Christian Vaagland Tellnes <https://github.com/tellnes> +// David Junger <https://github.com/touffy> +// Deividas Bakanas <https://github.com/DeividasBakanas> +// Eugene Y. Q. Shen <https://github.com/eyqs> +// Flarna <https://github.com/Flarna> +// Hannes Magnusson <https://github.com/Hannes-Magnusson-CK> +// Hoàng Văn Khải <https://github.com/KSXGitHub> +// Huw <https://github.com/hoo29> +// Kelvin Jin <https://github.com/kjin> +// Klaus Meinhardt <https://github.com/ajafff> +// Lishude <https://github.com/islishude> +// Mariusz Wiktorczyk <https://github.com/mwiktorczyk> +// Matthieu Sieben <https://github.com/matthieusieben> +// Mohsen Azimi <https://github.com/mohsen1> +// Nicolas Even <https://github.com/n-e> +// Nicolas Voigt <https://github.com/octo-sniffle> +// Parambir Singh <https://github.com/parambirs> +// Sebastian Silbermann <https://github.com/eps1lon> +// Simon Schick <https://github.com/SimonSchick> +// Thomas den Hollander <https://github.com/ThomasdenH> +// Wilco Bakker <https://github.com/WilcoBakker> +// wwwy3y3 <https://github.com/wwwy3y3> +// Zane Hannan AU <https://github.com/ZaneHannanAU> +// Jeremie Rodriguez <https://github.com/jeremiergz> +// Samuel Ainsworth <https://github.com/samuela> +// Kyle Uehlein <https://github.com/kuehlein> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NOTE: These definitions support NodeJS and TypeScript 3.1. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 + +// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides +// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.1, so the older definitions will be found here. + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// <reference path="base.d.ts" /> + +// TypeScript 2.1-specific augmentations: + +// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } +interface Set<T> {} +interface ReadonlySet<T> {} +interface IteratorResult<T> { } +interface Iterable<T> { } +interface Iterator<T> { + next(value?: any): IteratorResult<T>; +} +interface IterableIterator<T> { } +interface AsyncIterableIterator<T> {} +interface SymbolConstructor { + readonly iterator: symbol; + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +declare class SharedArrayBuffer { + constructor(byteSize: number); + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +declare module "util" { + namespace inspect { + const custom: symbol; + } + namespace promisify { + const custom: symbol; + } +} diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2dcd2760addda6e02121ec6c9ab438077b71be58 --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,3162 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module "inspector" { + import { EventEmitter } from 'events'; + + interface InspectorNotification<T> { + method: string; + params: T; + } + + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number; + } + + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + + /** + * Call frame identifier. + */ + type CallFrameId = string; + + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the `Debugger.scriptParsed`. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + } + + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * `this` object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject; + } + + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For `global` and `with` scopes it represents the actual + * object; for the rest of the scopes, it is artificial transient object enumerating scope + * variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string; + /** + * Location in the source code where scope starts + */ + startLocation?: Location; + /** + * Location in the source code where scope ends + */ + endLocation?: Location; + } + + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + + interface BreakLocation { + /** + * Script identifier as reported in the `Debugger.scriptParsed`. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + type?: string; + } + + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string; + } + + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles + * using `releaseObjectGroup`). + */ + objectGroup?: string; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults + * to false. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean; + /** + * Terminate execution after timing out (number of milliseconds). + * @experimental + */ + timeout?: Runtime.TimeDelta; + } + + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end + * of scripts is used as end of range. + */ + end?: Location; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean; + } + + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean; + } + + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async + * call stacks (default). + */ + maxDepth: number; + } + + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the + * breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either `url` or + * `urlRegex` must be specified. + */ + urlRegex?: string; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the + * breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointOnFunctionCallParameterType { + /** + * Function object id. + */ + objectId: Runtime.RemoteObjectId; + /** + * Expression to use as a breakpoint condition. When specified, debugger will + * stop on the breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result + * description without actually modifying the code. + */ + dryRun?: boolean; + } + + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' + * scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled + * before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean; + } + + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + } + + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + + interface SetBreakpointOnFunctionCallReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + } + + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[]; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {}; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. + * This field is available only after `Debugger.stepInto` call with `breakOnAsynCall` flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId; + } + + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + } + + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + } + + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The + * default value is 32768 bytes. + */ + samplingInterval?: number; + } + + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean; + } + + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken + * when the tracking is stopped. + */ + reportProgress?: boolean; + } + + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean; + } + + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment + * index, the second integer is a total count of objects for the fragment, the third integer is + * a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean; + } + } + + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number; + /** + * Child node ids. + */ + children?: number[]; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't + * optimize. + */ + deoptReason?: string; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[]; + } + + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[]; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the + * profile startTime. + */ + timeDeltas?: number[]; + } + + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean; + /** + * Collect block-based coverage. + */ + detailed?: boolean; + } + + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + } + + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + + /** + * Primitive value which cannot be JSON-stringified. Includes values `-0`, `NaN`, `Infinity`, + * `-Infinity`, and bigint literals. + */ + type UnserializableValue = string; + + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + /** + * Object class (constructor) name. Specified for `object` type values only. + */ + className?: string; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have `value`, but gets this + * property. + */ + unserializableValue?: UnserializableValue; + /** + * String representation of the object. + */ + description?: string; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId; + /** + * Preview containing abbreviated property values. Specified for `object` type values only. + * @experimental + */ + preview?: ObjectPreview; + /** + * @experimental + */ + customPreview?: CustomPreview; + } + + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId; + } + + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + /** + * String representation of the object. + */ + description?: string; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for `map` and `set` subtype values only. + */ + entries?: EntryPreview[]; + } + + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + } + + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean; + /** + * A function which serves as a getter for the property, or `undefined` if there is no getter + * (accessor descriptors only). + */ + get?: RemoteObject; + /** + * A function which serves as a setter for the property, or `undefined` if there is no setter + * (accessor descriptors only). + */ + set?: RemoteObject; + /** + * True if the type of this property descriptor may be changed and if the property may be + * deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding + * object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean; + /** + * Property symbol object, if the property is of the `symbol` type. + */ + symbol?: RemoteObject; + } + + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject; + } + + /** + * Represents function call argument. Either remote object id `objectId`, primitive `value`, + * unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId; + } + + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context + * script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {}; + } + + /** + * Detailed information about exception (or error) that was thrown during script compilation or + * execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace; + /** + * Exception object if available. + */ + exception?: RemoteObject; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId; + } + + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + + /** + * Number of milliseconds. + */ + type TimeDelta = number; + + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that + * initiated the async call. + */ + description?: string; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId; + } + + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + + /** + * If `debuggerId` is set stack trace comes from another debugger and can be resolved there. This + * allows to track cross-debugger calls. See `Runtime.StackTrace` and `Debugger.paused` for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId; + } + + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + } + + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should + * be specified. + */ + objectId?: RemoteObjectId; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target + * object. + */ + arguments?: CallArgument[]; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + /** + * Specifies execution context which global object will be used to call function on. Either + * executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not + * specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string; + } + + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId; + } + + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + * @experimental + */ + throwOnSideEffect?: boolean; + /** + * Terminate execution after timing out (number of milliseconds). + * @experimental + */ + timeout?: TimeDelta; + } + + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype + * chain. + */ + ownProperties?: boolean; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not + * returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean; + } + + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId; + } + + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + /** + * Symbolic group name that can be used to release the results. + */ + objectGroup?: string; + } + + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + } + + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails; + } + + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface GetIsolateIdReturnType { + /** + * The isolate id. + */ + id: string; + } + + interface GetHeapUsageReturnType { + /** + * Used heap size in bytes. + */ + usedSize: number; + /** + * Allocated heap size in bytes. + */ + totalSize: number; + } + + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[]; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace; + /** + * Console context descriptor for calls on non-default console context (not console.*): + * 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call + * on named context. + * @experimental + */ + context?: string; + } + + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in `exceptionThrown`. + */ + exceptionId: number; + } + + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + + interface StartParameterType { + traceConfig: TraceConfig; + } + + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + + namespace NodeWorker { + type WorkerID = string; + + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + + /** + * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if there is already a connected session established either + * through the API or by a front-end connected to the Inspector WebSocket port. + */ + connect(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * session.connect() will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. callback will be notified when a response is received. + * callback is a function that accepts two optional arguments - error and message-specific result. + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + + /** + * Enables console domain, sends the messages collected so far to the client by means of the + * `messageAdded` notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been + * enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be + * the same. + */ + post( + method: "Debugger.getPossibleBreakpoints", + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + + /** + * Returns stack trace with given `stackTraceId`. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and + * Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled + * before next pause. Returns success when async task is actually scheduled, returns error if no + * task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in + * scripts with url matching one of the patterns. VM will try to leave blackboxed script by + * performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted + * scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * Positions array contains positions where blackbox state is changed. First interval isn't + * blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this + * command is issued, all existing parsed scripts will have breakpoints resolved and returned in + * `locations` property. Further matching script parsing will result in subsequent + * `breakpointResolved` events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + + /** + * Sets JavaScript breakpoint before each call to the given function. + * If another function was created from the same source as a given one, + * calling it will also trigger the breakpoint. + * @experimental + */ + post( + method: "Debugger.setBreakpointOnFunctionCall", + params?: Debugger.SetBreakpointOnFunctionCallParameterType, + callback?: (err: Error | null, params: Debugger.SetBreakpointOnFunctionCallReturnType) => void + ): void; + post(method: "Debugger.setBreakpointOnFunctionCall", callback?: (err: Error | null, params: Debugger.SetBreakpointOnFunctionCallReturnType) => void): void; + + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or + * no exceptions. Initial pause on exceptions state is `none`. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be + * mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details + * $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + + post( + method: "HeapProfiler.getObjectByHeapObjectId", + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to + * garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code + * coverage may be incomplete. Enabling prevents running optimized code and resets execution + * counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Enable type profile. + * @experimental + */ + post(method: "Profiler.startTypeProfile", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows + * executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: "Profiler.stopTypeProfile", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code + * coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + + /** + * Collect type profile. + * @experimental + */ + post(method: "Profiler.takeTypeProfile", callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + + /** + * Calls function with given declaration on the given object. Object group of the result is + * inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + + /** + * Enables reporting of execution contexts creation by means of `executionContextCreated` event. + * When the reporting gets enabled the event will be sent immediately for each existing execution + * context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + + /** + * Returns the isolate id. + * @experimental + */ + post(method: "Runtime.getIsolateId", callback?: (err: Error | null, params: Runtime.GetIsolateIdReturnType) => void): void; + + /** + * Returns the JavaScript heap usage. + * It is the total usage of the corresponding isolate not scoped to a particular Runtime. + * @experimental + */ + post(method: "Runtime.getHeapUsage", callback?: (err: Error | null, params: Runtime.GetHeapUsageReturnType) => void): void; + + /** + * Returns properties of a given object. Object group of the result is inherited from the target + * object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: "Runtime.globalLexicalScopeNames", + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + + /** + * Terminate current or next JavaScript execution. + * Will cancel the termination when the outer-most script execution ends. + * @experimental + */ + post(method: "Runtime.terminateExecution", callback?: (err: Error | null) => void): void; + + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + + // Events + + addListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; + + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; + + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; + + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; + + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; + + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; + + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification<Console.MessageAddedEventDataType>): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>): boolean; + emit(event: "Debugger.paused", message: InspectorNotification<Debugger.PausedEventDataType>): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification<Debugger.ScriptParsedEventDataType>): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification<Runtime.ExceptionThrownEventDataType>): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification<Runtime.InspectRequestedEventDataType>): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification<NodeTracing.DataCollectedEventDataType>): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; + + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; + + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; + + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; + + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; + + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; + + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; + + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; + + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; + + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; + + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; + + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; + + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; + + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; + + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; + + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; + + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; + + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; + + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; + + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; + + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; + + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; + + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; + } + + // Top Level API + + /** + * Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programatically after node has started. + * If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client. + * @param port Port to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Optional, defaults to false. + */ + function open(port?: number, host?: string, wait?: boolean): void; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + + /** + * Return the URL of the active inspector, or undefined if there is none. + */ + function url(): string; +} diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f512be7e5edecf718a85ec03bd4e073b0d58ffa9 --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,3 @@ +declare module "module" { + export = NodeJS.Module; +} diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..33858de8df2b11e3668455e52cf8f03970d46603 --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,255 @@ +declare module "net" { + import * as stream from "stream"; + import * as events from "events"; + import * as dns from "dns"; + + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + interface SocketConstructorOpts { + fd?: number; + allowHalfOpen?: boolean; + readable?: boolean; + writable?: boolean; + } + + interface TcpSocketConnectOpts { + port: number; + host?: string; + localAddress?: string; + localPort?: number; + hints?: number; + family?: number; + lookup?: LookupFunction; + } + + interface IpcSocketConnectOpts { + path: string; + } + + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + write(data: any, encoding?: string, callback?: Function): void; + + connect(options: SocketConnectOpts, connectionListener?: Function): this; + connect(port: number, host: string, connectionListener?: Function): this; + connect(port: number, connectionListener?: Function): this; + connect(path: string, connectionListener?: Function): this; + + setEncoding(encoding?: string): this; + pause(): this; + resume(): this; + setTimeout(timeout: number, callback?: Function): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; + address(): AddressInfo | string; + unref(): void; + ref(): void; + + readonly bufferSize: number; + readonly bytesRead: number; + readonly bytesWritten: number; + readonly connecting: boolean; + readonly destroyed: boolean; + readonly localAddress: string; + readonly localPort: number; + readonly remoteAddress?: string; + readonly remoteFamily?: string; + readonly remotePort?: number; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + readableAll?: boolean; + writableAll?: boolean; + /** + * @default false + */ + ipv6Only?: boolean; + } + + // https://github.com/nodejs/node/blob/master/lib/net.js + class Server extends events.EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); + + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: Function): this; + listen(port?: number, hostname?: string, listeningListener?: Function): this; + listen(port?: number, backlog?: number, listeningListener?: Function): this; + listen(port?: number, listeningListener?: Function): this; + listen(path: string, backlog?: number, listeningListener?: Function): this; + listen(path: string, listeningListener?: Function): this; + listen(options: ListenOptions, listeningListener?: Function): this; + listen(handle: any, backlog?: number, listeningListener?: Function): this; + listen(handle: any, listeningListener?: Function): this; + close(callback?: Function): this; + address(): AddressInfo | string | null; + getConnections(cb: (error: Error | null, count: number) => void): void; + ref(): this; + unref(): this; + maxConnections: number; + connections: number; + listening: boolean; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + } + + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; + function connect(options: NetConnectOpts, connectionListener?: Function): Socket; + function connect(port: number, host?: string, connectionListener?: Function): Socket; + function connect(path: string, connectionListener?: Function): Socket; + function createConnection(options: NetConnectOpts, connectionListener?: Function): Socket; + function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + function createConnection(path: string, connectionListener?: Function): Socket; + function isIP(input: string): number; + function isIPv4(input: string): boolean; + function isIPv6(input: string): boolean; +} diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c85d217f916beee9628b46d1cf77b7a2521616a5 --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,192 @@ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + + function hostname(): string; + function loadavg(): number[]; + function uptime(): number; + function freemem(): number; + function totalmem(): number; + function cpus(): CpuInfo[]; + function type(): string; + function release(): string; + function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + function homedir(): string; + function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string }; + const constants: { + UV_UDP_REUSEADDR: number; + signals: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }; + errno: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }; + priority: { + PRIORITY_LOW: number; + PRIORITY_BELOW_NORMAL: number; + PRIORITY_NORMAL: number; + PRIORITY_ABOVE_NORMAL: number; + PRIORITY_HIGH: number; + PRIORITY_HIGHEST: number; + } + }; + function arch(): string; + function platform(): NodeJS.Platform; + function tmpdir(): string; + const EOL: string; + function endianness(): "BE" | "LE"; + /** + * Gets the priority of a process. + * Defaults to current process. + */ + function getPriority(pid?: number): number; + /** + * Sets the priority of the current process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(priority: number): void; + /** + * Sets the priority of the process specified process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(pid: number, priority: number): void; +} diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4720880793e31ca665cfbaf1e5b330ac380dcfdd --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,195 @@ +{ + "_from": "@types/node@*", + "_id": "@types/node@11.9.4", + "_inBundle": false, + "_integrity": "sha512-Zl8dGvAcEmadgs1tmSPcvwzO1YRsz38bVJQvH1RvRqSR9/5n61Q1ktcDL0ht3FXWR+ZpVmXVwN1LuH4Ax23NsA==", + "_location": "/@types/node", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/node@*", + "name": "@types/node", + "escapedName": "@types%2fnode", + "scope": "@types", + "rawSpec": "*", + "saveSpec": null, + "fetchSpec": "*" + }, + "_requiredBy": [ + "/@types/mysql" + ], + "_resolved": "https://registry.npmjs.org/@types/node/-/node-11.9.4.tgz", + "_shasum": "ceb0048a546db453f6248f2d1d95e937a6f00a14", + "_spec": "@types/node@*", + "_where": "/home/capsule_man/developpement/happy-botday/node_modules/@types/mysql", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft" + }, + { + "name": "DefinitelyTyped", + "url": "https://github.com/DefinitelyTyped" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alexander T.", + "url": "https://github.com/a-tarasyuk" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Bruno Scheufler", + "url": "https://github.com/brunoscheufler" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89" + }, + { + "name": "Christian Vaagland Tellnes", + "url": "https://github.com/tellnes" + }, + { + "name": "David Junger", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs" + }, + { + "name": "Flarna", + "url": "https://github.com/Flarna" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Hoàng Văn Khải", + "url": "https://github.com/KSXGitHub" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Matthieu Sieben", + "url": "https://github.com/matthieusieben" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nicolas Even", + "url": "https://github.com/n-e" + }, + { + "name": "Nicolas Voigt", + "url": "https://github.com/octo-sniffle" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon" + }, + { + "name": "Simon Schick", + "url": "https://github.com/SimonSchick" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Zane Hannan AU", + "url": "https://github.com/ZaneHannanAU" + }, + { + "name": "Jeremie Rodriguez", + "url": "https://github.com/jeremiergz" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "url": "https://github.com/kuehlein" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "TypeScript definitions for non-npm package Node.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/node", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.0", + "types": "index", + "typesPublisherContentHash": "04bbd0bd504157f2cd4bfb56dbb9060df88afaec4c62949aef29d8b9cf64640a", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + }, + "version": "11.9.4" +} diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bbc17098f40c788b8bc4f5b0f38db7440a42ac78 --- /dev/null +++ b/node_modules/@types/node/path.d.ts @@ -0,0 +1,159 @@ +declare module "path" { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string; + /** + * The file extension (if any) such as '.html' + */ + ext?: string; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + function resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + const sep: '\\' | '/'; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + const delimiter: ';' | ':'; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + function format(pathObject: FormatInputPathObject): string; + + namespace posix { + function normalize(p: string): string; + function join(...paths: any[]): string; + function resolve(...pathSegments: any[]): string; + function isAbsolute(p: string): boolean; + function relative(from: string, to: string): string; + function dirname(p: string): string; + function basename(p: string, ext?: string): string; + function extname(p: string): string; + const sep: string; + const delimiter: string; + function parse(p: string): ParsedPath; + function format(pP: FormatInputPathObject): string; + } + + namespace win32 { + function normalize(p: string): string; + function join(...paths: any[]): string; + function resolve(...pathSegments: any[]): string; + function isAbsolute(p: string): boolean; + function relative(from: string, to: string): string; + function dirname(p: string): string; + function basename(p: string, ext?: string): string; + function extname(p: string): string; + const sep: string; + const delimiter: string; + function parse(p: string): ParsedPath; + function format(pP: FormatInputPathObject): string; + } +} diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f68895ce612b72dee3cd38cdadc08abf7c9ef6f --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,241 @@ +declare module "perf_hooks" { + import { AsyncResource } from "async_hooks"; + + interface PerformanceEntry { + /** + * The total number of milliseconds elapsed for this entry. + * This value will not be meaningful for all Performance Entry types. + */ + readonly duration: number; + + /** + * The name of the performance entry. + */ + readonly name: string; + + /** + * The high resolution millisecond timestamp marking the starting time of the Performance Entry. + */ + readonly startTime: number; + + /** + * The type of the performance entry. + * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. + */ + readonly entryType: string; + + /** + * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies + * the type of garbage collection operation that occurred. + * The value may be one of perf_hooks.constants. + */ + readonly kind?: number; + } + + interface PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. + */ + readonly bootstrapComplete: number; + + /** + * The high resolution millisecond timestamp at which cluster processing ended. + */ + readonly clusterSetupEnd: number; + + /** + * The high resolution millisecond timestamp at which cluster processing started. + */ + readonly clusterSetupStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop exited. + */ + readonly loopExit: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop started. + */ + readonly loopStart: number; + + /** + * The high resolution millisecond timestamp at which main module load ended. + */ + readonly moduleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which main module load started. + */ + readonly moduleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + */ + readonly nodeStart: number; + + /** + * The high resolution millisecond timestamp at which preload module load ended. + */ + readonly preloadModuleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which preload module load started. + */ + readonly preloadModuleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing ended. + */ + readonly thirdPartyMainEnd: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing started. + */ + readonly thirdPartyMainStart: number; + + /** + * The high resolution millisecond timestamp at which the V8 platform was initialized. + */ + readonly v8Start: number; + } + + interface Performance { + /** + * If name is not provided, removes all PerformanceFunction objects from the Performance Timeline. + * If name is provided, removes entries with name. + * @param name + */ + clearFunctions(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only objects whose performanceEntry.name matches name. + */ + clearMeasures(name?: string): void; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + * @return list of all PerformanceEntry objects + */ + getEntries(): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + * @param name + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByType(type: string): PerformanceEntry[]; + + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string): void; + + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark: string, endMark: string): void; + + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify<T extends (...optionalParams: any[]) => any>(fn: T): T; + } + + interface PerformanceObserverEntryList { + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + */ + getEntries(): PerformanceEntry[]; + + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + */ + getEntriesByType(type: string): PerformanceEntry[]; + } + + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + + /** + * Disconnects the PerformanceObserver instance from all notifications. + */ + disconnect(): void; + + /** + * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. + * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. + * Property buffered defaults to false. + * @param options + */ + observe(options: { entryTypes: string[], buffered?: boolean }): void; + } + + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + } + + const performance: Performance; +} diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ccd5c9c198efbd1139f588430e46ba02580acb78 --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,3 @@ +declare module "process" { + export = process; +} diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..efc55622f109c9619949fe0459254818d75f24e9 --- /dev/null +++ b/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,12 @@ +declare module "punycode" { + function decode(string: string): string; + function encode(string: string): string; + function toUnicode(domain: string): string; + function toASCII(domain: string): string; + const ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + const version: any; +} diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f54d352c6c76e0b4862ecee44af885bb3af6b2bf --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,17 @@ +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: Function; + } + + interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } + + interface ParsedUrlQuery { [key: string]: string | string[]; } + + function stringify(obj?: {}, sep?: string, eq?: string, options?: StringifyOptions): string; + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + function escape(str: string): string; + function unescape(str: string): string; +} diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..011cf7ad64e87463043cb5043d45bb2c5fa39dac --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,136 @@ +declare module "readline" { + import * as events from "events"; + import * as stream from "stream"; + + interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + + class Interface extends events.EventEmitter { + readonly terminal: boolean; + + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): this; + resume(): this; + close(): void; + write(data: string | Buffer, key?: Key): void; + + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator<string>; + } + + type ReadLine = Interface; // type forwarded for backwards compatiblity + + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err: any, result: CompleterResult) => void) => any; + + type CompleterResult = [string[], string]; + + interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer | AsyncCompleter; + terminal?: boolean; + historySize?: number; + prompt?: string; + crlfDelay?: number; + removeHistoryDuplicates?: boolean; + } + + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; + + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; + function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: Interface): void; + function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + function clearLine(stream: NodeJS.WritableStream, dir: number): void; + function clearScreenDown(stream: NodeJS.WritableStream): void; +} diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb5a3d037bc331977abdd361fe31427a9d8794c5 --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,372 @@ +declare module "repl" { + import { Interface, Completer, AsyncCompleter } from "readline"; + import { Context } from "vm"; + import { InspectOptions } from "util"; + + interface ReplOptions { + /** + * The input prompt to display. + * Default: `"> "` + */ + prompt?: string; + /** + * The `Readable` stream from which REPL input will be read. + * Default: `process.stdin` + */ + input?: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + * Default: `process.stdout` + */ + output?: NodeJS.WritableStream; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean; + } + + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { options: InspectOptions }; + + type REPLCommandAction = (this: REPLServer, text: string) => void; + + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + + /** + * Provides a customizable Read-Eval-Print-Loop (REPL). + * + * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those + * according to a user-defined evaluation function, then output the result. Input and output + * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. + * + * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style + * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session + * state, error recovery, and customizable evaluation functions. + * + * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ + * be created directly using the JavaScript `new` keyword. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: { readonly [name: string]: REPLCommand | undefined }; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + + /** + * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked + * by typing a `.` followed by the `keyword`. + * + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * Readies the REPL instance for input from the user, printing the configured `prompt` to a + * new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * Clears any command that has been buffered but not yet executed. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @since v9.0.0 + */ + clearBufferedCommand(): void; + + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + export const REPL_MODE_SLOPPY: symbol; // TODO: unique symbol + + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + export const REPL_MODE_STRICT: symbol; // TODO: unique symbol + + /** + * Creates and starts a `repl.REPLServer` instance. + * + * @param options The options for the `REPLServer`. If `options` is a string, then it specifies + * the input prompt. + */ + function start(options?: string | ReplOptions): REPLServer; + + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + + constructor(err: Error); + } +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..122ae563c790a8772ed12372536fd19c0ef260b8 --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,294 @@ +declare module "stream" { + import * as events from "events"; + + class internal extends events.EventEmitter { + pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T; + } + + namespace internal { + class Stream extends internal { } + + interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?(this: Readable, size: number): void; + destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; + } + + class Readable extends Stream implements NodeJS.ReadableStream { + readable: boolean; + readonly readableHighWaterMark: number; + readonly readableLength: number; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + unpipe(destination?: NodeJS.WritableStream): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: string): boolean; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + [Symbol.asyncIterator](): AsyncIterableIterator<any>; + } + + interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Writable, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + + class Writable extends Stream implements NodeJS.WritableStream { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + + // Note: Duplex extends both Readable and Writable. + class Duplex extends Readable implements Writable { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + } + + type TransformCallback = (error?: Error | null, data?: any) => void; + + interface TransformOptions extends DuplexOptions { + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Transform, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: string, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + + class PassThrough extends Transform { } + + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream): Promise<void>; + } + + function pipeline<T extends NodeJS.WritableStream>(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException) => void): T; + function pipeline<T extends NodeJS.WritableStream>(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException) => void): T; + function pipeline<T extends NodeJS.WritableStream>( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: T, + callback?: (err: NodeJS.ErrnoException) => void, + ): T; + function pipeline<T extends NodeJS.WritableStream>( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: T, + callback?: (err: NodeJS.ErrnoException) => void, + ): T; + function pipeline(streams: Array<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>, callback?: (err: NodeJS.ErrnoException) => void): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException) => void)>, + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.WritableStream): Promise<void>; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.WritableStream): Promise<void>; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.WritableStream): Promise<void>; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: NodeJS.WritableStream, + ): Promise<void>; + function __promisify__(streams: Array<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>): Promise<void>; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream>, + ): Promise<void>; + } + } + + export = internal; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..762a4d8d5064d4662100f94cab396041e310969d --- /dev/null +++ b/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,9 @@ +declare module "string_decoder" { + interface NodeStringDecoder { + write(buffer: Buffer): string; + end(buffer?: Buffer): string; + } + const StringDecoder: { + new(encoding?: string): NodeStringDecoder; + }; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e64a6735c3a4f130d4a879186ce0f4effe7c08fd --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,16 @@ +declare module "timers" { + function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + namespace setTimeout { + function __promisify__(ms: number): Promise<void>; + function __promisify__<T>(ms: number, value: T): Promise<T>; + } + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; + namespace setImmediate { + function __promisify__(): Promise<void>; + function __promisify__<T>(value: T): Promise<T>; + } + function clearImmediate(immediateId: NodeJS.Immediate): void; +} diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e7222b5a5b2cdb27d15ef862a6a2f97e4cd8308e --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,390 @@ +declare module "tls" { + import * as crypto from "crypto"; + import * as dns from "dns"; + import * as net from "net"; + import * as stream from "stream"; + + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: { [index: string]: string[] | undefined }; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } + + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext, + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean, + /** + * An optional net.Server instance. + */ + server?: net.Server, + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean, + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. Defaults to false. + */ + rejectUnauthorized?: boolean, + /** + * An array of strings or a Buffer naming possible NPN protocols. + * (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) When the server + * receives both NPN and ALPN extensions from the client, ALPN takes + * precedence over NPN and the server does not send an NPN extension + * to the client. + */ + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, + /** + * SNICallback(servername, cb) <Function> A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void, + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer, + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean + }); + + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + + /** + * String containing the selected ALPN protocol. + * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol?: string; + + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): any; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): any; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + */ + renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; + + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + } + + interface TlsOptions extends SecureContextOptions { + handshakeTimeout?: number; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + sessionTimeout?: number; + ticketKeys?: Buffer; + } + + interface ConnectionOptions extends SecureContextOptions { + host?: string; + port?: number; + path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket + rejectUnauthorized?: boolean; // Defaults to true + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + checkServerIdentity?: typeof checkServerIdentity; + servername?: string; // SNI TLS Extension + session?: Buffer; + minDHSize?: number; + secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() + lookup?: net.LookupFunction; + timeout?: number; + } + + class Server extends net.Server { + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + } + + interface SecurePair { + encrypted: any; + cleartext: any; + } + + type SecureVersion = 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; + + interface SecureContextOptions { + pfx?: string | Buffer | Array<string | Buffer | Object>; + key?: string | Buffer | Array<Buffer | Object>; + passphrase?: string; + cert?: string | Buffer | Array<string | Buffer>; + ca?: string | Buffer | Array<string | Buffer>; + ciphers?: string; + honorCipherOrder?: boolean; + ecdhCurve?: string; + clientCertEngine?: string; + crl?: string | Buffer | Array<string | Buffer>; + dhparam?: string | Buffer; + secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options + secureProtocol?: string; // SSL Method, e.g. SSLv23_method + sessionIdContext?: string; + /** + * Optionally set the maximum TLS version to allow. One + * of `TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. **Default:** `'TLSv1.2'`. + */ + maxVersion?: SecureVersion; + /** + * Optionally set the minimum TLS version to allow. One + * of `TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` changes the default to `'TLSv1'`. Using `--tls-v1.1` changes + * the default to `'TLSv1.1'`. + */ + minVersion?: SecureVersion; + } + + interface SecureContext { + context: any; + } + + /* + * Verifies the certificate `cert` is issued to host `host`. + * @host The hostname to verify the certificate against + * @cert PeerCertificate representing the peer's certificate + * + * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. + */ + function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function createSecurePair(credentials?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + function createSecureContext(details: SecureContextOptions): SecureContext; + function getCiphers(): string[]; + + const DEFAULT_ECDH_CURVE: string; +} diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d1a59bdd06633862f77d2c18d009b90b6b2bd07 --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,61 @@ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + export interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + + /** + * Creates and returns a Tracing object for the given set of categories. + */ + export function createTracing(options: CreateTracingOptions): Tracing; + + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is + * determined by the union of all currently-enabled `Tracing` objects and + * any categories enabled using the `--trace-event-categories` flag. + */ + export function getEnabledCategories(): string; +} diff --git a/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5fadbc2d3944d7222a1bb37239b799a5e774b6da --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,47 @@ +declare module "tty" { + import * as net from "net"; + + function isatty(fd: number): boolean; + class ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + class WriteStream extends net.Socket { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + + clearLine(dir: Direction): void; + clearScreenDown(): void; + cursorTo(x: number, y: number): void; + /** + * @default `process.env` + */ + getColorDepth(env?: {}): number; + getWindowSize(): [number, number]; + columns: number; + rows: number; + isTTY: boolean; + } +} diff --git a/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e1d154e8e83114e9ef998693738e074b7c1d109 --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,104 @@ +declare module "url" { + import { ParsedUrlQuery } from 'querystring'; + + interface UrlObjectCommon { + auth?: string; + hash?: string; + host?: string; + hostname?: string; + href?: string; + path?: string; + pathname?: string; + protocol?: string; + search?: string; + slashes?: boolean; + } + + // Input to `url.format` + interface UrlObject extends UrlObjectCommon { + port?: string | number; + query?: string | null | { [key: string]: any }; + } + + // Output of `url.parse` + interface Url extends UrlObjectCommon { + port?: string; + query?: string | null | ParsedUrlQuery; + } + + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + + interface UrlWithStringQuery extends Url { + query: string | null; + } + + function parse(urlStr: string): UrlWithStringQuery; + function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + + function format(URL: URL, options?: URLFormatOptions): string; + function format(urlObject: UrlObject | string): string; + function resolve(from: string, to: string): string; + + function domainToASCII(domain: string): string; + function domainToUnicode(domain: string): string; + + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * @param url The file URL string or URL object to convert to a path. + */ + function fileURLToPath(url: string | URL): string; + + /** + * This function ensures that path is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * @param url The path to convert to a File URL. + */ + function pathToFileURL(url: string): URL; + + interface URLFormatOptions { + auth?: boolean; + fragment?: boolean; + search?: boolean; + unicode?: boolean; + } + + class URL { + constructor(input: string, base?: string | URL); + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toString(): string; + toJSON(): string; + } + + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | { [key: string]: string | string[] | undefined } | Iterable<[string, string]> | Array<[string, string]>); + append(name: string, value: string): void; + delete(name: string): void; + entries(): IterableIterator<[string, string]>; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + keys(): IterableIterator<string>; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[string, string]>; + } +} diff --git a/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1adf10059fd6d6f27f50387d8267f3437d4b4294 --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,168 @@ +declare module "util" { + interface InspectOptions extends NodeJS.InspectOptions { } + function format(format: any, ...param: any[]): string; + function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function debug(string: string): void; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function error(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function puts(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function print(...param: any[]): void; + /** @deprecated since v0.11.3 - use a third party module instead. */ + function log(string: string): void; + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; + namespace inspect { + let colors: { + [color: string]: [number, number] | undefined + }; + let styles: { + [style: string]: string | undefined + }; + let defaultOptions: InspectOptions; + } + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + function isError(object: any): object is Error; + function inherits(constructor: any, superConstructor: any): void; + function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + function isUndefined(object: any): object is undefined; + function deprecate<T extends Function>(fn: T, message: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + interface CustomPromisify<TCustom extends Function> extends Function { + __promisify__: TCustom; + } + + function callbackify(fn: () => Promise<void>): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<TResult>(fn: () => Promise<TResult>): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1>(fn: (arg1: T1) => Promise<void>): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, TResult>(fn: (arg1: T1) => Promise<TResult>): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1, T2>(fn: (arg1: T1, arg2: T2) => Promise<void>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2) => Promise<TResult>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, T2, T3, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1, T2, T3, T4>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, T2, T3, T4, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1, T2, T3, T4, T5>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, T2, T3, T4, T5, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1, T2, T3, T4, T5, T6>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, T2, T3, T4, T5, T6, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult> + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + + function promisify<TCustom extends Function>(fn: CustomPromisify<TCustom>): TCustom; + function promisify<TResult>(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise<TResult>; + function promisify(fn: (callback: (err?: Error | null) => void) => void): () => Promise<void>; + function promisify<T1, TResult>(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise<TResult>; + function promisify<T1>(fn: (arg1: T1, callback: (err?: Error | null) => void) => void): (arg1: T1) => Promise<void>; + function promisify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise<TResult>; + function promisify<T1, T2>(fn: (arg1: T1, arg2: T2, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2) => Promise<void>; + function promisify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>; + function promisify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise<void>; + function promisify<T1, T2, T3, T4, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>; + function promisify<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>; + function promisify<T1, T2, T3, T4, T5, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>; + function promisify<T1, T2, T3, T4, T5>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>; + function promisify(fn: Function): Function; + + namespace types { + function isAnyArrayBuffer(object: any): boolean; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isAsyncFunction(object: any): boolean; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* BigInt */); + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): boolean; + function isGeneratorObject(object: any): boolean; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap(object: any): boolean; + function isMapIterator(object: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): boolean; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet(object: any): boolean; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): boolean; + function isStringObject(object: any): boolean; + function isSymbolObject(object: any): boolean; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): boolean; + function isWeakSet(object: any): boolean; + function isWebAssemblyCompiledModule(object: any): boolean; + } + + class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + class TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; + } +} diff --git a/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee5f7072343333a8e16bffd2f4f6d3e719c7937f --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,28 @@ +declare module "v8" { + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + } + + function getHeapStatistics(): HeapInfo; + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + function setFlagsFromString(flags: string): void; +} diff --git a/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..404fa9c820d291ddea68e9e613292e242d3c667c --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,64 @@ +declare module "vm" { + interface Context { + [key: string]: any; + } + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * Default: `0` + */ + columnOffset?: number; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + interface RunningScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context; + + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[]; + } + class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + function createContext(sandbox?: Context): Context; + function isContext(sandbox: Context): boolean; + function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; + function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; + function runInThisContext(code: string, options?: RunningScriptOptions | string): any; + function compileFunction(code: string, params: string[], options: CompileFunctionOptions): Function; +} diff --git a/node_modules/@types/node/worker_threads.d.ts b/node_modules/@types/node/worker_threads.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b011b8ff3297efd451b62ca9acded956938fcb7d --- /dev/null +++ b/node_modules/@types/node/worker_threads.d.ts @@ -0,0 +1,125 @@ +declare module "worker_threads" { + import { EventEmitter } from "events"; + import { Readable, Writable } from "stream"; + + const isMainThread: boolean; + const parentPort: null | MessagePort; + const threadId: number; + const workerData: any; + + class MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; + } + + class MessagePort extends EventEmitter { + close(): void; + postMessage(value: any, transferList?: Array<ArrayBuffer | MessagePort>): void; + ref(): void; + unref(): void; + start(): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "message", value: any): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "close", listener: () => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface WorkerOptions { + eval?: boolean; + workerData?: any; + stdin?: boolean; + stdout?: boolean; + stderr?: boolean; + execArgv?: string[]; + } + + class Worker extends EventEmitter { + readonly stdin: Writable | null; + readonly stdout: Readable; + readonly stderr: Readable; + readonly threadId: number; + + constructor(filename: string, options?: WorkerOptions); + + postMessage(value: any, transferList?: Array<ArrayBuffer | MessagePort>): void; + ref(): void; + unref(): void; + terminate(callback?: (err: any, exitCode: number) => void): void; + + addListener(event: "error", listener: (err: any) => void): this; + addListener(event: "exit", listener: (exitCode: number) => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "online", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "error", err: any): boolean; + emit(event: "exit", exitCode: number): boolean; + emit(event: "message", value: any): boolean; + emit(event: "online"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "error", listener: (err: any) => void): this; + on(event: "exit", listener: (exitCode: number) => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "online", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "error", listener: (err: any) => void): this; + once(event: "exit", listener: (exitCode: number) => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "online", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "error", listener: (err: any) => void): this; + prependListener(event: "exit", listener: (exitCode: number) => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: "online", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "error", listener: (err: any) => void): this; + prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: "online", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "error", listener: (err: any) => void): this; + removeListener(event: "exit", listener: (exitCode: number) => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: "online", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "error", listener: (err: any) => void): this; + off(event: "exit", listener: (exitCode: number) => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "online", listener: () => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } +} diff --git a/node_modules/@types/node/zlib.d.ts b/node_modules/@types/node/zlib.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dff374b8f590ccfcc0b11812d154504edc5410b4 --- /dev/null +++ b/node_modules/@types/node/zlib.d.ts @@ -0,0 +1,141 @@ +declare module "zlib" { + import * as stream from "stream"; + + interface ZlibOptions { + flush?: number; // default: zlib.constants.Z_NO_FLUSH + finishFlush?: number; // default: zlib.constants.Z_FINISH + chunkSize?: number; // default: 16*1024 + windowBits?: number; + level?: number; // compression only + memLevel?: number; // compression only + strategy?: number; // compression only + dictionary?: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default + } + + interface Zlib { + /** @deprecated Use bytesWritten instead. */ + readonly bytesRead: number; + readonly bytesWritten: number; + shell?: boolean | string; + close(callback?: () => void): void; + flush(kind?: number | (() => void), callback?: () => void): void; + } + + interface ZlibParams { + params(level: number, strategy: number, callback: () => void): void; + } + + interface ZlibReset { + reset(): void; + } + + interface Gzip extends stream.Transform, Zlib { } + interface Gunzip extends stream.Transform, Zlib { } + interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface Inflate extends stream.Transform, Zlib, ZlibReset { } + interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } + interface Unzip extends stream.Transform, Zlib { } + + function createGzip(options?: ZlibOptions): Gzip; + function createGunzip(options?: ZlibOptions): Gunzip; + function createDeflate(options?: ZlibOptions): Deflate; + function createInflate(options?: ZlibOptions): Inflate; + function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + function createInflateRaw(options?: ZlibOptions): InflateRaw; + function createUnzip(options?: ZlibOptions): Unzip; + + type InputType = string | Buffer | DataView | ArrayBuffer | NodeJS.TypedArray; + function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; + function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; + function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; + function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; + function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; + + namespace constants { + // Allowed flush values. + + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + + // Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. + + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + + // Compression levels. + + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + + // Compression strategy. + + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + } + + // Constants + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + const Z_BINARY: number; + const Z_TEXT: number; + const Z_ASCII: number; + const Z_UNKNOWN: number; + const Z_DEFLATED: number; +} diff --git a/node_modules/async/CHANGELOG.md b/node_modules/async/CHANGELOG.md deleted file mode 100644 index c226ba8d733c550b2c99896f22529f0a9066925b..0000000000000000000000000000000000000000 --- a/node_modules/async/CHANGELOG.md +++ /dev/null @@ -1,269 +0,0 @@ -# v2.6.1 -- Updated lodash to prevent `npm audit` warnings. (#1532, #1533) -- Made `async-es` more optimized for webpack users (#1517) -- Fixed a stack overflow with large collections and a synchronous iterator (#1514) -- Various small fixes/chores (#1505, #1511, #1527, #1530) - -# v2.6.0 -- Added missing aliases for many methods. Previously, you could not (e.g.) `require('async/find')` or use `async.anyLimit`. (#1483) -- Improved `queue` performance. (#1448, #1454) -- Add missing sourcemap (#1452, #1453) -- Various doc updates (#1448, #1471, #1483) - -# v2.5.0 -- Added `concatLimit`, the `Limit` equivalent of [`concat`](https://caolan.github.io/async/docs.html#concat) ([#1426](https://github.com/caolan/async/issues/1426), [#1430](https://github.com/caolan/async/pull/1430)) -- `concat` improvements: it now preserves order, handles falsy values and the `iteratee` callback takes a variable number of arguments ([#1437](https://github.com/caolan/async/issues/1437), [#1436](https://github.com/caolan/async/pull/1436)) -- Fixed an issue in `queue` where there was a size discrepancy between `workersList().length` and `running()` ([#1428](https://github.com/caolan/async/issues/1428), [#1429](https://github.com/caolan/async/pull/1429)) -- Various doc fixes ([#1422](https://github.com/caolan/async/issues/1422), [#1424](https://github.com/caolan/async/pull/1424)) - -# v2.4.1 -- Fixed a bug preventing functions wrapped with `timeout()` from being re-used. ([#1418](https://github.com/caolan/async/issues/1418), [#1419](https://github.com/caolan/async/issues/1419)) - -# v2.4.0 -- Added `tryEach`, for running async functions in parallel, where you only expect one to succeed. ([#1365](https://github.com/caolan/async/issues/1365), [#687](https://github.com/caolan/async/issues/687)) -- Improved performance, most notably in `parallel` and `waterfall` ([#1395](https://github.com/caolan/async/issues/1395)) -- Added `queue.remove()`, for removing items in a `queue` ([#1397](https://github.com/caolan/async/issues/1397), [#1391](https://github.com/caolan/async/issues/1391)) -- Fixed using `eval`, preventing Async from running in pages with Content Security Policy ([#1404](https://github.com/caolan/async/issues/1404), [#1403](https://github.com/caolan/async/issues/1403)) -- Fixed errors thrown in an `asyncify`ed function's callback being caught by the underlying Promise ([#1408](https://github.com/caolan/async/issues/1408)) -- Fixed timing of `queue.empty()` ([#1367](https://github.com/caolan/async/issues/1367)) -- Various doc fixes ([#1314](https://github.com/caolan/async/issues/1314), [#1394](https://github.com/caolan/async/issues/1394), [#1412](https://github.com/caolan/async/issues/1412)) - -# v2.3.0 -- Added support for ES2017 `async` functions. Wherever you can pass a Node-style/CPS function that uses a callback, you can also pass an `async` function. Previously, you had to wrap `async` functions with `asyncify`. The caveat is that it will only work if `async` functions are supported natively in your environment, transpiled implementations can't be detected. ([#1386](https://github.com/caolan/async/issues/1386), [#1390](https://github.com/caolan/async/issues/1390)) -- Small doc fix ([#1392](https://github.com/caolan/async/issues/1392)) - -# v2.2.0 -- Added `groupBy`, and the `Series`/`Limit` equivalents, analogous to [`_.groupBy`](http://lodash.com/docs#groupBy) ([#1364](https://github.com/caolan/async/issues/1364)) -- Fixed `transform` bug when `callback` was not passed ([#1381](https://github.com/caolan/async/issues/1381)) -- Added note about `reflect` to `parallel` docs ([#1385](https://github.com/caolan/async/issues/1385)) - -# v2.1.5 -- Fix `auto` bug when function names collided with Array.prototype ([#1358](https://github.com/caolan/async/issues/1358)) -- Improve some error messages ([#1349](https://github.com/caolan/async/issues/1349)) -- Avoid stack overflow case in queue -- Fixed an issue in `some`, `every` and `find` where processing would continue after the result was determined. -- Cleanup implementations of `some`, `every` and `find` - -# v2.1.3 -- Make bundle size smaller -- Create optimized hotpath for `filter` in array case. - -# v2.1.2 -- Fixed a stackoverflow bug with `detect`, `some`, `every` on large inputs ([#1293](https://github.com/caolan/async/issues/1293)). - -# v2.1.0 - -- `retry` and `retryable` now support an optional `errorFilter` function that determines if the `task` should retry on the error ([#1256](https://github.com/caolan/async/issues/1256), [#1261](https://github.com/caolan/async/issues/1261)) -- Optimized array iteration in `race`, `cargo`, `queue`, and `priorityQueue` ([#1253](https://github.com/caolan/async/issues/1253)) -- Added alias documentation to doc site ([#1251](https://github.com/caolan/async/issues/1251), [#1254](https://github.com/caolan/async/issues/1254)) -- Added [BootStrap scrollspy](http://getbootstrap.com/javascript/#scrollspy) to docs to highlight in the sidebar the current method being viewed ([#1289](https://github.com/caolan/async/issues/1289), [#1300](https://github.com/caolan/async/issues/1300)) -- Various minor doc fixes ([#1263](https://github.com/caolan/async/issues/1263), [#1264](https://github.com/caolan/async/issues/1264), [#1271](https://github.com/caolan/async/issues/1271), [#1278](https://github.com/caolan/async/issues/1278), [#1280](https://github.com/caolan/async/issues/1280), [#1282](https://github.com/caolan/async/issues/1282), [#1302](https://github.com/caolan/async/issues/1302)) - -# v2.0.1 - -- Significantly optimized all iteration based collection methods such as `each`, `map`, `filter`, etc ([#1245](https://github.com/caolan/async/issues/1245), [#1246](https://github.com/caolan/async/issues/1246), [#1247](https://github.com/caolan/async/issues/1247)). - -# v2.0.0 - -Lots of changes here! - -First and foremost, we have a slick new [site for docs](https://caolan.github.io/async/). Special thanks to [**@hargasinski**](https://github.com/hargasinski) for his work converting our old docs to `jsdoc` format and implementing the new website. Also huge ups to [**@ivanseidel**](https://github.com/ivanseidel) for designing our new logo. It was a long process for both of these tasks, but I think these changes turned out extraordinary well. - -The biggest feature is modularization. You can now `require("async/series")` to only require the `series` function. Every Async library function is available this way. You still can `require("async")` to require the entire library, like you could do before. - -We also provide Async as a collection of ES2015 modules. You can now `import {each} from 'async-es'` or `import waterfall from 'async-es/waterfall'`. If you are using only a few Async functions, and are using a ES bundler such as Rollup, this can significantly lower your build size. - -Major thanks to [**@Kikobeats**](github.com/Kikobeats), [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for doing the majority of the modularization work, as well as [**@jdalton**](github.com/jdalton) and [**@Rich-Harris**](github.com/Rich-Harris) for advisory work on the general modularization strategy. - -Another one of the general themes of the 2.0 release is standardization of what an "async" function is. We are now more strictly following the node-style continuation passing style. That is, an async function is a function that: - -1. Takes a variable number of arguments -2. The last argument is always a callback -3. The callback can accept any number of arguments -4. The first argument passed to the callback will be treated as an error result, if the argument is truthy -5. Any number of result arguments can be passed after the "error" argument -6. The callback is called once and exactly once, either on the same tick or later tick of the JavaScript event loop. - -There were several cases where Async accepted some functions that did not strictly have these properties, most notably `auto`, `every`, `some`, `filter`, `reject` and `detect`. - -Another theme is performance. We have eliminated internal deferrals in all cases where they make sense. For example, in `waterfall` and `auto`, there was a `setImmediate` between each task -- these deferrals have been removed. A `setImmediate` call can add up to 1ms of delay. This might not seem like a lot, but it can add up if you are using many Async functions in the course of processing a HTTP request, for example. Nearly all asynchronous functions that do I/O already have some sort of deferral built in, so the extra deferral is unnecessary. The trade-off of this change is removing our built-in stack-overflow defense. Many synchronous callback calls in series can quickly overflow the JS call stack. If you do have a function that is sometimes synchronous (calling its callback on the same tick), and are running into stack overflows, wrap it with `async.ensureAsync()`. - -Another big performance win has been re-implementing `queue`, `cargo`, and `priorityQueue` with [doubly linked lists](https://en.wikipedia.org/wiki/Doubly_linked_list) instead of arrays. This has lead to queues being an order of [magnitude faster on large sets of tasks](https://github.com/caolan/async/pull/1205). - -## New Features - -- Async is now modularized. Individual functions can be `require()`d from the main package. (`require('async/auto')`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) -- Async is also available as a collection of ES2015 modules in the new `async-es` package. (`import {forEachSeries} from 'async-es'`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) -- Added `race`, analogous to `Promise.race()`. It will run an array of async tasks in parallel and will call its callback with the result of the first task to respond. ([#568](https://github.com/caolan/async/issues/568), [#1038](https://github.com/caolan/async/issues/1038)) -- Collection methods now accept ES2015 iterators. Maps, Sets, and anything that implements the iterator spec can now be passed directly to `each`, `map`, `parallel`, etc.. ([#579](https://github.com/caolan/async/issues/579), [#839](https://github.com/caolan/async/issues/839), [#1074](https://github.com/caolan/async/issues/1074)) -- Added `mapValues`, for mapping over the properties of an object and returning an object with the same keys. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) -- Added `timeout`, a wrapper for an async function that will make the task time-out after the specified time. ([#1007](https://github.com/caolan/async/issues/1007), [#1027](https://github.com/caolan/async/issues/1027)) -- Added `reflect` and `reflectAll`, analagous to [`Promise.reflect()`](http://bluebirdjs.com/docs/api/reflect.html), a wrapper for async tasks that always succeeds, by gathering results and errors into an object. ([#942](https://github.com/caolan/async/issues/942), [#1012](https://github.com/caolan/async/issues/1012), [#1095](https://github.com/caolan/async/issues/1095)) -- `constant` supports dynamic arguments -- it will now always use its last argument as the callback. ([#1016](https://github.com/caolan/async/issues/1016), [#1052](https://github.com/caolan/async/issues/1052)) -- `setImmediate` and `nextTick` now support arguments to partially apply to the deferred function, like the node-native versions do. ([#940](https://github.com/caolan/async/issues/940), [#1053](https://github.com/caolan/async/issues/1053)) -- `auto` now supports resolving cyclic dependencies using [Kahn's algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm) ([#1140](https://github.com/caolan/async/issues/1140)). -- Added `autoInject`, a relative of `auto` that automatically spreads a task's dependencies as arguments to the task function. ([#608](https://github.com/caolan/async/issues/608), [#1055](https://github.com/caolan/async/issues/1055), [#1099](https://github.com/caolan/async/issues/1099), [#1100](https://github.com/caolan/async/issues/1100)) -- You can now limit the concurrency of `auto` tasks. ([#635](https://github.com/caolan/async/issues/635), [#637](https://github.com/caolan/async/issues/637)) -- Added `retryable`, a relative of `retry` that wraps an async function, making it retry when called. ([#1058](https://github.com/caolan/async/issues/1058)) -- `retry` now supports specifying a function that determines the next time interval, useful for exponential backoff, logging and other retry strategies. ([#1161](https://github.com/caolan/async/issues/1161)) -- `retry` will now pass all of the arguments the task function was resolved with to the callback ([#1231](https://github.com/caolan/async/issues/1231)). -- Added `q.unsaturated` -- callback called when a `queue`'s number of running workers falls below a threshold. ([#868](https://github.com/caolan/async/issues/868), [#1030](https://github.com/caolan/async/issues/1030), [#1033](https://github.com/caolan/async/issues/1033), [#1034](https://github.com/caolan/async/issues/1034)) -- Added `q.error` -- a callback called whenever a `queue` task calls its callback with an error. ([#1170](https://github.com/caolan/async/issues/1170)) -- `applyEach` and `applyEachSeries` now pass results to the final callback. ([#1088](https://github.com/caolan/async/issues/1088)) - -## Breaking changes - -- Calling a callback more than once is considered an error, and an error will be thrown. This had an explicit breaking change in `waterfall`. If you were relying on this behavior, you should more accurately represent your control flow as an event emitter or stream. ([#814](https://github.com/caolan/async/issues/814), [#815](https://github.com/caolan/async/issues/815), [#1048](https://github.com/caolan/async/issues/1048), [#1050](https://github.com/caolan/async/issues/1050)) -- `auto` task functions now always take the callback as the last argument. If a task has dependencies, the `results` object will be passed as the first argument. To migrate old task functions, wrap them with [`_.flip`](https://lodash.com/docs#flip) ([#1036](https://github.com/caolan/async/issues/1036), [#1042](https://github.com/caolan/async/issues/1042)) -- Internal `setImmediate` calls have been refactored away. This may make existing flows vulnerable to stack overflows if you use many synchronous functions in series. Use `ensureAsync` to work around this. ([#696](https://github.com/caolan/async/issues/696), [#704](https://github.com/caolan/async/issues/704), [#1049](https://github.com/caolan/async/issues/1049), [#1050](https://github.com/caolan/async/issues/1050)) -- `map` used to return an object when iterating over an object. `map` now always returns an array, like in other libraries. The previous object behavior has been split out into `mapValues`. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) -- `filter`, `reject`, `some`, `every`, `detect` and their families like `{METHOD}Series` and `{METHOD}Limit` now expect an error as the first callback argument, rather than just a simple boolean. Pass `null` as the first argument, or use `fs.access` instead of `fs.exists`. ([#118](https://github.com/caolan/async/issues/118), [#774](https://github.com/caolan/async/issues/774), [#1028](https://github.com/caolan/async/issues/1028), [#1041](https://github.com/caolan/async/issues/1041)) -- `{METHOD}` and `{METHOD}Series` are now implemented in terms of `{METHOD}Limit`. This is a major internal simplification, and is not expected to cause many problems, but it does subtly affect how functions execute internally. ([#778](https://github.com/caolan/async/issues/778), [#847](https://github.com/caolan/async/issues/847)) -- `retry`'s callback is now optional. Previously, omitting the callback would partially apply the function, meaning it could be passed directly as a task to `series` or `auto`. The partially applied "control-flow" behavior has been separated out into `retryable`. ([#1054](https://github.com/caolan/async/issues/1054), [#1058](https://github.com/caolan/async/issues/1058)) -- The test function for `whilst`, `until`, and `during` used to be passed non-error args from the iteratee function's callback, but this led to weirdness where the first call of the test function would be passed no args. We have made it so the test function is never passed extra arguments, and only the `doWhilst`, `doUntil`, and `doDuring` functions pass iteratee callback arguments to the test function ([#1217](https://github.com/caolan/async/issues/1217), [#1224](https://github.com/caolan/async/issues/1224)) -- The `q.tasks` array has been renamed `q._tasks` and is now implemented as a doubly linked list (DLL). Any code that used to interact with this array will need to be updated to either use the provided helpers or support DLLs ([#1205](https://github.com/caolan/async/issues/1205)). -- The timing of the `q.saturated()` callback in a `queue` has been modified to better reflect when tasks pushed to the queue will start queueing. ([#724](https://github.com/caolan/async/issues/724), [#1078](https://github.com/caolan/async/issues/1078)) -- Removed `iterator` method in favour of [ES2015 iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators ) which natively supports arrays ([#1237](https://github.com/caolan/async/issues/1237)) -- Dropped support for Component, Jam, SPM, and Volo ([#1175](https://github.com/caolan/async/issues/1175), #[#176](https://github.com/caolan/async/issues/176)) - -## Bug Fixes - -- Improved handling of no dependency cases in `auto` & `autoInject` ([#1147](https://github.com/caolan/async/issues/1147)). -- Fixed a bug where the callback generated by `asyncify` with `Promises` could resolve twice ([#1197](https://github.com/caolan/async/issues/1197)). -- Fixed several documented optional callbacks not actually being optional ([#1223](https://github.com/caolan/async/issues/1223)). - -## Other - -- Added `someSeries` and `everySeries` for symmetry, as well as a complete set of `any`/`anyLimit`/`anySeries` and `all`/`/allLmit`/`allSeries` aliases. -- Added `find` as an alias for `detect. (as well as `findLimit` and `findSeries`). -- Various doc fixes ([#1005](https://github.com/caolan/async/issues/1005), [#1008](https://github.com/caolan/async/issues/1008), [#1010](https://github.com/caolan/async/issues/1010), [#1015](https://github.com/caolan/async/issues/1015), [#1021](https://github.com/caolan/async/issues/1021), [#1037](https://github.com/caolan/async/issues/1037), [#1039](https://github.com/caolan/async/issues/1039), [#1051](https://github.com/caolan/async/issues/1051), [#1102](https://github.com/caolan/async/issues/1102), [#1107](https://github.com/caolan/async/issues/1107), [#1121](https://github.com/caolan/async/issues/1121), [#1123](https://github.com/caolan/async/issues/1123), [#1129](https://github.com/caolan/async/issues/1129), [#1135](https://github.com/caolan/async/issues/1135), [#1138](https://github.com/caolan/async/issues/1138), [#1141](https://github.com/caolan/async/issues/1141), [#1153](https://github.com/caolan/async/issues/1153), [#1216](https://github.com/caolan/async/issues/1216), [#1217](https://github.com/caolan/async/issues/1217), [#1232](https://github.com/caolan/async/issues/1232), [#1233](https://github.com/caolan/async/issues/1233), [#1236](https://github.com/caolan/async/issues/1236), [#1238](https://github.com/caolan/async/issues/1238)) - -Thank you [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for taking the lead on version 2 of async. - ------------------------------------------- - -# v1.5.2 -- Allow using `"constructor"` as an argument in `memoize` ([#998](https://github.com/caolan/async/issues/998)) -- Give a better error messsage when `auto` dependency checking fails ([#994](https://github.com/caolan/async/issues/994)) -- Various doc updates ([#936](https://github.com/caolan/async/issues/936), [#956](https://github.com/caolan/async/issues/956), [#979](https://github.com/caolan/async/issues/979), [#1002](https://github.com/caolan/async/issues/1002)) - -# v1.5.1 -- Fix issue with `pause` in `queue` with concurrency enabled ([#946](https://github.com/caolan/async/issues/946)) -- `while` and `until` now pass the final result to callback ([#963](https://github.com/caolan/async/issues/963)) -- `auto` will properly handle concurrency when there is no callback ([#966](https://github.com/caolan/async/issues/966)) -- `auto` will no. properly stop execution when an error occurs ([#988](https://github.com/caolan/async/issues/988), [#993](https://github.com/caolan/async/issues/993)) -- Various doc fixes ([#971](https://github.com/caolan/async/issues/971), [#980](https://github.com/caolan/async/issues/980)) - -# v1.5.0 - -- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) ([#892](https://github.com/caolan/async/issues/892)) -- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. ([#873](https://github.com/caolan/async/issues/873)) -- `auto` now accepts an optional `concurrency` argument to limit the number o. running tasks ([#637](https://github.com/caolan/async/issues/637)) -- Added `queue#workersList()`, to retrieve the lis. of currently running tasks. ([#891](https://github.com/caolan/async/issues/891)) -- Various code simplifications ([#896](https://github.com/caolan/async/issues/896), [#904](https://github.com/caolan/async/issues/904)) -- Various doc fixes :scroll: ([#890](https://github.com/caolan/async/issues/890), [#894](https://github.com/caolan/async/issues/894), [#903](https://github.com/caolan/async/issues/903), [#905](https://github.com/caolan/async/issues/905), [#912](https://github.com/caolan/async/issues/912)) - -# v1.4.2 - -- Ensure coverage files don't get published on npm ([#879](https://github.com/caolan/async/issues/879)) - -# v1.4.1 - -- Add in overlooked `detectLimit` method ([#866](https://github.com/caolan/async/issues/866)) -- Removed unnecessary files from npm releases ([#861](https://github.com/caolan/async/issues/861)) -- Removed usage of a reserved word to prevent :boom: in older environments ([#870](https://github.com/caolan/async/issues/870)) - -# v1.4.0 - -- `asyncify` now supports promises ([#840](https://github.com/caolan/async/issues/840)) -- Added `Limit` versions of `filter` and `reject` ([#836](https://github.com/caolan/async/issues/836)) -- Add `Limit` versions of `detect`, `some` and `every` ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) -- `some`, `every` and `detect` now short circuit early ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) -- Improve detection of the global object ([#804](https://github.com/caolan/async/issues/804)), enabling use in WebWorkers -- `whilst` now called with arguments from iterator ([#823](https://github.com/caolan/async/issues/823)) -- `during` now gets called with arguments from iterator ([#824](https://github.com/caolan/async/issues/824)) -- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0)) - - -# v1.3.0 - -New Features: -- Added `constant` -- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. ([#671](https://github.com/caolan/async/issues/671), [#806](https://github.com/caolan/async/issues/806)) -- Added `during` and `doDuring`, which are like `whilst` with an async truth test. ([#800](https://github.com/caolan/async/issues/800)) -- `retry` now accepts an `interval` parameter to specify a delay between retries. ([#793](https://github.com/caolan/async/issues/793)) -- `async` should work better in Web Workers due to better `root` detection ([#804](https://github.com/caolan/async/issues/804)) -- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` ([#642](https://github.com/caolan/async/issues/642)) -- Various internal updates ([#786](https://github.com/caolan/async/issues/786), [#801](https://github.com/caolan/async/issues/801), [#802](https://github.com/caolan/async/issues/802), [#803](https://github.com/caolan/async/issues/803)) -- Various doc fixes ([#790](https://github.com/caolan/async/issues/790), [#794](https://github.com/caolan/async/issues/794)) - -Bug Fixes: -- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. ([#740](https://github.com/caolan/async/issues/740), [#744](https://github.com/caolan/async/issues/744), [#783](https://github.com/caolan/async/issues/783)) - - -# v1.2.1 - -Bug Fix: - -- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) - - -# v1.2.0 - -New Features: - -- Added `timesLimit` ([#743](https://github.com/caolan/async/issues/743)) -- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. ([#747](https://github.com/caolan/async/issues/747), [#772](https://github.com/caolan/async/issues/772)) - -Bug Fixes: - -- Fixed a regression in `each` and family with empty arrays that have additional properties. ([#775](https://github.com/caolan/async/issues/775), [#777](https://github.com/caolan/async/issues/777)) - - -# v1.1.1 - -Bug Fix: - -- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) - - -# 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](https://github.com/caolan/async/issues/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](https://github.com/caolan/async/issues/667)). -- The callback is now optional for the composed results of `compose` and `seq`. ([#618](https://github.com/caolan/async/issues/618)) -- Reduced file size by 4kb, (minified version by 1kb) -- Added code coverage through `nyc` and `coveralls` ([#768](https://github.com/caolan/async/issues/768)) - -Bug Fixes: - -- `forever` will no longer stack overflow with a synchronous iterator ([#622](https://github.com/caolan/async/issues/622)) -- `eachLimit` and other limit functions will stop iterating once an error occurs ([#754](https://github.com/caolan/async/issues/754)) -- Always pass `null` in callbacks when there is no error ([#439](https://github.com/caolan/async/issues/439)) -- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue ([#668](https://github.com/caolan/async/issues/668)) -- `each` and family will properly handle an empty array ([#578](https://github.com/caolan/async/issues/578)) -- `eachSeries` and family will finish if the underlying array is modified during execution ([#557](https://github.com/caolan/async/issues/557)) -- `queue` will throw if a non-function is passed to `q.push()` ([#593](https://github.com/caolan/async/issues/593)) -- Doc fixes ([#629](https://github.com/caolan/async/issues/629), [#766](https://github.com/caolan/async/issues/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](https://github.com/caolan/async/issues/168) [#704](https://github.com/caolan/async/issues/704) [#321](https://github.com/caolan/async/issues/321)) -- Detect deadlocks in `auto` ([#663](https://github.com/caolan/async/issues/663)) -- Better support for require.js ([#527](https://github.com/caolan/async/issues/527)) -- Throw if queue created with concurrency `0` ([#714](https://github.com/caolan/async/issues/714)) -- Fix unneeded iteration in `queue.resume()` ([#758](https://github.com/caolan/async/issues/758)) -- Guard against timer mocking overriding `setImmediate` ([#609](https://github.com/caolan/async/issues/609) [#611](https://github.com/caolan/async/issues/611)) -- Miscellaneous doc fixes ([#542](https://github.com/caolan/async/issues/542) [#596](https://github.com/caolan/async/issues/596) [#615](https://github.com/caolan/async/issues/615) [#628](https://github.com/caolan/async/issues/628) [#631](https://github.com/caolan/async/issues/631) [#690](https://github.com/caolan/async/issues/690) [#729](https://github.com/caolan/async/issues/729)) -- Use single noop function internally ([#546](https://github.com/caolan/async/issues/546)) -- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/node_modules/async/LICENSE b/node_modules/async/LICENSE deleted file mode 100644 index b18aed69219562718858d972467ba0a68b1ce178..0000000000000000000000000000000000000000 --- a/node_modules/async/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010-2018 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 deleted file mode 100644 index 49cf9504a6ff6c88ce0c82b4b027dd75be2226be..0000000000000000000000000000000000000000 --- a/node_modules/async/README.md +++ /dev/null @@ -1,56 +0,0 @@ - - -[](https://travis-ci.org/caolan/async) -[](https://www.npmjs.com/package/async) -[](https://coveralls.io/r/caolan/async?branch=master) -[](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[](https://www.libhive.com/providers/npm/packages/async) -[](https://www.jsdelivr.com/package/npm/async) - - -Async is a utility module which provides straight-forward, powerful functions for working with [asynchronous JavaScript](http://caolan.github.io/async/global.html). Although originally designed for use with [Node.js](https://nodejs.org/) and installable via `npm install --save async`, it can also be used directly in the browser. - -This version of the package is optimized for the Node.js environment. If you use Async with webpack, install [`async-es`](https://www.npmjs.com/package/async-es) instead. - -For Documentation, visit <https://caolan.github.io/async/> - -*For Async v1.5.x documentation, go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md)* - - -```javascript -// for use with Node-style callbacks... -var async = require("async"); - -var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; -var configs = {}; - -async.forEachOf(obj, (value, key, callback) => { - fs.readFile(__dirname + value, "utf8", (err, data) => { - if (err) return callback(err); - try { - configs[key] = JSON.parse(data); - } catch (e) { - return callback(e); - } - callback(); - }); -}, err => { - if (err) console.error(err.message); - // configs is now a map of JSON data - doSomethingWith(configs); -}); -``` - -```javascript -var async = require("async"); - -// ...or ES2017 async functions -async.mapLimit(urls, 5, async function(url) { - const response = await fetch(url) - return response.body -}, (err, results) => { - if (err) throw err - // results is now an array of the response bodies - console.log(results) -}) -``` diff --git a/node_modules/async/all.js b/node_modules/async/all.js deleted file mode 100644 index d0565b0454595ea7935f319cb882de0e97670423..0000000000000000000000000000000000000000 --- a/node_modules/async/all.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _notId = require('./internal/notId'); - -var _notId2 = _interopRequireDefault(_notId); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/allLimit.js b/node_modules/async/allLimit.js deleted file mode 100644 index a1a759a2b2eb0e6bedd3bbf7cc0c7ce0b3e7adcf..0000000000000000000000000000000000000000 --- a/node_modules/async/allLimit.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _notId = require('./internal/notId'); - -var _notId2 = _interopRequireDefault(_notId); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/allSeries.js b/node_modules/async/allSeries.js deleted file mode 100644 index 23bfebb59f519fcff02e58aa4b8afd03122a4e05..0000000000000000000000000000000000000000 --- a/node_modules/async/allSeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _everyLimit = require('./everyLimit'); - -var _everyLimit2 = _interopRequireDefault(_everyLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -exports.default = (0, _doLimit2.default)(_everyLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/any.js b/node_modules/async/any.js deleted file mode 100644 index a8e70f714a89a615bdd14d6ea7bf538fa37b1700..0000000000000000000000000000000000000000 --- a/node_modules/async/any.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(Boolean, _identity2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/anyLimit.js b/node_modules/async/anyLimit.js deleted file mode 100644 index 24ca3f4919d0eab978e8b72b4eb42abd2250df55..0000000000000000000000000000000000000000 --- a/node_modules/async/anyLimit.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(Boolean, _identity2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/anySeries.js b/node_modules/async/anySeries.js deleted file mode 100644 index dc24ed254cec1e8b32c7756efd4b3cb4229d24b7..0000000000000000000000000000000000000000 --- a/node_modules/async/anySeries.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _someLimit = require('./someLimit'); - -var _someLimit2 = _interopRequireDefault(_someLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -exports.default = (0, _doLimit2.default)(_someLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/apply.js b/node_modules/async/apply.js deleted file mode 100644 index f590fa574534c7cdafd25423defd44dbe1cddb98..0000000000000000000000000000000000000000 --- a/node_modules/async/apply.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (fn /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - return function () /*callArgs*/{ - var callArgs = (0, _slice2.default)(arguments); - return fn.apply(null, args.concat(callArgs)); - }; -}; - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -; - -/** - * 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. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // 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: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/applyEach.js b/node_modules/async/applyEach.js deleted file mode 100644 index 06c08450a00b2bf2e0524dc721eb92a09f35f252..0000000000000000000000000000000000000000 --- a/node_modules/async/applyEach.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _applyEach = require('./internal/applyEach'); - -var _applyEach2 = _interopRequireDefault(_applyEach); - -var _map = require('./map'); - -var _map2 = _interopRequireDefault(_map); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Applies the provided arguments to each function in the array, calling - * `callback` after all functions have completed. If you only provide the first - * argument, `fns`, then it will return a function which lets you pass in the - * arguments as if it were a single function call. If more arguments are - * provided, `callback` is required while `args` is still optional. - * - * @name applyEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s - * to all call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument, `fns`, is provided, it will - * return a function which lets you pass in the arguments as if it were a single - * function call. The signature is `(..args, callback)`. If invoked with any - * arguments, `callback` is required. - * @example - * - * async.applyEach([enableSearch, updateSchema], 'bucket', callback); - * - * // partial application example: - * async.each( - * buckets, - * async.applyEach([enableSearch, updateSchema]), - * callback - * ); - */ -exports.default = (0, _applyEach2.default)(_map2.default); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/applyEachSeries.js b/node_modules/async/applyEachSeries.js deleted file mode 100644 index ad80280ccfcca4c43ca8f16c7fb9a74d1c51065a..0000000000000000000000000000000000000000 --- a/node_modules/async/applyEachSeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _applyEach = require('./internal/applyEach'); - -var _applyEach2 = _interopRequireDefault(_applyEach); - -var _mapSeries = require('./mapSeries'); - -var _mapSeries2 = _interopRequireDefault(_mapSeries); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. - * - * @name applyEachSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.applyEach]{@link module:ControlFlow.applyEach} - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all - * call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument is provided, it will return - * a function which lets you pass in the arguments as if it were a single - * function call. - */ -exports.default = (0, _applyEach2.default)(_mapSeries2.default); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/asyncify.js b/node_modules/async/asyncify.js deleted file mode 100644 index 5e3fc91557debb47ebe5d30f10783bd6cf2d20ce..0000000000000000000000000000000000000000 --- a/node_modules/async/asyncify.js +++ /dev/null @@ -1,110 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = asyncify; - -var _isObject = require('lodash/isObject'); - -var _isObject2 = _interopRequireDefault(_isObject); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return (0, _initialParams2.default)(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if ((0, _isObject2.default)(result) && typeof result.then === 'function') { - result.then(function (value) { - invokeCallback(callback, null, value); - }, function (err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); -} - -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - (0, _setImmediate2.default)(rethrow, e); - } -} - -function rethrow(error) { - throw error; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/auto.js b/node_modules/async/auto.js deleted file mode 100644 index 26c1d562cead0778eba7c2aa5e83a3b37eacbe7f..0000000000000000000000000000000000000000 --- a/node_modules/async/auto.js +++ /dev/null @@ -1,289 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (tasks, concurrency, callback) { - if (typeof concurrency === 'function') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = (0, _once2.default)(callback || _noop2.default); - var keys = (0, _keys2.default)(tasks); - var numTasks = keys.length; - if (!numTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = numTasks; - } - - var results = {}; - var runningTasks = 0; - var hasError = false; - - var listeners = Object.create(null); - - var readyTasks = []; - - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; - - (0, _baseForOwn2.default)(tasks, function (task, key) { - if (!(0, _isArray2.default)(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } - - var dependencies = task.slice(0, task.length - 1); - var remainingDependencies = dependencies.length; - if (remainingDependencies === 0) { - enqueueTask(key, task); - readyToCheck.push(key); - return; - } - uncheckedDependencies[key] = remainingDependencies; - - (0, _arrayEach2.default)(dependencies, function (dependencyName) { - if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); - } - addListener(dependencyName, function () { - remainingDependencies--; - if (remainingDependencies === 0) { - enqueueTask(key, task); - } - }); - }); - }); - - checkForDeadlocks(); - processQueue(); - - function enqueueTask(key, task) { - readyTasks.push(function () { - runTask(key, task); - }); - } - - function processQueue() { - if (readyTasks.length === 0 && runningTasks === 0) { - return callback(null, results); - } - while (readyTasks.length && runningTasks < concurrency) { - var run = readyTasks.shift(); - run(); - } - } - - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } - - taskListeners.push(fn); - } - - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - (0, _arrayEach2.default)(taskListeners, function (fn) { - fn(); - }); - processQueue(); - } - - function runTask(key, task) { - if (hasError) return; - - var taskCallback = (0, _onlyOnce2.default)(function (err, result) { - runningTasks--; - if (arguments.length > 2) { - result = (0, _slice2.default)(arguments, 1); - } - if (err) { - var safeResults = {}; - (0, _baseForOwn2.default)(results, function (val, rkey) { - safeResults[rkey] = val; - }); - safeResults[key] = result; - hasError = true; - listeners = Object.create(null); - - callback(err, safeResults); - } else { - results[key] = result; - taskComplete(key); - } - }); - - runningTasks++; - var taskFn = (0, _wrapAsync2.default)(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } - - function checkForDeadlocks() { - // Kahn's algorithm - // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm - // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html - var currentTask; - var counter = 0; - while (readyToCheck.length) { - currentTask = readyToCheck.pop(); - counter++; - (0, _arrayEach2.default)(getDependents(currentTask), function (dependent) { - if (--uncheckedDependencies[dependent] === 0) { - readyToCheck.push(dependent); - } - }); - } - - if (counter !== numTasks) { - throw new Error('async.auto cannot execute tasks due to a recursive dependency'); - } - } - - function getDependents(taskName) { - var result = []; - (0, _baseForOwn2.default)(tasks, function (task, key) { - if ((0, _isArray2.default)(task) && (0, _baseIndexOf2.default)(task, taskName, 0) >= 0) { - result.push(key); - } - }); - return result; - } -}; - -var _arrayEach = require('lodash/_arrayEach'); - -var _arrayEach2 = _interopRequireDefault(_arrayEach); - -var _baseForOwn = require('lodash/_baseForOwn'); - -var _baseForOwn2 = _interopRequireDefault(_baseForOwn); - -var _baseIndexOf = require('lodash/_baseIndexOf'); - -var _baseIndexOf2 = _interopRequireDefault(_baseIndexOf); - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _keys = require('lodash/keys'); - -var _keys2 = _interopRequireDefault(_keys); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * Determines the best order for running the {@link AsyncFunction}s 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 {@link AsyncFunction}s pass an error to their callback, the `auto` sequence - * will stop. Further tasks will not execute (so any other functions depending - * on it will not run), and the main `callback` is immediately called with the - * error. - * - * {@link AsyncFunction}s also receive an object containing the results of functions which - * have completed so far as the first argument, if they have dependencies. If a - * task function has no dependencies, it will only be passed a callback. - * - * @name auto - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Object} tasks - An object. Each of its properties is either a - * function or an array of requirements, with the {@link AsyncFunction} 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 one or two arguments: - * * a `results` object, containing the results of the previously executed - * functions, only passed if the task has any dependencies, - * * a `callback(err, result)` function, which must be called when finished, - * passing an `error` (which can be `null`) and the result of the function's - * execution. - * @param {number} [concurrency=Infinity] - An optional `integer` for - * determining the maximum number of tasks that can be run in parallel. By - * default, as many as possible. - * @param {Function} [callback] - 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. Invoked with (err, results). - * @returns undefined - * @example - * - * async.auto({ - * // this function will just be passed a callback - * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), - * showData: ['readData', function(results, cb) { - * // results.readData is the file's contents - * // ... - * }] - * }, callback); - * - * 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(results, 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 - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * 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); - * }); - */ \ No newline at end of file diff --git a/node_modules/async/autoInject.js b/node_modules/async/autoInject.js deleted file mode 100644 index bfbe7e8ec11f322c5beafe37d98b4e439905bf5b..0000000000000000000000000000000000000000 --- a/node_modules/async/autoInject.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = autoInject; - -var _auto = require('./auto'); - -var _auto2 = _interopRequireDefault(_auto); - -var _baseForOwn = require('lodash/_baseForOwn'); - -var _baseForOwn2 = _interopRequireDefault(_baseForOwn); - -var _arrayMap = require('lodash/_arrayMap'); - -var _arrayMap2 = _interopRequireDefault(_arrayMap); - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _trim = require('lodash/trim'); - -var _trim2 = _interopRequireDefault(_trim); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; -var FN_ARG_SPLIT = /,/; -var FN_ARG = /(=.+)?(\s*)$/; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; - -function parseParams(func) { - func = func.toString().replace(STRIP_COMMENTS, ''); - func = func.match(FN_ARGS)[2].replace(' ', ''); - func = func ? func.split(FN_ARG_SPLIT) : []; - func = func.map(function (arg) { - return (0, _trim2.default)(arg.replace(FN_ARG, '')); - }); - return func; -} - -/** - * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent - * tasks are specified as parameters to the function, after the usual callback - * parameter, with the parameter names matching the names of the tasks it - * depends on. This can provide even more readable task graphs which can be - * easier to maintain. - * - * If a final callback is specified, the task results are similarly injected, - * specified as named parameters after the initial error parameter. - * - * The autoInject function is purely syntactic sugar and its semantics are - * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. - * - * @name autoInject - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.auto]{@link module:ControlFlow.auto} - * @category Control Flow - * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of - * the form 'func([dependencies...], callback). 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 `callback` parameter is 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. The remaining parameters name other tasks on - * which the task is dependent, and the results from those tasks are the - * arguments of those parameters. - * @param {Function} [callback] - 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, and a `results` object with any completed - * task results, similar to `auto`. - * @example - * - * // The example from `auto` can be rewritten as follows: - * async.autoInject({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // 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: function(get_data, make_folder, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }, - * email_link: function(write_file, callback) { - * // once the file is written let's email a link to it... - * // write_file contains the filename returned by write_file. - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * } - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - * - * // If you are using a JS minifier that mangles parameter names, `autoInject` - * // will not work with plain functions, since the parameter names will be - * // collapsed to a single letter identifier. To work around this, you can - * // explicitly specify the names of the parameters your task function needs - * // in an array, similar to Angular.js dependency injection. - * - * // This still has an advantage over plain `auto`, since the results a task - * // depends on are still spread into arguments. - * async.autoInject({ - * //... - * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(write_file, callback) { - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * }] - * //... - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - */ -function autoInject(tasks, callback) { - var newTasks = {}; - - (0, _baseForOwn2.default)(tasks, function (taskFn, key) { - var params; - var fnIsAsync = (0, _wrapAsync.isAsync)(taskFn); - var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0; - - if ((0, _isArray2.default)(taskFn)) { - params = taskFn.slice(0, -1); - taskFn = taskFn[taskFn.length - 1]; - - newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); - } else if (hasNoDeps) { - // no dependencies, use the function as-is - newTasks[key] = taskFn; - } else { - params = parseParams(taskFn); - if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { - throw new Error("autoInject task functions require explicit parameters."); - } - - // remove callback param - if (!fnIsAsync) params.pop(); - - newTasks[key] = params.concat(newTask); - } - - function newTask(results, taskCb) { - var newArgs = (0, _arrayMap2.default)(params, function (name) { - return results[name]; - }); - newArgs.push(taskCb); - (0, _wrapAsync2.default)(taskFn).apply(null, newArgs); - } - }); - - (0, _auto2.default)(newTasks, callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/bower.json b/node_modules/async/bower.json deleted file mode 100644 index 7dbeb1497b3a96ace3361b897f31c171dbe63467..0000000000000000000000000000000000000000 --- a/node_modules/async/bower.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "async", - "main": "dist/async.js", - "ignore": [ - "bower_components", - "lib", - "mocha_test", - "node_modules", - "perf", - "support", - "**/.*", - "*.config.js", - "*.json", - "index.js", - "Makefile" - ] -} diff --git a/node_modules/async/cargo.js b/node_modules/async/cargo.js deleted file mode 100644 index c7e59c7c5cc56761b6dc37d9f5583fbb877122c6..0000000000000000000000000000000000000000 --- a/node_modules/async/cargo.js +++ /dev/null @@ -1,94 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = cargo; - -var _queue = require('./internal/queue'); - -var _queue2 = _interopRequireDefault(_queue); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * A cargo of tasks for the worker function to complete. Cargo inherits all of - * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. - * @typedef {Object} CargoObject - * @memberOf module:ControlFlow - * @property {Function} length - A function returning the number of items - * waiting to be processed. Invoke like `cargo.length()`. - * @property {number} 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. - * @property {Function} push - 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. Invoke like `cargo.push(task, [callback])`. - * @property {Function} saturated - A callback that is called when the - * `queue.length()` hits the concurrency and further tasks will be queued. - * @property {Function} empty - A callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - A callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke like `cargo.idle()`. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke like `cargo.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke like `cargo.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. - */ - -/** - * 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`]{@link module:ControlFlow.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. - * - * @name cargo - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An asynchronous function for processing an array - * of queued tasks. Invoked with `(tasks, callback)`. - * @param {number} [payload=Infinity] - An optional `integer` for determining - * how many tasks should be processed per round; if omitted, the default is - * unlimited. - * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the cargo and inner queue. - * @example - * - * // create a cargo object with payload 2 - * var cargo = async.cargo(function(tasks, callback) { - * for (var i=0; i<tasks.length; i++) { - * console.log('hello ' + tasks[i].name); - * } - * callback(); - * }, 2); - * - * // add some items - * cargo.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * cargo.push({name: 'bar'}, function(err) { - * console.log('finished processing bar'); - * }); - * cargo.push({name: 'baz'}, function(err) { - * console.log('finished processing baz'); - * }); - */ -function cargo(worker, payload) { - return (0, _queue2.default)(worker, 1, payload); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/compose.js b/node_modules/async/compose.js deleted file mode 100644 index 47c49f62db4a04162e4389933a10094518587465..0000000000000000000000000000000000000000 --- a/node_modules/async/compose.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function () /*...args*/{ - return _seq2.default.apply(null, (0, _slice2.default)(arguments).reverse()); -}; - -var _seq = require('./seq'); - -var _seq2 = _interopRequireDefault(_seq); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -; - -/** - * 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. - * - * @name compose - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} an asynchronous function that is the composed - * asynchronous `functions` - * @example - * - * 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 - * }); - */ -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/concat.js b/node_modules/async/concat.js deleted file mode 100644 index c39ea000106ccb9f91f20759e4cd991d47b491a1..0000000000000000000000000000000000000000 --- a/node_modules/async/concat.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _concatLimit = require('./concatLimit'); - -var _concatLimit2 = _interopRequireDefault(_concatLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Applies `iteratee` to each item in `coll`, concatenating the results. Returns - * the concatenated list. The `iteratee`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 `coll` passed to the - * `iteratee` function. - * - * @name concat - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @example - * - * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { - * // files is now a list of filenames that exist in the 3 directories - * }); - */ -exports.default = (0, _doLimit2.default)(_concatLimit2.default, Infinity); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/concatLimit.js b/node_modules/async/concatLimit.js deleted file mode 100644 index f32cd4d347626c61ce997d8fff862ff24af55882..0000000000000000000000000000000000000000 --- a/node_modules/async/concatLimit.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll, limit, iteratee, callback) { - callback = callback || _noop2.default; - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _mapLimit2.default)(coll, limit, function (val, callback) { - _iteratee(val, function (err /*, ...args*/) { - if (err) return callback(err); - return callback(null, (0, _slice2.default)(arguments, 1)); - }); - }, function (err, mapResults) { - var result = []; - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - result = _concat.apply(result, mapResults[i]); - } - } - - return callback(err, result); - }); -}; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _mapLimit = require('./mapLimit'); - -var _mapLimit2 = _interopRequireDefault(_mapLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var _concat = Array.prototype.concat; - -/** - * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. - * - * @name concatLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/concatSeries.js b/node_modules/async/concatSeries.js deleted file mode 100644 index 541ab7d060d9b870b882a1bf3c54717d41c4c3fa..0000000000000000000000000000000000000000 --- a/node_modules/async/concatSeries.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _concatLimit = require('./concatLimit'); - -var _concatLimit2 = _interopRequireDefault(_concatLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. - * - * @name concatSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. - * The iteratee should complete with an array an array of results. - * Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -exports.default = (0, _doLimit2.default)(_concatLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/constant.js b/node_modules/async/constant.js deleted file mode 100644 index c825475bd3b3c78344eaa9b3fc6f06a95e6922fa..0000000000000000000000000000000000000000 --- a/node_modules/async/constant.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function () /*...values*/{ - var values = (0, _slice2.default)(arguments); - var args = [null].concat(values); - return function () /*...ignoredArgs, callback*/{ - var callback = arguments[arguments.length - 1]; - return callback.apply(this, args); - }; -}; - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -; - -/** - * Returns a function that when called, calls-back with the values provided. - * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to - * [`auto`]{@link module:ControlFlow.auto}. - * - * @name constant - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {...*} arguments... - Any number of arguments to automatically invoke - * callback with. - * @returns {AsyncFunction} Returns a function that when invoked, automatically - * invokes the callback with the previous given arguments. - * @example - * - * async.waterfall([ - * async.constant(42), - * function (value, next) { - * // value === 42 - * }, - * //... - * ], callback); - * - * async.waterfall([ - * async.constant(filename, "utf8"), - * fs.readFile, - * function (fileData, next) { - * //... - * } - * //... - * ], callback); - * - * async.auto({ - * hostname: async.constant("https://server.net/"), - * port: findFreePort, - * launchServer: ["hostname", "port", function (options, cb) { - * startServer(options, cb); - * }], - * //... - * }, callback); - */ -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/detect.js b/node_modules/async/detect.js deleted file mode 100644 index db467835859db77d6651d85a35198aed8ff8655a..0000000000000000000000000000000000000000 --- a/node_modules/async/detect.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _findGetResult = require('./internal/findGetResult'); - -var _findGetResult2 = _interopRequireDefault(_findGetResult); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. - - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @example - * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // result now equals the first file in the list that exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/detectLimit.js b/node_modules/async/detectLimit.js deleted file mode 100644 index 6bf656022254284851e735cce8608881cfb13d9a..0000000000000000000000000000000000000000 --- a/node_modules/async/detectLimit.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _findGetResult = require('./internal/findGetResult'); - -var _findGetResult2 = _interopRequireDefault(_findGetResult); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/detectSeries.js b/node_modules/async/detectSeries.js deleted file mode 100644 index 6fe16c956514c0677ac142187bed2aa551ae4959..0000000000000000000000000000000000000000 --- a/node_modules/async/detectSeries.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _detectLimit = require('./detectLimit'); - -var _detectLimit2 = _interopRequireDefault(_detectLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -exports.default = (0, _doLimit2.default)(_detectLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/dir.js b/node_modules/async/dir.js deleted file mode 100644 index 85fbcced030df81c5edfc959ffe3e0265e4cd8cf..0000000000000000000000000000000000000000 --- a/node_modules/async/dir.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _consoleFunc = require('./internal/consoleFunc'); - -var _consoleFunc2 = _interopRequireDefault(_consoleFunc); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Logs the result of an [`async` function]{@link AsyncFunction} 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. - * - * @name dir - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, {hello: name}); - * }, 1000); - * }; - * - * // in the node repl - * node> async.dir(hello, 'world'); - * {hello: 'world'} - */ -exports.default = (0, _consoleFunc2.default)('dir'); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/dist/async.js b/node_modules/async/dist/async.js deleted file mode 100644 index 72264ccb26e6024be714aad5c19b1e00de18f55a..0000000000000000000000000000000000000000 --- a/node_modules/async/dist/async.js +++ /dev/null @@ -1,5609 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.async = global.async || {}))); -}(this, (function (exports) { 'use strict'; - -function slice(arrayLike, start) { - start = start|0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for(var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; - } - return newArr; -} - -/** - * 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. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // 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: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ -var apply = function(fn/*, ...args*/) { - var args = slice(arguments, 1); - return function(/*callArgs*/) { - var callArgs = slice(arguments); - return fn.apply(null, args.concat(callArgs)); - }; -}; - -var initialParams = function (fn) { - return function (/*...args, callback*/) { - var args = slice(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; -}; - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} - -var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - -function fallback(fn) { - setTimeout(fn, 0); -} - -function wrap(defer) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; -} - -var _defer; - -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; -} - -var setImmediate$1 = wrap(_defer); - -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return initialParams(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if (isObject(result) && typeof result.then === 'function') { - result.then(function(value) { - invokeCallback(callback, null, value); - }, function(err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); -} - -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - setImmediate$1(rethrow, e); - } -} - -function rethrow(error) { - throw error; -} - -var supportsSymbol = typeof Symbol === 'function'; - -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} - -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; -} - -function applyEach$1(eachfn) { - return function(fns/*, ...args*/) { - var args = slice(arguments, 1); - var go = initialParams(function(args, callback) { - var that = this; - return eachfn(fns, function (fn, cb) { - wrapAsync(fn).apply(that, args.concat(cb)); - }, callback); - }); - if (args.length) { - return go.apply(this, args); - } - else { - return go; - } - }; -} - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -/** Built-in value references. */ -var Symbol$1 = root.Symbol; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; - -/** Built-in value references. */ -var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; - -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; - - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } - } - return result; -} - -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$1.toString; - -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString$1.call(value); -} - -/** `Object#toString` result references. */ -var nullTag = '[object Null]'; -var undefinedTag = '[object Undefined]'; - -/** Built-in value references. */ -var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; - -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); -} - -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]'; -var funcTag = '[object Function]'; -var genTag = '[object GeneratorFunction]'; -var proxyTag = '[object Proxy]'; - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; -} - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} - -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -var breakLoop = {}; - -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. -} - -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} - -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; - -var getIterator = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); -}; - -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; - -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; -} - -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - -/** Built-in value references. */ -var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; - -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); -}; - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -/** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ -function stubFalse() { - return false; -} - -/** Detect free variable `exports`. */ -var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; - -/** Built-in value references. */ -var Buffer = moduleExports ? root.Buffer : undefined; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - -/** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ -var isBuffer = nativeIsBuffer || stubFalse; - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER$1 = 9007199254740991; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$1 : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** `Object#toString` result references. */ -var argsTag$1 = '[object Arguments]'; -var arrayTag = '[object Array]'; -var boolTag = '[object Boolean]'; -var dateTag = '[object Date]'; -var errorTag = '[object Error]'; -var funcTag$1 = '[object Function]'; -var mapTag = '[object Map]'; -var numberTag = '[object Number]'; -var objectTag = '[object Object]'; -var regexpTag = '[object RegExp]'; -var setTag = '[object Set]'; -var stringTag = '[object String]'; -var weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]'; -var dataViewTag = '[object DataView]'; -var float32Tag = '[object Float32Array]'; -var float64Tag = '[object Float64Array]'; -var int8Tag = '[object Int8Array]'; -var int16Tag = '[object Int16Array]'; -var int32Tag = '[object Int32Array]'; -var uint8Tag = '[object Uint8Array]'; -var uint8ClampedTag = '[object Uint8ClampedArray]'; -var uint16Tag = '[object Uint16Array]'; -var uint32Tag = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = -typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = -typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = -typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = -typedArrayTags[uint32Tag] = true; -typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = -typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = -typedArrayTags[mapTag] = typedArrayTags[numberTag] = -typedArrayTags[objectTag] = typedArrayTags[regexpTag] = -typedArrayTags[setTag] = typedArrayTags[stringTag] = -typedArrayTags[weakMapTag] = false; - -/** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ -function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; -} - -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); - }; -} - -/** Detect free variable `exports`. */ -var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - -/** Detect free variable `process` from Node.js. */ -var freeProcess = moduleExports$1 && freeGlobal.process; - -/** Used to access faster Node.js helpers. */ -var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} -}()); - -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - -/** Used for built-in method references. */ -var objectProto$2 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$1.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; -} - -/** Used for built-in method references. */ -var objectProto$5 = Object.prototype; - -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; - - return value === proto; -} - -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object); - -/** Used for built-in method references. */ -var objectProto$4 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$4.hasOwnProperty; - -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$3.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; -} - -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); -} - -function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? {value: coll[i], key: i} : null; - } -} - -function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) - return null; - i++; - return {value: item.value, key: i}; - } -} - -function createObjectIterator(obj) { - var okeys = keys(obj); - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - return i < len ? {value: obj[key], key: key} : null; - }; -} - -function iterator(coll) { - if (isArrayLike(coll)) { - return createArrayIterator(coll); - } - - var iterator = getIterator(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); -} - -function onlyOnce(fn) { - return function() { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} - -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = once(callback || noop); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = iterator(obj); - var done = false; - var running = 0; - var looping = false; - - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } - else if (value === breakLoop || (done && running <= 0)) { - done = true; - return callback(null); - } - else if (!looping) { - replenish(); - } - } - - function replenish () { - looping = true; - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); - } - looping = false; - } - - replenish(); - }; -} - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); -} - -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = once(callback || noop); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if ((++completed === length) || value === breakLoop) { - callback(null); - } - } - - for (; index < length; index++) { - iteratee(coll[index], index, onlyOnce(iteratorCallback)); - } -} - -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = doLimit(eachOfLimit, Infinity); - -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * 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); - * }); - */ -var eachOf = function(coll, iteratee, callback) { - var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, wrapAsync(iteratee), callback); -}; - -function doParallel(fn) { - return function (obj, iteratee, callback) { - return fn(eachOf, obj, wrapAsync(iteratee), callback); - }; -} - -function _asyncMap(eachfn, arr, iteratee, callback) { - callback = callback || noop; - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = wrapAsync(iteratee); - - eachfn(arr, function (value, _, callback) { - var index = counter++; - _iteratee(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} - -/** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callback - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` 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 `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @example - * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file - * }); - */ -var map = doParallel(_asyncMap); - -/** - * Applies the provided arguments to each function in the array, calling - * `callback` after all functions have completed. If you only provide the first - * argument, `fns`, then it will return a function which lets you pass in the - * arguments as if it were a single function call. If more arguments are - * provided, `callback` is required while `args` is still optional. - * - * @name applyEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s - * to all call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument, `fns`, is provided, it will - * return a function which lets you pass in the arguments as if it were a single - * function call. The signature is `(..args, callback)`. If invoked with any - * arguments, `callback` is required. - * @example - * - * async.applyEach([enableSearch, updateSchema], 'bucket', callback); - * - * // partial application example: - * async.each( - * buckets, - * async.applyEach([enableSearch, updateSchema]), - * callback - * ); - */ -var applyEach = applyEach$1(map); - -function doParallelLimit(fn) { - return function (obj, limit, iteratee, callback) { - return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback); - }; -} - -/** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapLimit = doParallelLimit(_asyncMap); - -/** - * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. - * - * @name mapSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapSeries = doLimit(mapLimit, 1); - -/** - * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. - * - * @name applyEachSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.applyEach]{@link module:ControlFlow.applyEach} - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all - * call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument is provided, it will return - * a function which lets you pass in the arguments as if it were a single - * function call. - */ -var applyEachSeries = applyEach$1(mapSeries); - -/** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ -function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; -} - -/** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; -} - -/** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor = createBaseFor(); - -/** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); -} - -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} - -/** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); -} - -/** - * Determines the best order for running the {@link AsyncFunction}s 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 {@link AsyncFunction}s pass an error to their callback, the `auto` sequence - * will stop. Further tasks will not execute (so any other functions depending - * on it will not run), and the main `callback` is immediately called with the - * error. - * - * {@link AsyncFunction}s also receive an object containing the results of functions which - * have completed so far as the first argument, if they have dependencies. If a - * task function has no dependencies, it will only be passed a callback. - * - * @name auto - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Object} tasks - An object. Each of its properties is either a - * function or an array of requirements, with the {@link AsyncFunction} 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 one or two arguments: - * * a `results` object, containing the results of the previously executed - * functions, only passed if the task has any dependencies, - * * a `callback(err, result)` function, which must be called when finished, - * passing an `error` (which can be `null`) and the result of the function's - * execution. - * @param {number} [concurrency=Infinity] - An optional `integer` for - * determining the maximum number of tasks that can be run in parallel. By - * default, as many as possible. - * @param {Function} [callback] - 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. Invoked with (err, results). - * @returns undefined - * @example - * - * async.auto({ - * // this function will just be passed a callback - * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), - * showData: ['readData', function(results, cb) { - * // results.readData is the file's contents - * // ... - * }] - * }, callback); - * - * 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(results, 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 - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * 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); - * }); - */ -var auto = function (tasks, concurrency, callback) { - if (typeof concurrency === 'function') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = once(callback || noop); - var keys$$1 = keys(tasks); - var numTasks = keys$$1.length; - if (!numTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = numTasks; - } - - var results = {}; - var runningTasks = 0; - var hasError = false; - - var listeners = Object.create(null); - - var readyTasks = []; - - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; - - baseForOwn(tasks, function (task, key) { - if (!isArray(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } - - var dependencies = task.slice(0, task.length - 1); - var remainingDependencies = dependencies.length; - if (remainingDependencies === 0) { - enqueueTask(key, task); - readyToCheck.push(key); - return; - } - uncheckedDependencies[key] = remainingDependencies; - - arrayEach(dependencies, function (dependencyName) { - if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + - '` has a non-existent dependency `' + - dependencyName + '` in ' + - dependencies.join(', ')); - } - addListener(dependencyName, function () { - remainingDependencies--; - if (remainingDependencies === 0) { - enqueueTask(key, task); - } - }); - }); - }); - - checkForDeadlocks(); - processQueue(); - - function enqueueTask(key, task) { - readyTasks.push(function () { - runTask(key, task); - }); - } - - function processQueue() { - if (readyTasks.length === 0 && runningTasks === 0) { - return callback(null, results); - } - while(readyTasks.length && runningTasks < concurrency) { - var run = readyTasks.shift(); - run(); - } - - } - - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } - - taskListeners.push(fn); - } - - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - arrayEach(taskListeners, function (fn) { - fn(); - }); - processQueue(); - } - - - function runTask(key, task) { - if (hasError) return; - - var taskCallback = onlyOnce(function(err, result) { - runningTasks--; - if (arguments.length > 2) { - result = slice(arguments, 1); - } - if (err) { - var safeResults = {}; - baseForOwn(results, function(val, rkey) { - safeResults[rkey] = val; - }); - safeResults[key] = result; - hasError = true; - listeners = Object.create(null); - - callback(err, safeResults); - } else { - results[key] = result; - taskComplete(key); - } - }); - - runningTasks++; - var taskFn = wrapAsync(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } - - function checkForDeadlocks() { - // Kahn's algorithm - // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm - // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html - var currentTask; - var counter = 0; - while (readyToCheck.length) { - currentTask = readyToCheck.pop(); - counter++; - arrayEach(getDependents(currentTask), function (dependent) { - if (--uncheckedDependencies[dependent] === 0) { - readyToCheck.push(dependent); - } - }); - } - - if (counter !== numTasks) { - throw new Error( - 'async.auto cannot execute tasks due to a recursive dependency' - ); - } - } - - function getDependents(taskName) { - var result = []; - baseForOwn(tasks, function (task, key) { - if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { - result.push(key); - } - }); - return result; - } -}; - -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); -} - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined; -var symbolToString = symbolProto ? symbolProto.toString : undefined; - -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} - -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} - -/** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ -function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} - -/** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ -function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} - -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff'; -var rsComboMarksRange = '\\u0300-\\u036f'; -var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; -var rsComboSymbolsRange = '\\u20d0-\\u20ff'; -var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; -var rsVarRange = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsZWJ = '\\u200d'; - -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange$1 = '\\ud800-\\udfff'; -var rsComboMarksRange$1 = '\\u0300-\\u036f'; -var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; -var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; -var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; -var rsVarRange$1 = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange$1 + ']'; -var rsCombo = '[' + rsComboRange$1 + ']'; -var rsFitz = '\\ud83c[\\udffb-\\udfff]'; -var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; -var rsNonAstral = '[^' + rsAstralRange$1 + ']'; -var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; -var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; -var rsZWJ$1 = '\\u200d'; - -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?'; -var rsOptVar = '[' + rsVarRange$1 + ']?'; -var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; -var rsSeq = rsOptVar + reOptMod + rsOptJoin; -var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} - -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); -} - -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); -} - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; - -/** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ -function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; - - return castSlice(strSymbols, start, end).join(''); -} - -var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; -var FN_ARG_SPLIT = /,/; -var FN_ARG = /(=.+)?(\s*)$/; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; - -function parseParams(func) { - func = func.toString().replace(STRIP_COMMENTS, ''); - func = func.match(FN_ARGS)[2].replace(' ', ''); - func = func ? func.split(FN_ARG_SPLIT) : []; - func = func.map(function (arg){ - return trim(arg.replace(FN_ARG, '')); - }); - return func; -} - -/** - * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent - * tasks are specified as parameters to the function, after the usual callback - * parameter, with the parameter names matching the names of the tasks it - * depends on. This can provide even more readable task graphs which can be - * easier to maintain. - * - * If a final callback is specified, the task results are similarly injected, - * specified as named parameters after the initial error parameter. - * - * The autoInject function is purely syntactic sugar and its semantics are - * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. - * - * @name autoInject - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.auto]{@link module:ControlFlow.auto} - * @category Control Flow - * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of - * the form 'func([dependencies...], callback). 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 `callback` parameter is 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. The remaining parameters name other tasks on - * which the task is dependent, and the results from those tasks are the - * arguments of those parameters. - * @param {Function} [callback] - 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, and a `results` object with any completed - * task results, similar to `auto`. - * @example - * - * // The example from `auto` can be rewritten as follows: - * async.autoInject({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // 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: function(get_data, make_folder, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }, - * email_link: function(write_file, callback) { - * // once the file is written let's email a link to it... - * // write_file contains the filename returned by write_file. - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * } - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - * - * // If you are using a JS minifier that mangles parameter names, `autoInject` - * // will not work with plain functions, since the parameter names will be - * // collapsed to a single letter identifier. To work around this, you can - * // explicitly specify the names of the parameters your task function needs - * // in an array, similar to Angular.js dependency injection. - * - * // This still has an advantage over plain `auto`, since the results a task - * // depends on are still spread into arguments. - * async.autoInject({ - * //... - * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(write_file, callback) { - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * }] - * //... - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - */ -function autoInject(tasks, callback) { - var newTasks = {}; - - baseForOwn(tasks, function (taskFn, key) { - var params; - var fnIsAsync = isAsync(taskFn); - var hasNoDeps = - (!fnIsAsync && taskFn.length === 1) || - (fnIsAsync && taskFn.length === 0); - - if (isArray(taskFn)) { - params = taskFn.slice(0, -1); - taskFn = taskFn[taskFn.length - 1]; - - newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); - } else if (hasNoDeps) { - // no dependencies, use the function as-is - newTasks[key] = taskFn; - } else { - params = parseParams(taskFn); - if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { - throw new Error("autoInject task functions require explicit parameters."); - } - - // remove callback param - if (!fnIsAsync) params.pop(); - - newTasks[key] = params.concat(newTask); - } - - function newTask(results, taskCb) { - var newArgs = arrayMap(params, function (name) { - return results[name]; - }); - newArgs.push(taskCb); - wrapAsync(taskFn).apply(null, newArgs); - } - }); - - auto(newTasks, callback); -} - -// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation -// used for queues. This implementation assumes that the node provided by the user can be modified -// to adjust the next and last properties. We implement only the minimal functionality -// for queue support. -function DLL() { - this.head = this.tail = null; - this.length = 0; -} - -function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; -} - -DLL.prototype.removeLink = function(node) { - if (node.prev) node.prev.next = node.next; - else this.head = node.next; - if (node.next) node.next.prev = node.prev; - else this.tail = node.prev; - - node.prev = node.next = null; - this.length -= 1; - return node; -}; - -DLL.prototype.empty = function () { - while(this.head) this.shift(); - return this; -}; - -DLL.prototype.insertAfter = function(node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode; - else this.tail = newNode; - node.next = newNode; - this.length += 1; -}; - -DLL.prototype.insertBefore = function(node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode; - else this.head = newNode; - node.prev = newNode; - this.length += 1; -}; - -DLL.prototype.unshift = function(node) { - if (this.head) this.insertBefore(this.head, node); - else setInitial(this, node); -}; - -DLL.prototype.push = function(node) { - if (this.tail) this.insertAfter(this.tail, node); - else setInitial(this, node); -}; - -DLL.prototype.shift = function() { - return this.head && this.removeLink(this.head); -}; - -DLL.prototype.pop = function() { - return this.tail && this.removeLink(this.tail); -}; - -DLL.prototype.toArray = function () { - var arr = Array(this.length); - var curr = this.head; - for(var idx = 0; idx < this.length; idx++) { - arr[idx] = curr.data; - curr = curr.next; - } - return arr; -}; - -DLL.prototype.remove = function (testFn) { - var curr = this.head; - while(!!curr) { - var next = curr.next; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; -}; - -function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } - else if(concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - - var _worker = wrapAsync(worker); - var numRunning = 0; - var workersList = []; - - var processingScheduled = false; - function _insert(data, insertAtFront, 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 setImmediate$1(function() { - q.drain(); - }); - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - callback: callback || noop - }; - - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - } - - if (!processingScheduled) { - processingScheduled = true; - setImmediate$1(function() { - processingScheduled = false; - q.process(); - }); - } - } - - function _next(tasks) { - return function(err){ - numRunning -= 1; - - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; - - var index = baseIndexOf(workersList, task, 0); - if (index === 0) { - workersList.shift(); - } else if (index > 0) { - workersList.splice(index, 1); - } - - task.callback.apply(task, arguments); - - if (err != null) { - q.error(err, task.data); - } - } - - if (numRunning <= (q.concurrency - q.buffer) ) { - q.unsaturated(); - } - - if (q.idle()) { - q.drain(); - } - q.process(); - }; - } - - var isProcessing = false; - var q = { - _tasks: new DLL(), - concurrency: concurrency, - payload: payload, - saturated: noop, - unsaturated:noop, - buffer: concurrency / 4, - empty: noop, - drain: noop, - error: noop, - started: false, - paused: false, - push: function (data, callback) { - _insert(data, false, callback); - }, - kill: function () { - q.drain = noop; - q._tasks.empty(); - }, - unshift: function (data, callback) { - _insert(data, true, callback); - }, - remove: function (testFn) { - q._tasks.remove(testFn); - }, - process: function () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while(!q.paused && numRunning < q.concurrency && q._tasks.length){ - var tasks = [], data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } - - numRunning += 1; - - if (q._tasks.length === 0) { - q.empty(); - } - - if (numRunning === q.concurrency) { - q.saturated(); - } - - var cb = onlyOnce(_next(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length: function () { - return q._tasks.length; - }, - running: function () { - return numRunning; - }, - workersList: function () { - return workersList; - }, - idle: function() { - return q._tasks.length + numRunning === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { return; } - q.paused = false; - setImmediate$1(q.process); - } - }; - return q; -} - -/** - * A cargo of tasks for the worker function to complete. Cargo inherits all of - * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. - * @typedef {Object} CargoObject - * @memberOf module:ControlFlow - * @property {Function} length - A function returning the number of items - * waiting to be processed. Invoke like `cargo.length()`. - * @property {number} 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. - * @property {Function} push - 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. Invoke like `cargo.push(task, [callback])`. - * @property {Function} saturated - A callback that is called when the - * `queue.length()` hits the concurrency and further tasks will be queued. - * @property {Function} empty - A callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - A callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke like `cargo.idle()`. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke like `cargo.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke like `cargo.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. - */ - -/** - * 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`]{@link module:ControlFlow.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. - * - * @name cargo - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An asynchronous function for processing an array - * of queued tasks. Invoked with `(tasks, callback)`. - * @param {number} [payload=Infinity] - An optional `integer` for determining - * how many tasks should be processed per round; if omitted, the default is - * unlimited. - * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the cargo and inner queue. - * @example - * - * // create a cargo object with payload 2 - * var cargo = async.cargo(function(tasks, callback) { - * for (var i=0; i<tasks.length; i++) { - * console.log('hello ' + tasks[i].name); - * } - * callback(); - * }, 2); - * - * // add some items - * cargo.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * cargo.push({name: 'bar'}, function(err) { - * console.log('finished processing bar'); - * }); - * cargo.push({name: 'baz'}, function(err) { - * console.log('finished processing baz'); - * }); - */ -function cargo(worker, payload) { - return queue(worker, 1, payload); -} - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. - * - * @name eachOfSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Invoked with (err). - */ -var eachOfSeries = doLimit(eachOfLimit, 1); - -/** - * Reduces `coll` into a single value using an async `iteratee` 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. - * - * @name reduce - * @static - * @memberOf module:Collections - * @method - * @alias inject - * @alias foldl - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - * @example - * - * 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 - * }); - */ -function reduce(coll, memo, iteratee, callback) { - callback = once(callback || noop); - var _iteratee = wrapAsync(iteratee); - eachOfSeries(coll, function(x, i, callback) { - _iteratee(memo, x, function(err, v) { - memo = v; - callback(err); - }); - }, function(err) { - callback(err, memo); - }); -} - -/** - * 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]{@link module:ControlFlow.compose} with the arguments reversed. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name seq - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.compose]{@link module:ControlFlow.compose} - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} a function that composes the `functions` in order - * @example - * - * // 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 }); - * } - * }); - * }); - */ -function seq(/*...functions*/) { - var _functions = arrayMap(arguments, wrapAsync); - return function(/*...args*/) { - var args = slice(arguments); - var that = this; - - var cb = args[args.length - 1]; - if (typeof cb == 'function') { - args.pop(); - } else { - cb = noop; - } - - reduce(_functions, args, function(newargs, fn, cb) { - fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) { - var nextargs = slice(arguments, 1); - cb(err, nextargs); - })); - }, - function(err, results) { - cb.apply(that, [err].concat(results)); - }); - }; -} - -/** - * 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. - * - * @name compose - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} an asynchronous function that is the composed - * asynchronous `functions` - * @example - * - * 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 - * }); - */ -var compose = function(/*...args*/) { - return seq.apply(null, slice(arguments).reverse()); -}; - -var _concat = Array.prototype.concat; - -/** - * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. - * - * @name concatLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -var concatLimit = function(coll, limit, iteratee, callback) { - callback = callback || noop; - var _iteratee = wrapAsync(iteratee); - mapLimit(coll, limit, function(val, callback) { - _iteratee(val, function(err /*, ...args*/) { - if (err) return callback(err); - return callback(null, slice(arguments, 1)); - }); - }, function(err, mapResults) { - var result = []; - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - result = _concat.apply(result, mapResults[i]); - } - } - - return callback(err, result); - }); -}; - -/** - * Applies `iteratee` to each item in `coll`, concatenating the results. Returns - * the concatenated list. The `iteratee`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 `coll` passed to the - * `iteratee` function. - * - * @name concat - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @example - * - * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { - * // files is now a list of filenames that exist in the 3 directories - * }); - */ -var concat = doLimit(concatLimit, Infinity); - -/** - * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. - * - * @name concatSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. - * The iteratee should complete with an array an array of results. - * Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -var concatSeries = doLimit(concatLimit, 1); - -/** - * Returns a function that when called, calls-back with the values provided. - * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to - * [`auto`]{@link module:ControlFlow.auto}. - * - * @name constant - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {...*} arguments... - Any number of arguments to automatically invoke - * callback with. - * @returns {AsyncFunction} Returns a function that when invoked, automatically - * invokes the callback with the previous given arguments. - * @example - * - * async.waterfall([ - * async.constant(42), - * function (value, next) { - * // value === 42 - * }, - * //... - * ], callback); - * - * async.waterfall([ - * async.constant(filename, "utf8"), - * fs.readFile, - * function (fileData, next) { - * //... - * } - * //... - * ], callback); - * - * async.auto({ - * hostname: async.constant("https://server.net/"), - * port: findFreePort, - * launchServer: ["hostname", "port", function (options, cb) { - * startServer(options, cb); - * }], - * //... - * }, callback); - */ -var constant = function(/*...values*/) { - var values = slice(arguments); - var args = [null].concat(values); - return function (/*...ignoredArgs, callback*/) { - var callback = arguments[arguments.length - 1]; - return callback.apply(this, args); - }; -}; - -/** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ -function identity(value) { - return value; -} - -function _createTester(check, getResult) { - return function(eachfn, arr, iteratee, cb) { - cb = cb || noop; - var testPassed = false; - var testResult; - eachfn(arr, function(value, _, callback) { - iteratee(value, function(err, result) { - if (err) { - callback(err); - } else if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - callback(null, breakLoop); - } else { - callback(); - } - }); - }, function(err) { - if (err) { - cb(err); - } else { - cb(null, testPassed ? testResult : getResult(false)); - } - }); - }; -} - -function _findGetResult(v, x) { - return x; -} - -/** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. - - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @example - * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // result now equals the first file in the list that exists - * }); - */ -var detect = doParallel(_createTester(identity, _findGetResult)); - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -var detectLimit = doParallelLimit(_createTester(identity, _findGetResult)); - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -var detectSeries = doLimit(detectLimit, 1); - -function consoleFunc(name) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - args.push(function (err/*, ...args*/) { - var args = slice(arguments, 1); - if (typeof console === 'object') { - if (err) { - if (console.error) { - console.error(err); - } - } else if (console[name]) { - arrayEach(args, function (x) { - console[name](x); - }); - } - } - }); - wrapAsync(fn).apply(null, args); - }; -} - -/** - * Logs the result of an [`async` function]{@link AsyncFunction} 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. - * - * @name dir - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, {hello: name}); - * }, 1000); - * }; - * - * // in the node repl - * node> async.dir(hello, 'world'); - * {hello: 'world'} - */ -var dir = consoleFunc('dir'); - -/** - * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in - * the order of operations, the arguments `test` and `fn` are switched. - * - * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. - * @name doDuring - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.during]{@link module:ControlFlow.during} - * @category Control Flow - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `fn`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error if one occurred, otherwise `null`. - */ -function doDuring(fn, test, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - - function next(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - args.push(check); - _test.apply(this, args); - } - - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - - check(null, true); - -} - -/** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - */ -function doWhilst(iteratee, test, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - if (test.apply(this, args)) return _iteratee(next); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} - -/** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function doUntil(iteratee, test, callback) { - doWhilst(iteratee, function() { - return !test.apply(this, arguments); - }, callback); -} - -/** - * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that - * is passed a callback in the form of `function (err, truth)`. If error is - * passed to `test` or `fn`, the main callback is immediately called with the - * value of the error. - * - * @name during - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (callback). - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error, if one occurred, otherwise `null`. - * @example - * - * var count = 0; - * - * async.during( - * function (callback) { - * return callback(null, count < 5); - * }, - * function (callback) { - * count++; - * setTimeout(callback, 1000); - * }, - * function (err) { - * // 5 seconds have passed - * } - * ); - */ -function during(test, fn, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - - function next(err) { - if (err) return callback(err); - _test(check); - } - - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - - _test(check); -} - -function _withoutIndex(iteratee) { - return function (value, index, callback) { - return iteratee(value, callback); - }; -} - -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` 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 `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // 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 - * }); - * - * // 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'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} - -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit$1(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} - -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -var eachSeries = doLimit(eachLimit$1, 1); - -/** - * 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. ES2017 `async` functions are returned as-is -- they are immune - * to Zalgo's corrupting influences, as they always resolve on a later tick. - * - * @name ensureAsync - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - an async function, one that expects a node-style - * callback as its last argument. - * @returns {AsyncFunction} Returns a wrapped function with the exact same call - * signature as the function passed in. - * @example - * - * 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); - */ -function ensureAsync(fn) { - if (isAsync(fn)) return fn; - return initialParams(function (args, callback) { - var sync = true; - args.push(function () { - var innerArgs = arguments; - if (sync) { - setImmediate$1(function () { - callback.apply(null, innerArgs); - }); - } else { - callback.apply(null, innerArgs); - } - }); - fn.apply(this, args); - sync = false; - }); -} - -function notId(v) { - return !v; -} - -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -var every = doParallel(_createTester(notId, notId)); - -/** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everyLimit = doParallelLimit(_createTester(notId, notId)); - -/** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everySeries = doLimit(everyLimit, 1); - -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; -} - -function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, function (x, index, callback) { - iteratee(x, function (err, v) { - truthValues[index] = !!v; - callback(err); - }); - }, function (err) { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); -} - -function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, function (x, index, callback) { - iteratee(x, function (err, v) { - if (err) { - callback(err); - } else { - if (v) { - results.push({index: index, value: x}); - } - callback(); - } - }); - }, function (err) { - if (err) { - callback(err); - } else { - callback(null, arrayMap(results.sort(function (a, b) { - return a.index - b.index; - }), baseProperty('value'))); - } - }); -} - -function _filter(eachfn, coll, iteratee, callback) { - var filter = isArrayLike(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, wrapAsync(iteratee), callback || noop); -} - -/** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files - * }); - */ -var filter = doParallel(_filter); - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var filterLimit = doParallelLimit(_filter); - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - */ -var filterSeries = doLimit(filterLimit, 1); - -/** - * 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. - * - * @name forever - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} fn - an async function to call repeatedly. - * Invoked with (next). - * @param {Function} [errback] - when `fn` passes an error to it's callback, - * this function will be called, and execution stops. Invoked with (err). - * @example - * - * 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. - * } - * ); - */ -function forever(fn, errback) { - var done = onlyOnce(errback || noop); - var task = wrapAsync(ensureAsync(fn)); - - function next(err) { - if (err) return done(err); - task(next); - } - next(); -} - -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. - * - * @name groupByLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupByLimit = function(coll, limit, iteratee, callback) { - callback = callback || noop; - var _iteratee = wrapAsync(iteratee); - mapLimit(coll, limit, function(val, callback) { - _iteratee(val, function(err, key) { - if (err) return callback(err); - return callback(null, {key: key, val: val}); - }); - }, function(err, mapResults) { - var result = {}; - // from MDN, handle object having an `hasOwnProperty` prop - var hasOwnProperty = Object.prototype.hasOwnProperty; - - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - var key = mapResults[i].key; - var val = mapResults[i].val; - - if (hasOwnProperty.call(result, key)) { - result[key].push(val); - } else { - result[key] = [val]; - } - } - } - - return callback(err, result); - }); -}; - -/** - * Returns a new object, where each value corresponds to an array of items, from - * `coll`, that returned the corresponding key. That is, the keys of the object - * correspond to the values passed to the `iteratee` callback. - * - * Note: Since this function applies the `iteratee` to each item in parallel, - * there is no guarantee that the `iteratee` functions will complete in order. - * However, the values for each key in the `result` will be in the same order as - * the original `coll`. For Objects, the values will roughly be in the order of - * the original Objects' keys (but this can vary across JavaScript engines). - * - * @name groupBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @example - * - * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { - * db.findById(userId, function(err, user) { - * if (err) return callback(err); - * return callback(null, user.age); - * }); - * }, function(err, result) { - * // result is object containing the userIds grouped by age - * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; - * }); - */ -var groupBy = doLimit(groupByLimit, Infinity); - -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. - * - * @name groupBySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupBySeries = doLimit(groupByLimit, 1); - -/** - * 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. - * - * @name log - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, 'hello ' + name); - * }, 1000); - * }; - * - * // in the node repl - * node> async.log(hello, 'world'); - * 'hello world' - */ -var log = consoleFunc('log'); - -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a - * time. - * - * @name mapValuesLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -function mapValuesLimit(obj, limit, iteratee, callback) { - callback = once(callback || noop); - var newObj = {}; - var _iteratee = wrapAsync(iteratee); - eachOfLimit(obj, limit, function(val, key, next) { - _iteratee(val, key, function (err, result) { - if (err) return next(err); - newObj[key] = result; - next(); - }); - }, function (err) { - callback(err, newObj); - }); -} - -/** - * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. - * - * Produces a new Object by mapping each value of `obj` through the `iteratee` - * function. The `iteratee` is called each `value` and `key` from `obj` and a - * callback for when it has finished processing. Each of these callbacks takes - * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` - * passes an error to its callback, the main `callback` (for the `mapValues` - * function) is immediately called with the error. - * - * Note, the order of the keys in the result is not guaranteed. The keys will - * be roughly in the order they complete, (but this is very engine-specific) - * - * @name mapValues - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @example - * - * async.mapValues({ - * f1: 'file1', - * f2: 'file2', - * f3: 'file3' - * }, function (file, key, callback) { - * fs.stat(file, callback); - * }, function(err, result) { - * // result is now a map of stats for each file, e.g. - * // { - * // f1: [stats for file1], - * // f2: [stats for file2], - * // f3: [stats for file3] - * // } - * }); - */ - -var mapValues = doLimit(mapValuesLimit, Infinity); - -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. - * - * @name mapValuesSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -var mapValuesSeries = doLimit(mapValuesLimit, 1); - -function has(obj, key) { - return key in obj; -} - -/** - * 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`. - * - * @name memoize - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function to proxy and cache results from. - * @param {Function} 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. - * @returns {AsyncFunction} a memoized version of `fn` - * @example - * - * 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 - * }); - */ -function memoize(fn, hasher) { - var memo = Object.create(null); - var queues = Object.create(null); - hasher = hasher || identity; - var _fn = wrapAsync(fn); - var memoized = initialParams(function memoized(args, callback) { - var key = hasher.apply(null, args); - if (has(memo, key)) { - setImmediate$1(function() { - callback.apply(null, memo[key]); - }); - } else if (has(queues, key)) { - queues[key].push(callback); - } else { - queues[key] = [callback]; - _fn.apply(null, args.concat(function(/*args*/) { - var args = slice(arguments); - memo[key] = args; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, args); - } - })); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; -} - -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `process.nextTick`. In the browser it will use `setImmediate` 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. - * - * @name nextTick - * @static - * @memberOf module:Utils - * @method - * @see [async.setImmediate]{@link module:Utils.setImmediate} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -var _defer$1; - -if (hasNextTick) { - _defer$1 = process.nextTick; -} else if (hasSetImmediate) { - _defer$1 = setImmediate; -} else { - _defer$1 = fallback; -} - -var nextTick = wrap(_defer$1); - -function _parallel(eachfn, tasks, callback) { - callback = callback || noop; - var results = isArrayLike(tasks) ? [] : {}; - - eachfn(tasks, function (task, key, callback) { - wrapAsync(task)(function (err, result) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } - results[key] = result; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} - -/** - * Run the `tasks` collection 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. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * 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 {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * - * @example - * 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} - * }); - */ -function parallelLimit(tasks, callback) { - _parallel(eachOf, tasks, callback); -} - -/** - * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a - * time. - * - * @name parallelLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.parallel]{@link module:ControlFlow.parallel} - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - */ -function parallelLimit$1(tasks, limit, callback) { - _parallel(_eachOfLimit(limit), tasks, callback); -} - -/** - * A queue of tasks for the worker function to complete. - * @typedef {Object} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} 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. - * @property {Function} push - 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. Invoke with `queue.push(task, [callback])`, - * @property {Function} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a callback that is called when the number of - * running workers hits the `concurrency` limit, and further tasks will be - * queued. - * @property {Function} unsaturated - a callback that is called when the number - * of running workers is less than the `concurrency` & `buffer` limits, and - * further tasks will not be queued. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - a callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} error - a callback that is called when a task errors. - * Has the signature `function(error, task)`. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - */ - -/** - * 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. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - 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. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // 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'); - * }); - */ -var queue$1 = function (worker, concurrency) { - var _worker = wrapAsync(worker); - return queue(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); -}; - -/** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} 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. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. 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. - */ -var priorityQueue = function(worker, concurrency) { - // Start with a normal queue - var q = queue$1(worker, concurrency); - - // Override push to accept second parameter representing priority - q.push = function(data, priority, callback) { - if (callback == null) callback = noop; - if (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 setImmediate$1(function() { - q.drain(); - }); - } - - priority = priority || 0; - var nextNode = q._tasks.head; - while (nextNode && priority >= nextNode.priority) { - nextNode = nextNode.next; - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - priority: priority, - callback: callback - }; - - if (nextNode) { - q._tasks.insertBefore(nextNode, item); - } else { - q._tasks.push(item); - } - } - setImmediate$1(q.process); - }; - - // Remove unshift function - delete q.unshift; - - return q; -}; - -/** - * Runs the `tasks` array of functions in parallel, without waiting until the - * previous function has completed. Once any of the `tasks` complete or pass an - * error to its callback, the main `callback` is immediately called. It's - * equivalent to `Promise.race()`. - * - * @name race - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} - * to run. Each function can complete with an optional `result` value. - * @param {Function} callback - A callback to run once any of the functions have - * completed. This function gets an error or result from the first function that - * completed. Invoked with (err, result). - * @returns undefined - * @example - * - * async.race([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // main callback - * function(err, result) { - * // the result will be equal to 'two' as it finishes earlier - * }); - */ -function race(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); - if (!tasks.length) return callback(); - for (var i = 0, l = tasks.length; i < l; i++) { - wrapAsync(tasks[i])(callback); - } -} - -/** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - */ -function reduceRight (array, memo, iteratee, callback) { - var reversed = slice(array).reverse(); - reduce(reversed, memo, iteratee, callback); -} - -/** - * Wraps the async function in another function that always completes with a - * result object, even when it errors. - * - * The result object has either the property `error` or `value`. - * - * @name reflect - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function you want to wrap - * @returns {Function} - A function that always passes null to it's callback as - * the error. The second argument to the callback will be an `object` with - * either an `error` or a `value` property. - * @example - * - * async.parallel([ - * async.reflect(function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }), - * async.reflect(function(callback) { - * // do some more stuff but error ... - * callback('bad stuff happened'); - * }), - * async.reflect(function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * }) - * ], - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = 'bad stuff happened' - * // results[2].value = 'two' - * }); - */ -function reflect(fn) { - var _fn = wrapAsync(fn); - return initialParams(function reflectOn(args, reflectCallback) { - args.push(function callback(error, cbArg) { - if (error) { - reflectCallback(null, { error: error }); - } else { - var value; - if (arguments.length <= 2) { - value = cbArg; - } else { - value = slice(arguments, 1); - } - reflectCallback(null, { value: value }); - } - }); - - return _fn.apply(this, args); - }); -} - -/** - * A helper function that wraps an array or an object of functions with `reflect`. - * - * @name reflectAll - * @static - * @memberOf module:Utils - * @method - * @see [async.reflect]{@link module:Utils.reflect} - * @category Util - * @param {Array|Object|Iterable} tasks - The collection of - * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. - * @returns {Array} Returns an array of async functions, each wrapped in - * `async.reflect` - * @example - * - * let tasks = [ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * // do some more stuff but error ... - * callback(new Error('bad stuff happened')); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = Error('bad stuff happened') - * // results[2].value = 'two' - * }); - * - * // an example using an object instead of an array - * let tasks = { - * one: function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * two: function(callback) { - * callback('two'); - * }, - * three: function(callback) { - * setTimeout(function() { - * callback(null, 'three'); - * }, 100); - * } - * }; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results.one.value = 'one' - * // results.two.error = 'two' - * // results.three.value = 'three' - * }); - */ -function reflectAll(tasks) { - var results; - if (isArray(tasks)) { - results = arrayMap(tasks, reflect); - } else { - results = {}; - baseForOwn(tasks, function(task, key) { - results[key] = reflect.call(this, task); - }); - } - return results; -} - -function reject$1(eachfn, arr, iteratee, callback) { - _filter(eachfn, arr, function(value, cb) { - iteratee(value, function(err, v) { - cb(err, !v); - }); - }, callback); -} - -/** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); - * }); - */ -var reject = doParallel(reject$1); - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a - * time. - * - * @name rejectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectLimit = doParallelLimit(reject$1); - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. - * - * @name rejectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectSeries = doLimit(rejectLimit, 1); - -/** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ -function constant$1(value) { - return function() { - return value; - }; -} - -/** - * 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. - * - * @name retry - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @see [async.retryable]{@link module:ControlFlow.retryable} - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an - * object with `times` and `interval` or a number. - * * `times` - The number of attempts to make before giving up. The default - * is `5`. - * * `interval` - The time to wait between retries, in milliseconds. The - * default is `0`. The interval may also be specified as a function of the - * retry count (see example). - * * `errorFilter` - An optional synchronous function that is invoked on - * erroneous result. If it returns `true` the retry attempts will continue; - * if the function returns `false` the retry flow is aborted with the current - * attempt's error and result being returned to the final callback. - * Invoked with (err). - * * If `opts` is a number, the number specifies the number of times to retry, - * with the default interval of `0`. - * @param {AsyncFunction} task - An async function to retry. - * Invoked with (callback). - * @param {Function} [callback] - 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`. Invoked - * with (err, results). - * - * @example - * - * // The `retry` function can be used as a stand-alone control flow by passing - * // a callback, as shown below: - * - * // try calling apiMethod 3 times - * async.retry(3, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 3 times, waiting 200 ms between each retry - * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 10 times with exponential backoff - * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) - * async.retry({ - * times: 10, - * interval: function(retryCount) { - * return 50 * Math.pow(2, retryCount); - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod the default 5 times no delay between each retry - * async.retry(apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod only when error condition satisfies, all other - * // errors will abort the retry control flow and return to final callback - * async.retry({ - * errorFilter: function(err) { - * return err.message === 'Temporary error'; // only retry on a specific error - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // to retry individual methods that are not as reliable within other - * // control flow functions, use the `retryable` wrapper: - * async.auto({ - * users: api.getUsers.bind(api), - * payments: async.retryable(3, api.getPayments.bind(api)) - * }, function(err, results) { - * // do something with the results - * }); - * - */ -function retry(opts, task, callback) { - var DEFAULT_TIMES = 5; - var DEFAULT_INTERVAL = 0; - - var options = { - times: DEFAULT_TIMES, - intervalFunc: constant$1(DEFAULT_INTERVAL) - }; - - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; - - acc.intervalFunc = typeof t.interval === 'function' ? - t.interval : - constant$1(+t.interval || DEFAULT_INTERVAL); - - acc.errorFilter = t.errorFilter; - } else if (typeof t === 'number' || typeof t === 'string') { - acc.times = +t || DEFAULT_TIMES; - } else { - throw new Error("Invalid arguments for async.retry"); - } - } - - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || noop; - task = opts; - } else { - parseTimes(options, opts); - callback = callback || noop; - } - - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } - - var _task = wrapAsync(task); - - var attempt = 1; - function retryAttempt() { - _task(function(err) { - if (err && attempt++ < options.times && - (typeof options.errorFilter != 'function' || - options.errorFilter(err))) { - setTimeout(retryAttempt, options.intervalFunc(attempt)); - } else { - callback.apply(null, arguments); - } - }); - } - - retryAttempt(); -} - -/** - * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method - * wraps a task and makes it retryable, rather than immediately calling it - * with retries. - * - * @name retryable - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.retry]{@link module:ControlFlow.retry} - * @category Control Flow - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional - * options, exactly the same as from `retry` - * @param {AsyncFunction} task - the asynchronous function to wrap. - * This function will be passed any arguments passed to the returned wrapper. - * Invoked with (...args, callback). - * @returns {AsyncFunction} The wrapped function, which when invoked, will - * retry on an error, based on the parameters specified in `opts`. - * This function will accept the same parameters as `task`. - * @example - * - * async.auto({ - * dep1: async.retryable(3, getFromFlakyService), - * process: ["dep1", async.retryable(3, function (results, cb) { - * maybeProcessData(results.dep1, cb); - * })] - * }, callback); - */ -var retryable = function (opts, task) { - if (!task) { - task = opts; - opts = null; - } - var _task = wrapAsync(task); - return initialParams(function (args, callback) { - function taskFn(cb) { - _task.apply(null, args.concat(cb)); - } - - if (opts) retry(opts, taskFn, callback); - else retry(taskFn, callback); - - }); -}; - -/** - * Run the functions in the `tasks` collection 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 {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](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. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - 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. Invoked - * with (err, result). - * @example - * 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'] - * }); - * - * 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} - * }); - */ -function series(tasks, callback) { - _parallel(eachOfSeries, tasks, callback); -} - -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -var some = doParallel(_createTester(Boolean, identity)); - -/** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someLimit = doParallelLimit(_createTester(Boolean, identity)); - -/** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someSeries = doLimit(someLimit, 1); - -/** - * Sorts a list by the results of running each `coll` value through an async - * `iteratee`. - * - * @name sortBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a value to use as the sort criteria as - * its `result`. - * Invoked with (item, callback). - * @param {Function} callback - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is the items - * from the original `coll` sorted by the values returned by the `iteratee` - * calls. Invoked with (err, results). - * @example - * - * 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 - * }); - * - * // By modifying the callback parameter the - * // sorting order can be influenced: - * - * // 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 - * }); - */ -function sortBy (coll, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - map(coll, function (x, callback) { - _iteratee(x, function (err, criteria) { - if (err) return callback(err); - callback(null, {value: x, criteria: criteria}); - }); - }, function (err, results) { - if (err) return callback(err); - callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); - }); - - function comparator(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - } -} - -/** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ -function timeout(asyncFn, milliseconds, info) { - var fn = wrapAsync(asyncFn); - - return initialParams(function (args, callback) { - var timedOut = false; - var timer; - - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } - - args.push(function () { - if (!timedOut) { - callback.apply(null, arguments); - clearTimeout(timer); - } - }); - - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args); - }); -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeCeil = Math.ceil; -var nativeMax = Math.max; - -/** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ -function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); - - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; -} - -/** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. - * - * @name timesLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - */ -function timeLimit(count, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); -} - -/** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. - * - * @name times - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @example - * - * // 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 - * }); - */ -var times = doLimit(timeLimit, Infinity); - -/** - * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. - * - * @name timesSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - */ -var timesSeries = doLimit(timeLimit, 1); - -/** - * A relative of `reduce`. Takes an Object or Array, and iterates over each - * element in series, each step potentially mutating an `accumulator` value. - * The type of the accumulator defaults to the type of collection passed in. - * - * @name transform - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} [accumulator] - The initial state of the transform. If omitted, - * it will default to an empty Object or Array, depending on the type of `coll` - * @param {AsyncFunction} iteratee - A function applied to each item in the - * collection that potentially modifies the accumulator. - * Invoked with (accumulator, item, key, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the transformed accumulator. - * Invoked with (err, result). - * @example - * - * async.transform([1,2,3], function(acc, item, index, callback) { - * // pointless async: - * process.nextTick(function() { - * acc.push(item * 2) - * callback(null) - * }); - * }, function(err, result) { - * // result is now equal to [2, 4, 6] - * }); - * - * @example - * - * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { - * setImmediate(function () { - * obj[key] = val * 2; - * callback(); - * }) - * }, function (err, result) { - * // result is equal to {a: 2, b: 4, c: 6} - * }) - */ -function transform (coll, accumulator, iteratee, callback) { - if (arguments.length <= 3) { - callback = iteratee; - iteratee = accumulator; - accumulator = isArray(coll) ? [] : {}; - } - callback = once(callback || noop); - var _iteratee = wrapAsync(iteratee); - - eachOf(coll, function(v, k, cb) { - _iteratee(accumulator, v, k, cb); - }, function(err) { - callback(err, accumulator); - }); -} - -/** - * It runs each task in series but stops whenever any of the functions were - * successful. If one of the tasks were successful, the `callback` will be - * passed the result of the successful task. If all tasks fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name tryEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection 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. - * @param {Function} [callback] - An optional callback which is called when one - * of the tasks has succeeded, or all have failed. It receives the `err` and - * `result` arguments of the last attempt at completing the `task`. Invoked with - * (err, results). - * @example - * async.tryEach([ - * function getDataFromFirstWebsite(callback) { - * // Try getting the data from the first website - * callback(err, data); - * }, - * function getDataFromSecondWebsite(callback) { - * // First website failed, - * // Try getting the data from the backup website - * callback(err, data); - * } - * ], - * // optional callback - * function(err, results) { - * Now do something with the data. - * }); - * - */ -function tryEach(tasks, callback) { - var error = null; - var result; - callback = callback || noop; - eachSeries(tasks, function(task, callback) { - wrapAsync(task)(function (err, res/*, ...args*/) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } else { - result = res; - } - error = err; - callback(!err); - }); - }, function () { - callback(error, result); - }); -} - -/** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function - */ -function unmemoize(fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; -} - -/** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns undefined - * @example - * - * var count = 0; - * async.whilst( - * function() { return count < 5; }, - * function(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ -function whilst(test, iteratee, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - if (!test()) return callback(null); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - if (test()) return _iteratee(next); - var args = slice(arguments, 1); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} - -/** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function until(test, iteratee, callback) { - whilst(function() { - return !test.apply(this, arguments); - }, iteratee, 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. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns undefined - * @example - * - * 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' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ -var waterfall = function(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; - - function nextTask(args) { - var task = wrapAsync(tasks[taskIndex++]); - args.push(onlyOnce(next)); - task.apply(null, args); - } - - function next(err/*, ...args*/) { - if (err || taskIndex === tasks.length) { - return callback.apply(null, arguments); - } - nextTask(slice(arguments, 1)); - } - - nextTask([]); -}; - -/** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. - * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) - * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. - * - * @typedef {Function} AsyncFunction - * @static - */ - -/** - * 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 --save async`, it can also be used directly in the browser. - * @module async - * @see AsyncFunction - */ - - -/** - * A collection of `async` functions for manipulating collections, such as - * arrays and objects. - * @module Collections - */ - -/** - * A collection of `async` functions for controlling the flow through a script. - * @module ControlFlow - */ - -/** - * A collection of `async` utility functions. - * @module Utils - */ - -var index = { - apply: apply, - applyEach: applyEach, - applyEachSeries: applyEachSeries, - asyncify: asyncify, - auto: auto, - autoInject: autoInject, - cargo: cargo, - compose: compose, - concat: concat, - concatLimit: concatLimit, - concatSeries: concatSeries, - constant: constant, - detect: detect, - detectLimit: detectLimit, - detectSeries: detectSeries, - dir: dir, - doDuring: doDuring, - doUntil: doUntil, - doWhilst: doWhilst, - during: during, - each: eachLimit, - eachLimit: eachLimit$1, - eachOf: eachOf, - eachOfLimit: eachOfLimit, - eachOfSeries: eachOfSeries, - eachSeries: eachSeries, - ensureAsync: ensureAsync, - every: every, - everyLimit: everyLimit, - everySeries: everySeries, - filter: filter, - filterLimit: filterLimit, - filterSeries: filterSeries, - forever: forever, - groupBy: groupBy, - groupByLimit: groupByLimit, - groupBySeries: groupBySeries, - log: log, - map: map, - mapLimit: mapLimit, - mapSeries: mapSeries, - mapValues: mapValues, - mapValuesLimit: mapValuesLimit, - mapValuesSeries: mapValuesSeries, - memoize: memoize, - nextTick: nextTick, - parallel: parallelLimit, - parallelLimit: parallelLimit$1, - priorityQueue: priorityQueue, - queue: queue$1, - race: race, - reduce: reduce, - reduceRight: reduceRight, - reflect: reflect, - reflectAll: reflectAll, - reject: reject, - rejectLimit: rejectLimit, - rejectSeries: rejectSeries, - retry: retry, - retryable: retryable, - seq: seq, - series: series, - setImmediate: setImmediate$1, - some: some, - someLimit: someLimit, - someSeries: someSeries, - sortBy: sortBy, - timeout: timeout, - times: times, - timesLimit: timeLimit, - timesSeries: timesSeries, - transform: transform, - tryEach: tryEach, - unmemoize: unmemoize, - until: until, - waterfall: waterfall, - whilst: whilst, - - // aliases - all: every, - allLimit: everyLimit, - allSeries: everySeries, - any: some, - anyLimit: someLimit, - anySeries: someSeries, - find: detect, - findLimit: detectLimit, - findSeries: detectSeries, - forEach: eachLimit, - forEachSeries: eachSeries, - forEachLimit: eachLimit$1, - forEachOf: eachOf, - forEachOfSeries: eachOfSeries, - forEachOfLimit: eachOfLimit, - inject: reduce, - foldl: reduce, - foldr: reduceRight, - select: filter, - selectLimit: filterLimit, - selectSeries: filterSeries, - wrapSync: asyncify -}; - -exports['default'] = index; -exports.apply = apply; -exports.applyEach = applyEach; -exports.applyEachSeries = applyEachSeries; -exports.asyncify = asyncify; -exports.auto = auto; -exports.autoInject = autoInject; -exports.cargo = cargo; -exports.compose = compose; -exports.concat = concat; -exports.concatLimit = concatLimit; -exports.concatSeries = concatSeries; -exports.constant = constant; -exports.detect = detect; -exports.detectLimit = detectLimit; -exports.detectSeries = detectSeries; -exports.dir = dir; -exports.doDuring = doDuring; -exports.doUntil = doUntil; -exports.doWhilst = doWhilst; -exports.during = during; -exports.each = eachLimit; -exports.eachLimit = eachLimit$1; -exports.eachOf = eachOf; -exports.eachOfLimit = eachOfLimit; -exports.eachOfSeries = eachOfSeries; -exports.eachSeries = eachSeries; -exports.ensureAsync = ensureAsync; -exports.every = every; -exports.everyLimit = everyLimit; -exports.everySeries = everySeries; -exports.filter = filter; -exports.filterLimit = filterLimit; -exports.filterSeries = filterSeries; -exports.forever = forever; -exports.groupBy = groupBy; -exports.groupByLimit = groupByLimit; -exports.groupBySeries = groupBySeries; -exports.log = log; -exports.map = map; -exports.mapLimit = mapLimit; -exports.mapSeries = mapSeries; -exports.mapValues = mapValues; -exports.mapValuesLimit = mapValuesLimit; -exports.mapValuesSeries = mapValuesSeries; -exports.memoize = memoize; -exports.nextTick = nextTick; -exports.parallel = parallelLimit; -exports.parallelLimit = parallelLimit$1; -exports.priorityQueue = priorityQueue; -exports.queue = queue$1; -exports.race = race; -exports.reduce = reduce; -exports.reduceRight = reduceRight; -exports.reflect = reflect; -exports.reflectAll = reflectAll; -exports.reject = reject; -exports.rejectLimit = rejectLimit; -exports.rejectSeries = rejectSeries; -exports.retry = retry; -exports.retryable = retryable; -exports.seq = seq; -exports.series = series; -exports.setImmediate = setImmediate$1; -exports.some = some; -exports.someLimit = someLimit; -exports.someSeries = someSeries; -exports.sortBy = sortBy; -exports.timeout = timeout; -exports.times = times; -exports.timesLimit = timeLimit; -exports.timesSeries = timesSeries; -exports.transform = transform; -exports.tryEach = tryEach; -exports.unmemoize = unmemoize; -exports.until = until; -exports.waterfall = waterfall; -exports.whilst = whilst; -exports.all = every; -exports.allLimit = everyLimit; -exports.allSeries = everySeries; -exports.any = some; -exports.anyLimit = someLimit; -exports.anySeries = someSeries; -exports.find = detect; -exports.findLimit = detectLimit; -exports.findSeries = detectSeries; -exports.forEach = eachLimit; -exports.forEachSeries = eachSeries; -exports.forEachLimit = eachLimit$1; -exports.forEachOf = eachOf; -exports.forEachOfSeries = eachOfSeries; -exports.forEachOfLimit = eachOfLimit; -exports.inject = reduce; -exports.foldl = reduce; -exports.foldr = reduceRight; -exports.select = filter; -exports.selectLimit = filterLimit; -exports.selectSeries = filterSeries; -exports.wrapSync = asyncify; - -Object.defineProperty(exports, '__esModule', { value: true }); - -}))); diff --git a/node_modules/async/dist/async.min.js b/node_modules/async/dist/async.min.js deleted file mode 100644 index 013f194d147b8ea517854ca683f8f63ab4e5f406..0000000000000000000000000000000000000000 --- a/node_modules/async/dist/async.min.js +++ /dev/null @@ -1,2 +0,0 @@ -!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(n.async=n.async||{})}(this,function(n){"use strict";function t(n,t){t|=0;for(var e=Math.max(n.length-t,0),r=Array(e),u=0;u<e;u++)r[u]=n[t+u];return r}function e(n){var t=typeof n;return null!=n&&("object"==t||"function"==t)}function r(n){setTimeout(n,0)}function u(n){return function(e){var r=t(arguments,1);n(function(){e.apply(null,r)})}}function i(n){return ct(function(t,r){var u;try{u=n.apply(this,t)}catch(n){return r(n)}e(u)&&"function"==typeof u.then?u.then(function(n){o(r,null,n)},function(n){o(r,n.message?n:new Error(n))}):r(null,u)})}function o(n,t,e){try{n(t,e)}catch(n){lt(c,n)}}function c(n){throw n}function f(n){return st&&"AsyncFunction"===n[Symbol.toStringTag]}function a(n){return f(n)?i(n):n}function l(n){return function(e){var r=t(arguments,1),u=ct(function(t,r){var u=this;return n(e,function(n,e){a(n).apply(u,t.concat(e))},r)});return r.length?u.apply(this,r):u}}function s(n){var t=mt.call(n,bt),e=n[bt];try{n[bt]=void 0;var r=!0}catch(n){}var u=gt.call(n);return r&&(t?n[bt]=e:delete n[bt]),u}function p(n){return St.call(n)}function h(n){return null==n?void 0===n?Lt:kt:Ot&&Ot in Object(n)?s(n):p(n)}function y(n){if(!e(n))return!1;var t=h(n);return t==xt||t==Et||t==wt||t==At}function v(n){return"number"==typeof n&&n>-1&&n%1==0&&n<=Tt}function d(n){return null!=n&&v(n.length)&&!y(n)}function m(){}function g(n){return function(){if(null!==n){var t=n;n=null,t.apply(this,arguments)}}}function b(n,t){for(var e=-1,r=Array(n);++e<n;)r[e]=t(e);return r}function j(n){return null!=n&&"object"==typeof n}function S(n){return j(n)&&h(n)==_t}function k(){return!1}function L(n,t){var e=typeof n;return t=null==t?Nt:t,!!t&&("number"==e||"symbol"!=e&&Qt.test(n))&&n>-1&&n%1==0&&n<t}function O(n){return j(n)&&v(n.length)&&!!me[h(n)]}function w(n){return function(t){return n(t)}}function x(n,t){var e=Pt(n),r=!e&&zt(n),u=!e&&!r&&Wt(n),i=!e&&!r&&!u&&Oe(n),o=e||r||u||i,c=o?b(n.length,String):[],f=c.length;for(var a in n)!t&&!xe.call(n,a)||o&&("length"==a||u&&("offset"==a||"parent"==a)||i&&("buffer"==a||"byteLength"==a||"byteOffset"==a)||L(a,f))||c.push(a);return c}function E(n){var t=n&&n.constructor,e="function"==typeof t&&t.prototype||Ee;return n===e}function A(n,t){return function(e){return n(t(e))}}function T(n){if(!E(n))return Ae(n);var t=[];for(var e in Object(n))Be.call(n,e)&&"constructor"!=e&&t.push(e);return t}function B(n){return d(n)?x(n):T(n)}function F(n){var t=-1,e=n.length;return function(){return++t<e?{value:n[t],key:t}:null}}function I(n){var t=-1;return function(){var e=n.next();return e.done?null:(t++,{value:e.value,key:t})}}function _(n){var t=B(n),e=-1,r=t.length;return function(){var u=t[++e];return e<r?{value:n[u],key:u}:null}}function M(n){if(d(n))return F(n);var t=It(n);return t?I(t):_(n)}function U(n){return function(){if(null===n)throw new Error("Callback was already called.");var t=n;n=null,t.apply(this,arguments)}}function q(n){return function(t,e,r){function u(n,t){if(f-=1,n)c=!0,r(n);else{if(t===Bt||c&&f<=0)return c=!0,r(null);a||i()}}function i(){for(a=!0;f<n&&!c;){var t=o();if(null===t)return c=!0,void(f<=0&&r(null));f+=1,e(t.value,t.key,U(u))}a=!1}if(r=g(r||m),n<=0||!t)return r(null);var o=M(t),c=!1,f=0,a=!1;i()}}function z(n,t,e,r){q(t)(n,a(e),r)}function P(n,t){return function(e,r,u){return n(e,t,r,u)}}function V(n,t,e){function r(n,t){n?e(n):++i!==o&&t!==Bt||e(null)}e=g(e||m);var u=0,i=0,o=n.length;for(0===o&&e(null);u<o;u++)t(n[u],u,U(r))}function D(n){return function(t,e,r){return n(Ie,t,a(e),r)}}function R(n,t,e,r){r=r||m,t=t||[];var u=[],i=0,o=a(e);n(t,function(n,t,e){var r=i++;o(n,function(n,t){u[r]=t,e(n)})},function(n){r(n,u)})}function C(n){return function(t,e,r,u){return n(q(e),t,a(r),u)}}function $(n,t){for(var e=-1,r=null==n?0:n.length;++e<r&&t(n[e],e,n)!==!1;);return n}function W(n){return function(t,e,r){for(var u=-1,i=Object(t),o=r(t),c=o.length;c--;){var f=o[n?c:++u];if(e(i[f],f,i)===!1)break}return t}}function N(n,t){return n&&Pe(n,t,B)}function Q(n,t,e,r){for(var u=n.length,i=e+(r?1:-1);r?i--:++i<u;)if(t(n[i],i,n))return i;return-1}function G(n){return n!==n}function H(n,t,e){for(var r=e-1,u=n.length;++r<u;)if(n[r]===t)return r;return-1}function J(n,t,e){return t===t?H(n,t,e):Q(n,G,e)}function K(n,t){for(var e=-1,r=null==n?0:n.length,u=Array(r);++e<r;)u[e]=t(n[e],e,n);return u}function X(n){return"symbol"==typeof n||j(n)&&h(n)==De}function Y(n){if("string"==typeof n)return n;if(Pt(n))return K(n,Y)+"";if(X(n))return $e?$e.call(n):"";var t=n+"";return"0"==t&&1/n==-Re?"-0":t}function Z(n,t,e){var r=-1,u=n.length;t<0&&(t=-t>u?0:u+t),e=e>u?u:e,e<0&&(e+=u),u=t>e?0:e-t>>>0,t>>>=0;for(var i=Array(u);++r<u;)i[r]=n[r+t];return i}function nn(n,t,e){var r=n.length;return e=void 0===e?r:e,!t&&e>=r?n:Z(n,t,e)}function tn(n,t){for(var e=n.length;e--&&J(t,n[e],0)>-1;);return e}function en(n,t){for(var e=-1,r=n.length;++e<r&&J(t,n[e],0)>-1;);return e}function rn(n){return n.split("")}function un(n){return Xe.test(n)}function on(n){return n.match(mr)||[]}function cn(n){return un(n)?on(n):rn(n)}function fn(n){return null==n?"":Y(n)}function an(n,t,e){if(n=fn(n),n&&(e||void 0===t))return n.replace(gr,"");if(!n||!(t=Y(t)))return n;var r=cn(n),u=cn(t),i=en(r,u),o=tn(r,u)+1;return nn(r,i,o).join("")}function ln(n){return n=n.toString().replace(kr,""),n=n.match(br)[2].replace(" ",""),n=n?n.split(jr):[],n=n.map(function(n){return an(n.replace(Sr,""))})}function sn(n,t){var e={};N(n,function(n,t){function r(t,e){var r=K(u,function(n){return t[n]});r.push(e),a(n).apply(null,r)}var u,i=f(n),o=!i&&1===n.length||i&&0===n.length;if(Pt(n))u=n.slice(0,-1),n=n[n.length-1],e[t]=u.concat(u.length>0?r:n);else if(o)e[t]=n;else{if(u=ln(n),0===n.length&&!i&&0===u.length)throw new Error("autoInject task functions require explicit parameters.");i||u.pop(),e[t]=u.concat(r)}}),Ve(e,t)}function pn(){this.head=this.tail=null,this.length=0}function hn(n,t){n.length=1,n.head=n.tail=t}function yn(n,t,e){function r(n,t,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");if(s.started=!0,Pt(n)||(n=[n]),0===n.length&&s.idle())return lt(function(){s.drain()});for(var r=0,u=n.length;r<u;r++){var i={data:n[r],callback:e||m};t?s._tasks.unshift(i):s._tasks.push(i)}f||(f=!0,lt(function(){f=!1,s.process()}))}function u(n){return function(t){o-=1;for(var e=0,r=n.length;e<r;e++){var u=n[e],i=J(c,u,0);0===i?c.shift():i>0&&c.splice(i,1),u.callback.apply(u,arguments),null!=t&&s.error(t,u.data)}o<=s.concurrency-s.buffer&&s.unsaturated(),s.idle()&&s.drain(),s.process()}}if(null==t)t=1;else if(0===t)throw new Error("Concurrency must not be zero");var i=a(n),o=0,c=[],f=!1,l=!1,s={_tasks:new pn,concurrency:t,payload:e,saturated:m,unsaturated:m,buffer:t/4,empty:m,drain:m,error:m,started:!1,paused:!1,push:function(n,t){r(n,!1,t)},kill:function(){s.drain=m,s._tasks.empty()},unshift:function(n,t){r(n,!0,t)},remove:function(n){s._tasks.remove(n)},process:function(){if(!l){for(l=!0;!s.paused&&o<s.concurrency&&s._tasks.length;){var n=[],t=[],e=s._tasks.length;s.payload&&(e=Math.min(e,s.payload));for(var r=0;r<e;r++){var f=s._tasks.shift();n.push(f),c.push(f),t.push(f.data)}o+=1,0===s._tasks.length&&s.empty(),o===s.concurrency&&s.saturated();var a=U(u(n));i(t,a)}l=!1}},length:function(){return s._tasks.length},running:function(){return o},workersList:function(){return c},idle:function(){return s._tasks.length+o===0},pause:function(){s.paused=!0},resume:function(){s.paused!==!1&&(s.paused=!1,lt(s.process))}};return s}function vn(n,t){return yn(n,1,t)}function dn(n,t,e,r){r=g(r||m);var u=a(e);Or(n,function(n,e,r){u(t,n,function(n,e){t=e,r(n)})},function(n){r(n,t)})}function mn(){var n=K(arguments,a);return function(){var e=t(arguments),r=this,u=e[e.length-1];"function"==typeof u?e.pop():u=m,dn(n,e,function(n,e,u){e.apply(r,n.concat(function(n){var e=t(arguments,1);u(n,e)}))},function(n,t){u.apply(r,[n].concat(t))})}}function gn(n){return n}function bn(n,t){return function(e,r,u,i){i=i||m;var o,c=!1;e(r,function(e,r,i){u(e,function(r,u){r?i(r):n(u)&&!o?(c=!0,o=t(!0,e),i(null,Bt)):i()})},function(n){n?i(n):i(null,c?o:t(!1))})}}function jn(n,t){return t}function Sn(n){return function(e){var r=t(arguments,1);r.push(function(e){var r=t(arguments,1);"object"==typeof console&&(e?console.error&&console.error(e):console[n]&&$(r,function(t){console[n](t)}))}),a(e).apply(null,r)}}function kn(n,e,r){function u(n){if(n)return r(n);var e=t(arguments,1);e.push(i),c.apply(this,e)}function i(n,t){return n?r(n):t?void o(u):r(null)}r=U(r||m);var o=a(n),c=a(e);i(null,!0)}function Ln(n,e,r){r=U(r||m);var u=a(n),i=function(n){if(n)return r(n);var o=t(arguments,1);return e.apply(this,o)?u(i):void r.apply(null,[null].concat(o))};u(i)}function On(n,t,e){Ln(n,function(){return!t.apply(this,arguments)},e)}function wn(n,t,e){function r(n){return n?e(n):void o(u)}function u(n,t){return n?e(n):t?void i(r):e(null)}e=U(e||m);var i=a(t),o=a(n);o(u)}function xn(n){return function(t,e,r){return n(t,r)}}function En(n,t,e){Ie(n,xn(a(t)),e)}function An(n,t,e,r){q(t)(n,xn(a(e)),r)}function Tn(n){return f(n)?n:ct(function(t,e){var r=!0;t.push(function(){var n=arguments;r?lt(function(){e.apply(null,n)}):e.apply(null,n)}),n.apply(this,t),r=!1})}function Bn(n){return!n}function Fn(n){return function(t){return null==t?void 0:t[n]}}function In(n,t,e,r){var u=new Array(t.length);n(t,function(n,t,r){e(n,function(n,e){u[t]=!!e,r(n)})},function(n){if(n)return r(n);for(var e=[],i=0;i<t.length;i++)u[i]&&e.push(t[i]);r(null,e)})}function _n(n,t,e,r){var u=[];n(t,function(n,t,r){e(n,function(e,i){e?r(e):(i&&u.push({index:t,value:n}),r())})},function(n){n?r(n):r(null,K(u.sort(function(n,t){return n.index-t.index}),Fn("value")))})}function Mn(n,t,e,r){var u=d(t)?In:_n;u(n,t,a(e),r||m)}function Un(n,t){function e(n){return n?r(n):void u(e)}var r=U(t||m),u=a(Tn(n));e()}function qn(n,t,e,r){r=g(r||m);var u={},i=a(e);z(n,t,function(n,t,e){i(n,t,function(n,r){return n?e(n):(u[t]=r,void e())})},function(n){r(n,u)})}function zn(n,t){return t in n}function Pn(n,e){var r=Object.create(null),u=Object.create(null);e=e||gn;var i=a(n),o=ct(function(n,o){var c=e.apply(null,n);zn(r,c)?lt(function(){o.apply(null,r[c])}):zn(u,c)?u[c].push(o):(u[c]=[o],i.apply(null,n.concat(function(){var n=t(arguments);r[c]=n;var e=u[c];delete u[c];for(var i=0,o=e.length;i<o;i++)e[i].apply(null,n)})))});return o.memo=r,o.unmemoized=n,o}function Vn(n,e,r){r=r||m;var u=d(e)?[]:{};n(e,function(n,e,r){a(n)(function(n,i){arguments.length>2&&(i=t(arguments,1)),u[e]=i,r(n)})},function(n){r(n,u)})}function Dn(n,t){Vn(Ie,n,t)}function Rn(n,t,e){Vn(q(t),n,e)}function Cn(n,t){if(t=g(t||m),!Pt(n))return t(new TypeError("First argument to race must be an array of functions"));if(!n.length)return t();for(var e=0,r=n.length;e<r;e++)a(n[e])(t)}function $n(n,e,r,u){var i=t(n).reverse();dn(i,e,r,u)}function Wn(n){var e=a(n);return ct(function(n,r){return n.push(function(n,e){if(n)r(null,{error:n});else{var u;u=arguments.length<=2?e:t(arguments,1),r(null,{value:u})}}),e.apply(this,n)})}function Nn(n){var t;return Pt(n)?t=K(n,Wn):(t={},N(n,function(n,e){t[e]=Wn.call(this,n)})),t}function Qn(n,t,e,r){Mn(n,t,function(n,t){e(n,function(n,e){t(n,!e)})},r)}function Gn(n){return function(){return n}}function Hn(n,t,e){function r(n,t){if("object"==typeof t)n.times=+t.times||i,n.intervalFunc="function"==typeof t.interval?t.interval:Gn(+t.interval||o),n.errorFilter=t.errorFilter;else{if("number"!=typeof t&&"string"!=typeof t)throw new Error("Invalid arguments for async.retry");n.times=+t||i}}function u(){f(function(n){n&&l++<c.times&&("function"!=typeof c.errorFilter||c.errorFilter(n))?setTimeout(u,c.intervalFunc(l)):e.apply(null,arguments)})}var i=5,o=0,c={times:i,intervalFunc:Gn(o)};if(arguments.length<3&&"function"==typeof n?(e=t||m,t=n):(r(c,n),e=e||m),"function"!=typeof t)throw new Error("Invalid arguments for async.retry");var f=a(t),l=1;u()}function Jn(n,t){Vn(Or,n,t)}function Kn(n,t,e){function r(n,t){var e=n.criteria,r=t.criteria;return e<r?-1:e>r?1:0}var u=a(t);_e(n,function(n,t){u(n,function(e,r){return e?t(e):void t(null,{value:n,criteria:r})})},function(n,t){return n?e(n):void e(null,K(t.sort(r),Fn("value")))})}function Xn(n,t,e){var r=a(n);return ct(function(u,i){function o(){var t=n.name||"anonymous",r=new Error('Callback function "'+t+'" timed out.');r.code="ETIMEDOUT",e&&(r.info=e),f=!0,i(r)}var c,f=!1;u.push(function(){f||(i.apply(null,arguments),clearTimeout(c))}),c=setTimeout(o,t),r.apply(null,u)})}function Yn(n,t,e,r){for(var u=-1,i=iu(uu((t-n)/(e||1)),0),o=Array(i);i--;)o[r?i:++u]=n,n+=e;return o}function Zn(n,t,e,r){var u=a(e);Ue(Yn(0,n,1),t,u,r)}function nt(n,t,e,r){arguments.length<=3&&(r=e,e=t,t=Pt(n)?[]:{}),r=g(r||m);var u=a(e);Ie(n,function(n,e,r){u(t,n,e,r)},function(n){r(n,t)})}function tt(n,e){var r,u=null;e=e||m,Ur(n,function(n,e){a(n)(function(n,i){r=arguments.length>2?t(arguments,1):i,u=n,e(!n)})},function(){e(u,r)})}function et(n){return function(){return(n.unmemoized||n).apply(null,arguments)}}function rt(n,e,r){r=U(r||m);var u=a(e);if(!n())return r(null);var i=function(e){if(e)return r(e);if(n())return u(i);var o=t(arguments,1);r.apply(null,[null].concat(o))};u(i)}function ut(n,t,e){rt(function(){return!n.apply(this,arguments)},t,e)}var it,ot=function(n){var e=t(arguments,1);return function(){var r=t(arguments);return n.apply(null,e.concat(r))}},ct=function(n){return function(){var e=t(arguments),r=e.pop();n.call(this,e,r)}},ft="function"==typeof setImmediate&&setImmediate,at="object"==typeof process&&"function"==typeof process.nextTick;it=ft?setImmediate:at?process.nextTick:r;var lt=u(it),st="function"==typeof Symbol,pt="object"==typeof global&&global&&global.Object===Object&&global,ht="object"==typeof self&&self&&self.Object===Object&&self,yt=pt||ht||Function("return this")(),vt=yt.Symbol,dt=Object.prototype,mt=dt.hasOwnProperty,gt=dt.toString,bt=vt?vt.toStringTag:void 0,jt=Object.prototype,St=jt.toString,kt="[object Null]",Lt="[object Undefined]",Ot=vt?vt.toStringTag:void 0,wt="[object AsyncFunction]",xt="[object Function]",Et="[object GeneratorFunction]",At="[object Proxy]",Tt=9007199254740991,Bt={},Ft="function"==typeof Symbol&&Symbol.iterator,It=function(n){return Ft&&n[Ft]&&n[Ft]()},_t="[object Arguments]",Mt=Object.prototype,Ut=Mt.hasOwnProperty,qt=Mt.propertyIsEnumerable,zt=S(function(){return arguments}())?S:function(n){return j(n)&&Ut.call(n,"callee")&&!qt.call(n,"callee")},Pt=Array.isArray,Vt="object"==typeof n&&n&&!n.nodeType&&n,Dt=Vt&&"object"==typeof module&&module&&!module.nodeType&&module,Rt=Dt&&Dt.exports===Vt,Ct=Rt?yt.Buffer:void 0,$t=Ct?Ct.isBuffer:void 0,Wt=$t||k,Nt=9007199254740991,Qt=/^(?:0|[1-9]\d*)$/,Gt="[object Arguments]",Ht="[object Array]",Jt="[object Boolean]",Kt="[object Date]",Xt="[object Error]",Yt="[object Function]",Zt="[object Map]",ne="[object Number]",te="[object Object]",ee="[object RegExp]",re="[object Set]",ue="[object String]",ie="[object WeakMap]",oe="[object ArrayBuffer]",ce="[object DataView]",fe="[object Float32Array]",ae="[object Float64Array]",le="[object Int8Array]",se="[object Int16Array]",pe="[object Int32Array]",he="[object Uint8Array]",ye="[object Uint8ClampedArray]",ve="[object Uint16Array]",de="[object Uint32Array]",me={};me[fe]=me[ae]=me[le]=me[se]=me[pe]=me[he]=me[ye]=me[ve]=me[de]=!0,me[Gt]=me[Ht]=me[oe]=me[Jt]=me[ce]=me[Kt]=me[Xt]=me[Yt]=me[Zt]=me[ne]=me[te]=me[ee]=me[re]=me[ue]=me[ie]=!1;var ge="object"==typeof n&&n&&!n.nodeType&&n,be=ge&&"object"==typeof module&&module&&!module.nodeType&&module,je=be&&be.exports===ge,Se=je&&pt.process,ke=function(){try{var n=be&&be.require&&be.require("util").types;return n?n:Se&&Se.binding&&Se.binding("util")}catch(n){}}(),Le=ke&&ke.isTypedArray,Oe=Le?w(Le):O,we=Object.prototype,xe=we.hasOwnProperty,Ee=Object.prototype,Ae=A(Object.keys,Object),Te=Object.prototype,Be=Te.hasOwnProperty,Fe=P(z,1/0),Ie=function(n,t,e){var r=d(n)?V:Fe;r(n,a(t),e)},_e=D(R),Me=l(_e),Ue=C(R),qe=P(Ue,1),ze=l(qe),Pe=W(),Ve=function(n,e,r){function u(n,t){j.push(function(){f(n,t)})}function i(){if(0===j.length&&0===v)return r(null,y);for(;j.length&&v<e;){var n=j.shift();n()}}function o(n,t){var e=b[n];e||(e=b[n]=[]),e.push(t)}function c(n){var t=b[n]||[];$(t,function(n){n()}),i()}function f(n,e){if(!d){var u=U(function(e,u){if(v--,arguments.length>2&&(u=t(arguments,1)),e){var i={};N(y,function(n,t){i[t]=n}),i[n]=u,d=!0,b=Object.create(null),r(e,i)}else y[n]=u,c(n)});v++;var i=a(e[e.length-1]);e.length>1?i(y,u):i(u)}}function l(){for(var n,t=0;S.length;)n=S.pop(),t++,$(s(n),function(n){0===--k[n]&&S.push(n)});if(t!==h)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function s(t){var e=[];return N(n,function(n,r){Pt(n)&&J(n,t,0)>=0&&e.push(r)}),e}"function"==typeof e&&(r=e,e=null),r=g(r||m);var p=B(n),h=p.length;if(!h)return r(null);e||(e=h);var y={},v=0,d=!1,b=Object.create(null),j=[],S=[],k={};N(n,function(t,e){if(!Pt(t))return u(e,[t]),void S.push(e);var r=t.slice(0,t.length-1),i=r.length;return 0===i?(u(e,t),void S.push(e)):(k[e]=i,void $(r,function(c){if(!n[c])throw new Error("async.auto task `"+e+"` has a non-existent dependency `"+c+"` in "+r.join(", "));o(c,function(){i--,0===i&&u(e,t)})}))}),l(),i()},De="[object Symbol]",Re=1/0,Ce=vt?vt.prototype:void 0,$e=Ce?Ce.toString:void 0,We="\\ud800-\\udfff",Ne="\\u0300-\\u036f",Qe="\\ufe20-\\ufe2f",Ge="\\u20d0-\\u20ff",He=Ne+Qe+Ge,Je="\\ufe0e\\ufe0f",Ke="\\u200d",Xe=RegExp("["+Ke+We+He+Je+"]"),Ye="\\ud800-\\udfff",Ze="\\u0300-\\u036f",nr="\\ufe20-\\ufe2f",tr="\\u20d0-\\u20ff",er=Ze+nr+tr,rr="\\ufe0e\\ufe0f",ur="["+Ye+"]",ir="["+er+"]",or="\\ud83c[\\udffb-\\udfff]",cr="(?:"+ir+"|"+or+")",fr="[^"+Ye+"]",ar="(?:\\ud83c[\\udde6-\\uddff]){2}",lr="[\\ud800-\\udbff][\\udc00-\\udfff]",sr="\\u200d",pr=cr+"?",hr="["+rr+"]?",yr="(?:"+sr+"(?:"+[fr,ar,lr].join("|")+")"+hr+pr+")*",vr=hr+pr+yr,dr="(?:"+[fr+ir+"?",ir,ar,lr,ur].join("|")+")",mr=RegExp(or+"(?="+or+")|"+dr+vr,"g"),gr=/^\s+|\s+$/g,br=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,jr=/,/,Sr=/(=.+)?(\s*)$/,kr=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;pn.prototype.removeLink=function(n){return n.prev?n.prev.next=n.next:this.head=n.next,n.next?n.next.prev=n.prev:this.tail=n.prev,n.prev=n.next=null,this.length-=1,n},pn.prototype.empty=function(){for(;this.head;)this.shift();return this},pn.prototype.insertAfter=function(n,t){t.prev=n,t.next=n.next,n.next?n.next.prev=t:this.tail=t,n.next=t,this.length+=1},pn.prototype.insertBefore=function(n,t){t.prev=n.prev,t.next=n,n.prev?n.prev.next=t:this.head=t,n.prev=t,this.length+=1},pn.prototype.unshift=function(n){this.head?this.insertBefore(this.head,n):hn(this,n)},pn.prototype.push=function(n){this.tail?this.insertAfter(this.tail,n):hn(this,n)},pn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},pn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},pn.prototype.toArray=function(){for(var n=Array(this.length),t=this.head,e=0;e<this.length;e++)n[e]=t.data,t=t.next;return n},pn.prototype.remove=function(n){for(var t=this.head;t;){var e=t.next;n(t)&&this.removeLink(t),t=e}return this};var Lr,Or=P(z,1),wr=function(){return mn.apply(null,t(arguments).reverse())},xr=Array.prototype.concat,Er=function(n,e,r,u){u=u||m;var i=a(r);Ue(n,e,function(n,e){i(n,function(n){return n?e(n):e(null,t(arguments,1))})},function(n,t){for(var e=[],r=0;r<t.length;r++)t[r]&&(e=xr.apply(e,t[r]));return u(n,e)})},Ar=P(Er,1/0),Tr=P(Er,1),Br=function(){var n=t(arguments),e=[null].concat(n);return function(){var n=arguments[arguments.length-1];return n.apply(this,e)}},Fr=D(bn(gn,jn)),Ir=C(bn(gn,jn)),_r=P(Ir,1),Mr=Sn("dir"),Ur=P(An,1),qr=D(bn(Bn,Bn)),zr=C(bn(Bn,Bn)),Pr=P(zr,1),Vr=D(Mn),Dr=C(Mn),Rr=P(Dr,1),Cr=function(n,t,e,r){r=r||m;var u=a(e);Ue(n,t,function(n,t){u(n,function(e,r){return e?t(e):t(null,{key:r,val:n})})},function(n,t){for(var e={},u=Object.prototype.hasOwnProperty,i=0;i<t.length;i++)if(t[i]){var o=t[i].key,c=t[i].val;u.call(e,o)?e[o].push(c):e[o]=[c]}return r(n,e)})},$r=P(Cr,1/0),Wr=P(Cr,1),Nr=Sn("log"),Qr=P(qn,1/0),Gr=P(qn,1);Lr=at?process.nextTick:ft?setImmediate:r;var Hr=u(Lr),Jr=function(n,t){var e=a(n);return yn(function(n,t){e(n[0],t)},t,1)},Kr=function(n,t){var e=Jr(n,t);return e.push=function(n,t,r){if(null==r&&(r=m),"function"!=typeof r)throw new Error("task callback must be a function");if(e.started=!0,Pt(n)||(n=[n]),0===n.length)return lt(function(){e.drain()});t=t||0;for(var u=e._tasks.head;u&&t>=u.priority;)u=u.next;for(var i=0,o=n.length;i<o;i++){var c={data:n[i],priority:t,callback:r};u?e._tasks.insertBefore(u,c):e._tasks.push(c)}lt(e.process)},delete e.unshift,e},Xr=D(Qn),Yr=C(Qn),Zr=P(Yr,1),nu=function(n,t){t||(t=n,n=null);var e=a(t);return ct(function(t,r){function u(n){e.apply(null,t.concat(n))}n?Hn(n,u,r):Hn(u,r)})},tu=D(bn(Boolean,gn)),eu=C(bn(Boolean,gn)),ru=P(eu,1),uu=Math.ceil,iu=Math.max,ou=P(Zn,1/0),cu=P(Zn,1),fu=function(n,e){function r(t){var e=a(n[i++]);t.push(U(u)),e.apply(null,t)}function u(u){return u||i===n.length?e.apply(null,arguments):void r(t(arguments,1))}if(e=g(e||m),!Pt(n))return e(new Error("First argument to waterfall must be an array of functions"));if(!n.length)return e();var i=0;r([])},au={apply:ot,applyEach:Me,applyEachSeries:ze,asyncify:i,auto:Ve,autoInject:sn,cargo:vn,compose:wr,concat:Ar,concatLimit:Er,concatSeries:Tr,constant:Br,detect:Fr,detectLimit:Ir,detectSeries:_r,dir:Mr,doDuring:kn,doUntil:On,doWhilst:Ln,during:wn,each:En,eachLimit:An,eachOf:Ie,eachOfLimit:z,eachOfSeries:Or,eachSeries:Ur,ensureAsync:Tn,every:qr,everyLimit:zr,everySeries:Pr,filter:Vr,filterLimit:Dr,filterSeries:Rr,forever:Un,groupBy:$r,groupByLimit:Cr,groupBySeries:Wr,log:Nr,map:_e,mapLimit:Ue,mapSeries:qe,mapValues:Qr,mapValuesLimit:qn,mapValuesSeries:Gr,memoize:Pn,nextTick:Hr,parallel:Dn,parallelLimit:Rn,priorityQueue:Kr,queue:Jr,race:Cn,reduce:dn,reduceRight:$n,reflect:Wn,reflectAll:Nn,reject:Xr,rejectLimit:Yr,rejectSeries:Zr,retry:Hn,retryable:nu,seq:mn,series:Jn,setImmediate:lt,some:tu,someLimit:eu,someSeries:ru,sortBy:Kn,timeout:Xn,times:ou,timesLimit:Zn,timesSeries:cu,transform:nt,tryEach:tt,unmemoize:et,until:ut,waterfall:fu,whilst:rt,all:qr,allLimit:zr,allSeries:Pr,any:tu,anyLimit:eu,anySeries:ru,find:Fr,findLimit:Ir,findSeries:_r,forEach:En,forEachSeries:Ur,forEachLimit:An,forEachOf:Ie,forEachOfSeries:Or,forEachOfLimit:z,inject:dn,foldl:dn,foldr:$n,select:Vr,selectLimit:Dr,selectSeries:Rr,wrapSync:i};n.default=au,n.apply=ot,n.applyEach=Me,n.applyEachSeries=ze,n.asyncify=i,n.auto=Ve,n.autoInject=sn,n.cargo=vn,n.compose=wr,n.concat=Ar,n.concatLimit=Er,n.concatSeries=Tr,n.constant=Br,n.detect=Fr,n.detectLimit=Ir,n.detectSeries=_r,n.dir=Mr,n.doDuring=kn,n.doUntil=On,n.doWhilst=Ln,n.during=wn,n.each=En,n.eachLimit=An,n.eachOf=Ie,n.eachOfLimit=z,n.eachOfSeries=Or,n.eachSeries=Ur,n.ensureAsync=Tn,n.every=qr,n.everyLimit=zr,n.everySeries=Pr,n.filter=Vr,n.filterLimit=Dr,n.filterSeries=Rr,n.forever=Un,n.groupBy=$r,n.groupByLimit=Cr,n.groupBySeries=Wr,n.log=Nr,n.map=_e,n.mapLimit=Ue,n.mapSeries=qe,n.mapValues=Qr,n.mapValuesLimit=qn,n.mapValuesSeries=Gr,n.memoize=Pn,n.nextTick=Hr,n.parallel=Dn,n.parallelLimit=Rn,n.priorityQueue=Kr,n.queue=Jr,n.race=Cn,n.reduce=dn,n.reduceRight=$n,n.reflect=Wn,n.reflectAll=Nn,n.reject=Xr,n.rejectLimit=Yr,n.rejectSeries=Zr,n.retry=Hn,n.retryable=nu,n.seq=mn,n.series=Jn,n.setImmediate=lt,n.some=tu,n.someLimit=eu,n.someSeries=ru,n.sortBy=Kn,n.timeout=Xn,n.times=ou,n.timesLimit=Zn,n.timesSeries=cu,n.transform=nt,n.tryEach=tt,n.unmemoize=et,n.until=ut,n.waterfall=fu,n.whilst=rt,n.all=qr,n.allLimit=zr,n.allSeries=Pr,n.any=tu,n.anyLimit=eu,n.anySeries=ru,n.find=Fr,n.findLimit=Ir,n.findSeries=_r,n.forEach=En,n.forEachSeries=Ur,n.forEachLimit=An,n.forEachOf=Ie,n.forEachOfSeries=Or,n.forEachOfLimit=z,n.inject=dn,n.foldl=dn,n.foldr=$n,n.select=Vr,n.selectLimit=Dr,n.selectSeries=Rr,n.wrapSync=i,Object.defineProperty(n,"__esModule",{value:!0})}); -//# sourceMappingURL=async.min.map \ No newline at end of file diff --git a/node_modules/async/dist/async.min.map b/node_modules/async/dist/async.min.map deleted file mode 100644 index 0911b05899cdb1b14caccc8c7fbfe1cfbfe07096..0000000000000000000000000000000000000000 --- a/node_modules/async/dist/async.min.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["build/dist/async.js"],"names":["global","factory","exports","module","define","amd","async","this","slice","arrayLike","start","newLen","Math","max","length","newArr","Array","idx","isObject","value","type","fallback","fn","setTimeout","wrap","defer","args","arguments","apply","asyncify","func","initialParams","callback","result","e","then","invokeCallback","err","message","Error","error","setImmediate$1","rethrow","isAsync","supportsSymbol","Symbol","toStringTag","wrapAsync","asyncFn","applyEach$1","eachfn","fns","go","that","cb","concat","getRawTag","isOwn","hasOwnProperty","call","symToStringTag$1","tag","undefined","unmasked","nativeObjectToString","objectToString","nativeObjectToString$1","baseGetTag","undefinedTag","nullTag","symToStringTag","Object","isFunction","funcTag","genTag","asyncTag","proxyTag","isLength","MAX_SAFE_INTEGER","isArrayLike","noop","once","callFn","baseTimes","n","iteratee","index","isObjectLike","baseIsArguments","argsTag","stubFalse","isIndex","MAX_SAFE_INTEGER$1","reIsUint","test","baseIsTypedArray","typedArrayTags","baseUnary","arrayLikeKeys","inherited","isArr","isArray","isArg","isArguments","isBuff","isBuffer","isType","isTypedArray","skipIndexes","String","key","hasOwnProperty$1","push","isPrototype","Ctor","constructor","proto","prototype","objectProto$5","overArg","transform","arg","baseKeys","object","nativeKeys","hasOwnProperty$3","keys","createArrayIterator","coll","i","len","createES2015Iterator","iterator","item","next","done","createObjectIterator","obj","okeys","getIterator","onlyOnce","_eachOfLimit","limit","iterateeCallback","running","breakLoop","looping","replenish","elem","nextElem","eachOfLimit","doLimit","iterable","eachOfArrayLike","iteratorCallback","completed","doParallel","eachOf","_asyncMap","arr","results","counter","_iteratee","_","v","doParallelLimit","arrayEach","array","createBaseFor","fromRight","keysFunc","props","baseForOwn","baseFor","baseFindIndex","predicate","fromIndex","baseIsNaN","strictIndexOf","baseIndexOf","arrayMap","isSymbol","symbolTag","baseToString","symbolToString","INFINITY","baseSlice","end","castSlice","charsEndIndex","strSymbols","chrSymbols","charsStartIndex","asciiToArray","string","split","hasUnicode","reHasUnicode","unicodeToArray","match","reUnicode","stringToArray","toString","trim","chars","guard","replace","reTrim","join","parseParams","STRIP_COMMENTS","FN_ARGS","FN_ARG_SPLIT","map","FN_ARG","autoInject","tasks","newTasks","taskFn","newTask","taskCb","newArgs","params","name","fnIsAsync","hasNoDeps","pop","auto","DLL","head","tail","setInitial","dll","node","queue","worker","concurrency","payload","_insert","data","insertAtFront","q","started","idle","drain","l","_tasks","unshift","processingScheduled","process","_next","numRunning","task","workersList","shift","splice","buffer","unsaturated","_worker","isProcessing","saturated","empty","paused","kill","remove","testFn","min","pause","resume","cargo","reduce","memo","eachOfSeries","x","seq","_functions","newargs","nextargs","identity","_createTester","check","getResult","testResult","testPassed","_findGetResult","consoleFunc","console","doDuring","_test","truth","_fn","doWhilst","doUntil","during","_withoutIndex","eachLimit","eachLimit$1","ensureAsync","sync","innerArgs","notId","baseProperty","filterArray","truthValues","filterGeneric","sort","a","b","_filter","filter","forever","errback","mapValuesLimit","newObj","val","has","memoize","hasher","create","queues","memoized","unmemoized","_parallel","parallelLimit","parallelLimit$1","race","TypeError","reduceRight","reversed","reverse","reflect","reflectCallback","cbArg","reflectAll","reject$1","constant$1","retry","opts","parseTimes","acc","t","times","DEFAULT_TIMES","intervalFunc","interval","DEFAULT_INTERVAL","errorFilter","retryAttempt","_task","attempt","options","series","sortBy","comparator","left","right","criteria","timeout","milliseconds","info","timeoutCallback","code","timedOut","timer","clearTimeout","baseRange","step","nativeMax","nativeCeil","timeLimit","count","mapLimit","accumulator","k","tryEach","eachSeries","res","unmemoize","whilst","until","_defer","callArgs","hasSetImmediate","setImmediate","hasNextTick","nextTick","freeGlobal","freeSelf","self","root","Function","Symbol$1","objectProto","objectProto$1","iteratorSymbol","objectProto$3","hasOwnProperty$2","propertyIsEnumerable","freeExports","nodeType","freeModule","moduleExports","Buffer","nativeIsBuffer","argsTag$1","arrayTag","boolTag","dateTag","errorTag","funcTag$1","mapTag","numberTag","objectTag","regexpTag","setTag","stringTag","weakMapTag","arrayBufferTag","dataViewTag","float32Tag","float64Tag","int8Tag","int16Tag","int32Tag","uint8Tag","uint8ClampedTag","uint16Tag","uint32Tag","freeExports$1","freeModule$1","moduleExports$1","freeProcess","nodeUtil","types","require","binding","nodeIsTypedArray","objectProto$2","objectProto$4","eachOfGeneric","Infinity","eachOfImplementation","applyEach","mapSeries","applyEachSeries","enqueueTask","readyTasks","runTask","processQueue","runningTasks","run","addListener","taskName","taskListeners","listeners","taskComplete","hasError","taskCallback","safeResults","rkey","checkForDeadlocks","currentTask","readyToCheck","getDependents","dependent","uncheckedDependencies","numTasks","keys$$1","dependencies","remainingDependencies","dependencyName","symbolProto","rsAstralRange","rsComboMarksRange","reComboHalfMarksRange","rsComboSymbolsRange","rsComboRange","rsVarRange","rsZWJ","RegExp","rsAstralRange$1","rsComboMarksRange$1","reComboHalfMarksRange$1","rsComboSymbolsRange$1","rsComboRange$1","rsVarRange$1","rsAstral","rsCombo","rsFitz","rsModifier","rsNonAstral","rsRegional","rsSurrPair","rsZWJ$1","reOptMod","rsOptVar","rsOptJoin","rsSeq","rsSymbol","removeLink","prev","insertAfter","newNode","insertBefore","toArray","curr","_defer$1","compose","_concat","concatLimit","mapResults","concatSeries","constant","values","detect","detectLimit","detectSeries","dir","every","everyLimit","everySeries","filterLimit","filterSeries","groupByLimit","groupBy","groupBySeries","log","mapValues","mapValuesSeries","queue$1","items","priorityQueue","priority","nextNode","reject","rejectLimit","rejectSeries","retryable","some","Boolean","someLimit","someSeries","ceil","timesSeries","waterfall","nextTask","taskIndex","each","parallel","timesLimit","all","allLimit","allSeries","any","anyLimit","anySeries","find","findLimit","findSeries","forEach","forEachSeries","forEachLimit","forEachOf","forEachOfSeries","forEachOfLimit","inject","foldl","foldr","select","selectLimit","selectSeries","wrapSync","defineProperty"],"mappings":"CAAC,SAAUA,EAAQC,GACE,gBAAZC,UAA0C,mBAAXC,QAAyBF,EAAQC,SACrD,kBAAXE,SAAyBA,OAAOC,IAAMD,QAAQ,WAAYH,GAChEA,EAASD,EAAOM,MAAQN,EAAOM,YAChCC,KAAM,SAAWL,GAAW,YAE9B,SAASM,GAAMC,EAAWC,GACtBA,GAAc,CAGd,KAAI,GAFAC,GAASC,KAAKC,IAAIJ,EAAUK,OAASJ,EAAO,GAC5CK,EAASC,MAAML,GACXM,EAAM,EAAGA,EAAMN,EAAQM,IAC3BF,EAAOE,GAAOR,EAAUC,EAAQO,EAEpC,OAAOF,GAyFX,QAASG,GAASC,GAChB,GAAIC,SAAcD,EAClB,OAAgB,OAATA,IAA0B,UAARC,GAA4B,YAARA,GAM/C,QAASC,GAASC,GACdC,WAAWD,EAAI,GAGnB,QAASE,GAAKC,GACV,MAAO,UAAUH,GACb,GAAII,GAAOlB,EAAMmB,UAAW,EAC5BF,GAAM,WACFH,EAAGM,MAAM,KAAMF,MAyE3B,QAASG,GAASC,GACd,MAAOC,IAAc,SAAUL,EAAMM,GACjC,GAAIC,EACJ,KACIA,EAASH,EAAKF,MAAMrB,KAAMmB,GAC5B,MAAOQ,GACL,MAAOF,GAASE,GAGhBhB,EAASe,IAAkC,kBAAhBA,GAAOE,KAClCF,EAAOE,KAAK,SAAShB,GACjBiB,EAAeJ,EAAU,KAAMb,IAChC,SAASkB,GACRD,EAAeJ,EAAUK,EAAIC,QAAUD,EAAM,GAAIE,OAAMF,MAG3DL,EAAS,KAAMC,KAK3B,QAASG,GAAeJ,EAAUQ,EAAOrB,GACrC,IACIa,EAASQ,EAAOrB,GAClB,MAAOe,GACLO,GAAeC,EAASR,IAIhC,QAASQ,GAAQF,GACb,KAAMA,GAKV,QAASG,GAAQrB,GACb,MAAOsB,KAA6C,kBAA3BtB,EAAGuB,OAAOC,aAGvC,QAASC,GAAUC,GACf,MAAOL,GAAQK,GAAWnB,EAASmB,GAAWA,EAGlD,QAASC,GAAYC,GACjB,MAAO,UAASC,GACZ,GAAIzB,GAAOlB,EAAMmB,UAAW,GACxByB,EAAKrB,GAAc,SAASL,EAAMM,GAClC,GAAIqB,GAAO9C,IACX,OAAO2C,GAAOC,EAAK,SAAU7B,EAAIgC,GAC7BP,EAAUzB,GAAIM,MAAMyB,EAAM3B,EAAK6B,OAAOD,KACvCtB,IAEP,OAAIN,GAAKZ,OACEsC,EAAGxB,MAAMrB,KAAMmB,GAGf0B,GAwCnB,QAASI,GAAUrC,GACjB,GAAIsC,GAAQC,GAAeC,KAAKxC,EAAOyC,IACnCC,EAAM1C,EAAMyC,GAEhB,KACEzC,EAAMyC,IAAoBE,MAC1B,IAAIC,IAAW,EACf,MAAO7B,IAET,GAAID,GAAS+B,GAAqBL,KAAKxC,EAQvC,OAPI4C,KACEN,EACFtC,EAAMyC,IAAoBC,QAEnB1C,GAAMyC,KAGV3B,EAoBT,QAASgC,GAAe9C,GACtB,MAAO+C,IAAuBP,KAAKxC,GAiBrC,QAASgD,GAAWhD,GAClB,MAAa,OAATA,EACe2C,SAAV3C,EAAsBiD,GAAeC,GAEtCC,IAAkBA,KAAkBC,QAAOpD,GAC/CqC,EAAUrC,GACV8C,EAAe9C,GA0BrB,QAASqD,GAAWrD,GAClB,IAAKD,EAASC,GACZ,OAAO,CAIT,IAAI0C,GAAMM,EAAWhD,EACrB,OAAO0C,IAAOY,IAAWZ,GAAOa,IAAUb,GAAOc,IAAYd,GAAOe,GAgCtE,QAASC,GAAS1D,GAChB,MAAuB,gBAATA,IACZA,GAAQ,GAAMA,EAAQ,GAAK,GAAKA,GAAS2D,GA4B7C,QAASC,GAAY5D,GACnB,MAAgB,OAATA,GAAiB0D,EAAS1D,EAAML,UAAY0D,EAAWrD,GAmBhE,QAAS6D,MAIT,QAASC,GAAK3D,GACV,MAAO,YACH,GAAW,OAAPA,EAAJ,CACA,GAAI4D,GAAS5D,CACbA,GAAK,KACL4D,EAAOtD,MAAMrB,KAAMoB,aAmB3B,QAASwD,GAAUC,EAAGC,GAIpB,IAHA,GAAIC,IAAQ,EACRrD,EAASjB,MAAMoE,KAEVE,EAAQF,GACfnD,EAAOqD,GAASD,EAASC,EAE3B,OAAOrD,GA2BT,QAASsD,GAAapE,GACpB,MAAgB,OAATA,GAAiC,gBAATA,GAajC,QAASqE,GAAgBrE,GACvB,MAAOoE,GAAapE,IAAUgD,EAAWhD,IAAUsE,GAyErD,QAASC,KACP,OAAO,EAmDT,QAASC,GAAQxE,EAAOL,GACtB,GAAIM,SAAcD,EAGlB,OAFAL,GAAmB,MAAVA,EAAiB8E,GAAqB9E,IAEtCA,IACE,UAARM,GACU,UAARA,GAAoByE,GAASC,KAAK3E,KAChCA,GAAQ,GAAMA,EAAQ,GAAK,GAAKA,EAAQL,EAqDjD,QAASiF,GAAiB5E,GACxB,MAAOoE,GAAapE,IAClB0D,EAAS1D,EAAML,WAAakF,GAAe7B,EAAWhD,IAU1D,QAAS8E,GAAUnE,GACjB,MAAO,UAASX,GACd,MAAOW,GAAKX,IAmEhB,QAAS+E,GAAc/E,EAAOgF,GAC5B,GAAIC,GAAQC,GAAQlF,GAChBmF,GAASF,GAASG,GAAYpF,GAC9BqF,GAAUJ,IAAUE,GAASG,GAAStF,GACtCuF,GAAUN,IAAUE,IAAUE,GAAUG,GAAaxF,GACrDyF,EAAcR,GAASE,GAASE,GAAUE,EAC1CzE,EAAS2E,EAAczB,EAAUhE,EAAML,OAAQ+F,WAC/C/F,EAASmB,EAAOnB,MAEpB,KAAK,GAAIgG,KAAO3F,IACTgF,IAAaY,GAAiBpD,KAAKxC,EAAO2F,IACzCF,IAEQ,UAAPE,GAECN,IAAkB,UAAPM,GAA0B,UAAPA,IAE9BJ,IAAkB,UAAPI,GAA0B,cAAPA,GAA8B,cAAPA,IAEtDnB,EAAQmB,EAAKhG,KAElBmB,EAAO+E,KAAKF,EAGhB,OAAO7E,GAaT,QAASgF,GAAY9F,GACnB,GAAI+F,GAAO/F,GAASA,EAAMgG,YACtBC,EAAwB,kBAARF,IAAsBA,EAAKG,WAAcC,EAE7D,OAAOnG,KAAUiG,EAWnB,QAASG,GAAQzF,EAAM0F,GACrB,MAAO,UAASC,GACd,MAAO3F,GAAK0F,EAAUC,KAoB1B,QAASC,GAASC,GAChB,IAAKV,EAAYU,GACf,MAAOC,IAAWD,EAEpB,IAAI1F,KACJ,KAAK,GAAI6E,KAAOvC,QAAOoD,GACjBE,GAAiBlE,KAAKgE,EAAQb,IAAe,eAAPA,GACxC7E,EAAO+E,KAAKF,EAGhB,OAAO7E,GA+BT,QAAS6F,GAAKH,GACZ,MAAO5C,GAAY4C,GAAUzB,EAAcyB,GAAUD,EAASC,GAGhE,QAASI,GAAoBC,GACzB,GAAIC,IAAI,EACJC,EAAMF,EAAKlH,MACf,OAAO,YACH,QAASmH,EAAIC,GAAO/G,MAAO6G,EAAKC,GAAInB,IAAKmB,GAAK,MAItD,QAASE,GAAqBC,GAC1B,GAAIH,IAAI,CACR,OAAO,YACH,GAAII,GAAOD,EAASE,MACpB,OAAID,GAAKE,KACE,MACXN,KACQ9G,MAAOkH,EAAKlH,MAAO2F,IAAKmB,KAIxC,QAASO,GAAqBC,GAC1B,GAAIC,GAAQZ,EAAKW,GACbR,GAAI,EACJC,EAAMQ,EAAM5H,MAChB,OAAO,YACH,GAAIgG,GAAM4B,IAAQT,EAClB,OAAOA,GAAIC,GAAO/G,MAAOsH,EAAI3B,GAAMA,IAAKA,GAAO,MAIvD,QAASsB,GAASJ,GACd,GAAIjD,EAAYiD,GACZ,MAAOD,GAAoBC,EAG/B,IAAII,GAAWO,GAAYX,EAC3B,OAAOI,GAAWD,EAAqBC,GAAYI,EAAqBR,GAG5E,QAASY,GAAStH,GACd,MAAO,YACH,GAAW,OAAPA,EAAa,KAAM,IAAIiB,OAAM,+BACjC,IAAI2C,GAAS5D,CACbA,GAAK,KACL4D,EAAOtD,MAAMrB,KAAMoB,YAI3B,QAASkH,GAAaC,GAClB,MAAO,UAAUL,EAAKpD,EAAUrD,GAU5B,QAAS+G,GAAiB1G,EAAKlB,GAE3B,GADA6H,GAAW,EACP3G,EACAkG,GAAO,EACPvG,EAASK,OAER,CAAA,GAAIlB,IAAU8H,IAAcV,GAAQS,GAAW,EAEhD,MADAT,IAAO,EACAvG,EAAS,KAEVkH,IACNC,KAIR,QAASA,KAEL,IADAD,GAAU,EACHF,EAAUF,IAAUP,GAAM,CAC7B,GAAIa,GAAOC,GACX,IAAa,OAATD,EAKA,MAJAb,IAAO,OACHS,GAAW,GACXhH,EAAS,MAIjBgH,IAAW,EACX3D,EAAS+D,EAAKjI,MAAOiI,EAAKtC,IAAK8B,EAASG,IAE5CG,GAAU,EArCd,GADAlH,EAAWiD,EAAKjD,GAAYgD,GACxB8D,GAAS,IAAML,EACf,MAAOzG,GAAS,KAEpB,IAAIqH,GAAWjB,EAASK,GACpBF,GAAO,EACPS,EAAU,EACVE,GAAU,CAkCdC,MAwBR,QAASG,GAAYtB,EAAMc,EAAOzD,EAAUrD,GACxC6G,EAAaC,GAAOd,EAAMjF,EAAUsC,GAAWrD,GAGnD,QAASuH,GAAQjI,EAAIwH,GACjB,MAAO,UAAUU,EAAUnE,EAAUrD,GACjC,MAAOV,GAAGkI,EAAUV,EAAOzD,EAAUrD,IAK7C,QAASyH,GAAgBzB,EAAM3C,EAAUrD,GASrC,QAAS0H,GAAiBrH,EAAKlB,GACvBkB,EACAL,EAASK,KACCsH,IAAc7I,GAAWK,IAAU8H,IAC7CjH,EAAS,MAZjBA,EAAWiD,EAAKjD,GAAYgD,EAC5B,IAAIM,GAAQ,EACRqE,EAAY,EACZ7I,EAASkH,EAAKlH,MAalB,KAZe,IAAXA,GACAkB,EAAS,MAWNsD,EAAQxE,EAAQwE,IACnBD,EAAS2C,EAAK1C,GAAQA,EAAOsD,EAASc,IAmD9C,QAASE,GAAWtI,GAChB,MAAO,UAAUmH,EAAKpD,EAAUrD,GAC5B,MAAOV,GAAGuI,GAAQpB,EAAK1F,EAAUsC,GAAWrD,IAIpD,QAAS8H,GAAU5G,EAAQ6G,EAAK1E,EAAUrD,GACtCA,EAAWA,GAAYgD,EACvB+E,EAAMA,KACN,IAAIC,MACAC,EAAU,EACVC,EAAYnH,EAAUsC,EAE1BnC,GAAO6G,EAAK,SAAU5I,EAAOgJ,EAAGnI,GAC5B,GAAIsD,GAAQ2E,GACZC,GAAU/I,EAAO,SAAUkB,EAAK+H,GAC5BJ,EAAQ1E,GAAS8E,EACjBpI,EAASK,MAEd,SAAUA,GACTL,EAASK,EAAK2H,KA6EtB,QAASK,GAAgB/I,GACrB,MAAO,UAAUmH,EAAKK,EAAOzD,EAAUrD,GACnC,MAAOV,GAAGuH,EAAaC,GAAQL,EAAK1F,EAAUsC,GAAWrD,IA2EjE,QAASsI,GAAUC,EAAOlF,GAIxB,IAHA,GAAIC,IAAQ,EACRxE,EAAkB,MAATyJ,EAAgB,EAAIA,EAAMzJ,SAE9BwE,EAAQxE,GACXuE,EAASkF,EAAMjF,GAAQA,EAAOiF,MAAW,IAI/C,MAAOA,GAUT,QAASC,GAAcC,GACrB,MAAO,UAAS9C,EAAQtC,EAAUqF,GAMhC,IALA,GAAIpF,IAAQ,EACRkE,EAAWjF,OAAOoD,GAClBgD,EAAQD,EAAS/C,GACjB7G,EAAS6J,EAAM7J,OAEZA,KAAU,CACf,GAAIgG,GAAM6D,EAAMF,EAAY3J,IAAWwE,EACvC,IAAID,EAASmE,EAAS1C,GAAMA,EAAK0C,MAAc,EAC7C,MAGJ,MAAO7B,IAyBX,QAASiD,GAAWjD,EAAQtC,GAC1B,MAAOsC,IAAUkD,GAAQlD,EAAQtC,EAAUyC,GAc7C,QAASgD,GAAcP,EAAOQ,EAAWC,EAAWP,GAIlD,IAHA,GAAI3J,GAASyJ,EAAMzJ,OACfwE,EAAQ0F,GAAaP,EAAY,GAAI,GAEjCA,EAAYnF,MAAYA,EAAQxE,GACtC,GAAIiK,EAAUR,EAAMjF,GAAQA,EAAOiF,GACjC,MAAOjF,EAGX,QAAO,EAUT,QAAS2F,GAAU9J,GACjB,MAAOA,KAAUA,EAanB,QAAS+J,GAAcX,EAAOpJ,EAAO6J,GAInC,IAHA,GAAI1F,GAAQ0F,EAAY,EACpBlK,EAASyJ,EAAMzJ,SAEVwE,EAAQxE,GACf,GAAIyJ,EAAMjF,KAAWnE,EACnB,MAAOmE,EAGX,QAAO,EAYT,QAAS6F,GAAYZ,EAAOpJ,EAAO6J,GACjC,MAAO7J,KAAUA,EACb+J,EAAcX,EAAOpJ,EAAO6J,GAC5BF,EAAcP,EAAOU,EAAWD,GAkQtC,QAASI,GAASb,EAAOlF,GAKvB,IAJA,GAAIC,IAAQ,EACRxE,EAAkB,MAATyJ,EAAgB,EAAIA,EAAMzJ,OACnCmB,EAASjB,MAAMF,KAEVwE,EAAQxE,GACfmB,EAAOqD,GAASD,EAASkF,EAAMjF,GAAQA,EAAOiF,EAEhD,OAAOtI,GAuBT,QAASoJ,GAASlK,GAChB,MAAuB,gBAATA,IACXoE,EAAapE,IAAUgD,EAAWhD,IAAUmK,GAkBjD,QAASC,GAAapK,GAEpB,GAAoB,gBAATA,GACT,MAAOA,EAET,IAAIkF,GAAQlF,GAEV,MAAOiK,GAASjK,EAAOoK,GAAgB,EAEzC,IAAIF,EAASlK,GACX,MAAOqK,IAAiBA,GAAe7H,KAAKxC,GAAS,EAEvD,IAAIc,GAAUd,EAAQ,EACtB,OAAkB,KAAVc,GAAkB,EAAId,IAAWsK,GAAY,KAAOxJ,EAY9D,QAASyJ,GAAUnB,EAAO7J,EAAOiL,GAC/B,GAAIrG,IAAQ,EACRxE,EAASyJ,EAAMzJ,MAEfJ,GAAQ,IACVA,GAASA,EAAQI,EAAS,EAAKA,EAASJ,GAE1CiL,EAAMA,EAAM7K,EAASA,EAAS6K,EAC1BA,EAAM,IACRA,GAAO7K,GAETA,EAASJ,EAAQiL,EAAM,EAAMA,EAAMjL,IAAW,EAC9CA,KAAW,CAGX,KADA,GAAIuB,GAASjB,MAAMF,KACVwE,EAAQxE,GACfmB,EAAOqD,GAASiF,EAAMjF,EAAQ5E,EAEhC,OAAOuB,GAYT,QAAS2J,IAAUrB,EAAO7J,EAAOiL,GAC/B,GAAI7K,GAASyJ,EAAMzJ,MAEnB,OADA6K,GAAc7H,SAAR6H,EAAoB7K,EAAS6K,GAC1BjL,GAASiL,GAAO7K,EAAUyJ,EAAQmB,EAAUnB,EAAO7J,EAAOiL,GAYrE,QAASE,IAAcC,EAAYC,GAGjC,IAFA,GAAIzG,GAAQwG,EAAWhL,OAEhBwE,KAAW6F,EAAYY,EAAYD,EAAWxG,GAAQ,IAAK,IAClE,MAAOA,GAYT,QAAS0G,IAAgBF,EAAYC,GAInC,IAHA,GAAIzG,IAAQ,EACRxE,EAASgL,EAAWhL,SAEfwE,EAAQxE,GAAUqK,EAAYY,EAAYD,EAAWxG,GAAQ,IAAK,IAC3E,MAAOA,GAUT,QAAS2G,IAAaC,GACpB,MAAOA,GAAOC,MAAM,IAwBtB,QAASC,IAAWF,GAClB,MAAOG,IAAavG,KAAKoG,GAsC3B,QAASI,IAAeJ,GACtB,MAAOA,GAAOK,MAAMC,QAUtB,QAASC,IAAcP,GACrB,MAAOE,IAAWF,GACdI,GAAeJ,GACfD,GAAaC,GAwBnB,QAASQ,IAASvL,GAChB,MAAgB,OAATA,EAAgB,GAAKoK,EAAapK,GA4B3C,QAASwL,IAAKT,EAAQU,EAAOC,GAE3B,GADAX,EAASQ,GAASR,GACdA,IAAWW,GAAmB/I,SAAV8I,GACtB,MAAOV,GAAOY,QAAQC,GAAQ,GAEhC,KAAKb,KAAYU,EAAQrB,EAAaqB,IACpC,MAAOV,EAET,IAAIJ,GAAaW,GAAcP,GAC3BH,EAAaU,GAAcG,GAC3BlM,EAAQsL,GAAgBF,EAAYC,GACpCJ,EAAME,GAAcC,EAAYC,GAAc,CAElD,OAAOH,IAAUE,EAAYpL,EAAOiL,GAAKqB,KAAK,IAQhD,QAASC,IAAYnL,GAOjB,MANAA,GAAOA,EAAK4K,WAAWI,QAAQI,GAAgB,IAC/CpL,EAAOA,EAAKyK,MAAMY,IAAS,GAAGL,QAAQ,IAAK,IAC3ChL,EAAOA,EAAOA,EAAKqK,MAAMiB,OACzBtL,EAAOA,EAAKuL,IAAI,SAAU5F,GACtB,MAAOkF,IAAKlF,EAAIqF,QAAQQ,GAAQ,OAuFxC,QAASC,IAAWC,EAAOxL,GACvB,GAAIyL,KAEJ7C,GAAW4C,EAAO,SAAUE,EAAQ5G,GA2BhC,QAAS6G,GAAQ3D,EAAS4D,GACtB,GAAIC,GAAUzC,EAAS0C,EAAQ,SAAUC,GACrC,MAAO/D,GAAQ+D,IAEnBF,GAAQ7G,KAAK4G,GACb7K,EAAU2K,GAAQ9L,MAAM,KAAMiM,GA/BlC,GAAIC,GACAE,EAAYrL,EAAQ+K,GACpBO,GACED,GAA+B,IAAlBN,EAAO5M,QACrBkN,GAA+B,IAAlBN,EAAO5M,MAEzB,IAAIuF,GAAQqH,GACRI,EAASJ,EAAOlN,MAAM,GAAG,GACzBkN,EAASA,EAAOA,EAAO5M,OAAS,GAEhC2M,EAAS3G,GAAOgH,EAAOvK,OAAOuK,EAAOhN,OAAS,EAAI6M,EAAUD,OACzD,IAAIO,EAEPR,EAAS3G,GAAO4G,MACb,CAEH,GADAI,EAASb,GAAYS,GACC,IAAlBA,EAAO5M,SAAiBkN,GAA+B,IAAlBF,EAAOhN,OAC5C,KAAM,IAAIyB,OAAM,yDAIfyL,IAAWF,EAAOI,MAEvBT,EAAS3G,GAAOgH,EAAOvK,OAAOoK,MAYtCQ,GAAKV,EAAUzL,GAOnB,QAASoM,MACL7N,KAAK8N,KAAO9N,KAAK+N,KAAO,KACxB/N,KAAKO,OAAS,EAGlB,QAASyN,IAAWC,EAAKC,GACrBD,EAAI1N,OAAS,EACb0N,EAAIH,KAAOG,EAAIF,KAAOG,EA6E1B,QAASC,IAAMC,EAAQC,EAAaC,GAahC,QAASC,GAAQC,EAAMC,EAAehN,GAClC,GAAgB,MAAZA,GAAwC,kBAAbA,GAC3B,KAAM,IAAIO,OAAM,mCAMpB,IAJA0M,EAAEC,SAAU,EACP7I,GAAQ0I,KACTA,GAAQA,IAEQ,IAAhBA,EAAKjO,QAAgBmO,EAAEE,OAEvB,MAAO1M,IAAe,WAClBwM,EAAEG,SAIV,KAAK,GAAInH,GAAI,EAAGoH,EAAIN,EAAKjO,OAAQmH,EAAIoH,EAAGpH,IAAK,CACzC,GAAII,IACA0G,KAAMA,EAAK9G,GACXjG,SAAUA,GAAYgD,EAGtBgK,GACAC,EAAEK,OAAOC,QAAQlH,GAEjB4G,EAAEK,OAAOtI,KAAKqB,GAIjBmH,IACDA,GAAsB,EACtB/M,GAAe,WACX+M,GAAsB,EACtBP,EAAEQ,aAKd,QAASC,GAAMlC,GACX,MAAO,UAASnL,GACZsN,GAAc,CAEd,KAAK,GAAI1H,GAAI,EAAGoH,EAAI7B,EAAM1M,OAAQmH,EAAIoH,EAAGpH,IAAK,CAC1C,GAAI2H,GAAOpC,EAAMvF,GAEb3C,EAAQ6F,EAAY0E,EAAaD,EAAM,EAC7B,KAAVtK,EACAuK,EAAYC,QACLxK,EAAQ,GACfuK,EAAYE,OAAOzK,EAAO,GAG9BsK,EAAK5N,SAASJ,MAAMgO,EAAMjO,WAEf,MAAPU,GACA4M,EAAEzM,MAAMH,EAAKuN,EAAKb,MAItBY,GAAeV,EAAEL,YAAcK,EAAEe,QACjCf,EAAEgB,cAGFhB,EAAEE,QACFF,EAAEG,QAENH,EAAEQ,WA7EV,GAAmB,MAAfb,EACAA,EAAc,MAEb,IAAmB,IAAhBA,EACJ,KAAM,IAAIrM,OAAM,+BAGpB,IAAI2N,GAAUnN,EAAU4L,GACpBgB,EAAa,EACbE,KAEAL,GAAsB,EAsEtBW,GAAe,EACflB,GACAK,OAAQ,GAAIlB,IACZQ,YAAaA,EACbC,QAASA,EACTuB,UAAWpL,EACXiL,YAAYjL,EACZgL,OAAQpB,EAAc,EACtByB,MAAOrL,EACPoK,MAAOpK,EACPxC,MAAOwC,EACPkK,SAAS,EACToB,QAAQ,EACRtJ,KAAM,SAAU+H,EAAM/M,GAClB8M,EAAQC,GAAM,EAAO/M,IAEzBuO,KAAM,WACFtB,EAAEG,MAAQpK,EACViK,EAAEK,OAAOe,SAEbd,QAAS,SAAUR,EAAM/M,GACrB8M,EAAQC,GAAM,EAAM/M,IAExBwO,OAAQ,SAAUC,GACdxB,EAAEK,OAAOkB,OAAOC,IAEpBhB,QAAS,WAGL,IAAIU,EAAJ,CAIA,IADAA,GAAe,GACRlB,EAAEqB,QAAUX,EAAaV,EAAEL,aAAeK,EAAEK,OAAOxO,QAAO,CAC7D,GAAI0M,MAAYuB,KACZM,EAAIJ,EAAEK,OAAOxO,MACbmO,GAAEJ,UAASQ,EAAIzO,KAAK8P,IAAIrB,EAAGJ,EAAEJ,SACjC,KAAK,GAAI5G,GAAI,EAAGA,EAAIoH,EAAGpH,IAAK,CACxB,GAAIwG,GAAOQ,EAAEK,OAAOQ,OACpBtC,GAAMxG,KAAKyH,GACXoB,EAAY7I,KAAKyH,GACjBM,EAAK/H,KAAKyH,EAAKM,MAGnBY,GAAc,EAEU,IAApBV,EAAEK,OAAOxO,QACTmO,EAAEoB,QAGFV,IAAeV,EAAEL,aACjBK,EAAEmB,WAGN,IAAI9M,GAAKsF,EAAS8G,EAAMlC,GACxB0C,GAAQnB,EAAMzL,GAElB6M,GAAe,IAEnBrP,OAAQ,WACJ,MAAOmO,GAAEK,OAAOxO,QAEpBkI,QAAS,WACL,MAAO2G,IAEXE,YAAa,WACT,MAAOA,IAEXV,KAAM,WACF,MAAOF,GAAEK,OAAOxO,OAAS6O,IAAe,GAE5CgB,MAAO,WACH1B,EAAEqB,QAAS,GAEfM,OAAQ,WACA3B,EAAEqB,UAAW,IACjBrB,EAAEqB,QAAS,EACX7N,GAAewM,EAAEQ,WAGzB,OAAOR,GAgFX,QAAS4B,IAAMlC,EAAQE,GACnB,MAAOH,IAAMC,EAAQ,EAAGE,GA8D5B,QAASiC,IAAO9I,EAAM+I,EAAM1L,EAAUrD,GAClCA,EAAWiD,EAAKjD,GAAYgD,EAC5B,IAAIkF,GAAYnH,EAAUsC,EAC1B2L,IAAahJ,EAAM,SAASiJ,EAAGhJ,EAAGjG,GAC9BkI,EAAU6G,EAAME,EAAG,SAAS5O,EAAK+H,GAC7B2G,EAAO3G,EACPpI,EAASK,MAEd,SAASA,GACRL,EAASK,EAAK0O,KA0CtB,QAASG,MACL,GAAIC,GAAa/F,EAASzJ,UAAWoB,EACrC,OAAO,YACH,GAAIrB,GAAOlB,EAAMmB,WACb0B,EAAO9C,KAEP+C,EAAK5B,EAAKA,EAAKZ,OAAS,EACX,mBAANwC,GACP5B,EAAKwM,MAEL5K,EAAK0B,EAGT8L,GAAOK,EAAYzP,EAAM,SAAS0P,EAAS9P,EAAIgC,GAC3ChC,EAAGM,MAAMyB,EAAM+N,EAAQ7N,OAAO,SAASlB,GACnC,GAAIgP,GAAW7Q,EAAMmB,UAAW,EAChC2B,GAAGjB,EAAKgP,OAGhB,SAAShP,EAAK2H,GACV1G,EAAG1B,MAAMyB,GAAOhB,GAAKkB,OAAOyG,OAsMxC,QAASsH,IAASnQ,GAChB,MAAOA,GAGT,QAASoQ,IAAcC,EAAOC,GAC1B,MAAO,UAASvO,EAAQ6G,EAAK1E,EAAU/B,GACnCA,EAAKA,GAAM0B,CACX,IACI0M,GADAC,GAAa,CAEjBzO,GAAO6G,EAAK,SAAS5I,EAAOgJ,EAAGnI,GAC3BqD,EAASlE,EAAO,SAASkB,EAAKJ,GACtBI,EACAL,EAASK,GACFmP,EAAMvP,KAAYyP,GACzBC,GAAa,EACbD,EAAaD,GAAU,EAAMtQ,GAC7Ba,EAAS,KAAMiH,KAEfjH,OAGT,SAASK,GACJA,EACAiB,EAAGjB,GAEHiB,EAAG,KAAMqO,EAAaD,EAAaD,GAAU,OAM7D,QAASG,IAAexH,EAAG6G,GACvB,MAAOA,GAsFX,QAASY,IAAY9D,GACjB,MAAO,UAAUzM,GACb,GAAII,GAAOlB,EAAMmB,UAAW,EAC5BD,GAAKsF,KAAK,SAAU3E,GAChB,GAAIX,GAAOlB,EAAMmB,UAAW,EACL,iBAAZmQ,WACHzP,EACIyP,QAAQtP,OACRsP,QAAQtP,MAAMH,GAEXyP,QAAQ/D,IACfzD,EAAU5I,EAAM,SAAUuP,GACtBa,QAAQ/D,GAAMkD,QAK9BlO,EAAUzB,GAAIM,MAAM,KAAMF,IAuDlC,QAASqQ,IAASzQ,EAAIwE,EAAM9D,GAKxB,QAASsG,GAAKjG,GACV,GAAIA,EAAK,MAAOL,GAASK,EACzB,IAAIX,GAAOlB,EAAMmB,UAAW,EAC5BD,GAAKsF,KAAKwK,GACVQ,EAAMpQ,MAAMrB,KAAMmB,GAGtB,QAAS8P,GAAMnP,EAAK4P,GAChB,MAAI5P,GAAYL,EAASK,GACpB4P,MACLC,GAAI5J,GADetG,EAAS,MAbhCA,EAAW4G,EAAS5G,GAAYgD,EAChC,IAAIkN,GAAMnP,EAAUzB,GAChB0Q,EAAQjP,EAAU+C,EAetB0L,GAAM,MAAM,GA0BhB,QAASW,IAAS9M,EAAUS,EAAM9D,GAC9BA,EAAW4G,EAAS5G,GAAYgD,EAChC,IAAIkF,GAAYnH,EAAUsC,GACtBiD,EAAO,SAASjG,GAChB,GAAIA,EAAK,MAAOL,GAASK,EACzB,IAAIX,GAAOlB,EAAMmB,UAAW,EAC5B,OAAImE,GAAKlE,MAAMrB,KAAMmB,GAAcwI,EAAU5B,OAC7CtG,GAASJ,MAAM,MAAO,MAAM2B,OAAO7B,IAEvCwI,GAAU5B,GAuBd,QAAS8J,IAAQ/M,EAAUS,EAAM9D,GAC7BmQ,GAAS9M,EAAU,WACf,OAAQS,EAAKlE,MAAMrB,KAAMoB,YAC1BK,GAuCP,QAASqQ,IAAOvM,EAAMxE,EAAIU,GAKtB,QAASsG,GAAKjG,GACV,MAAIA,GAAYL,EAASK,OACzB2P,GAAMR,GAGV,QAASA,GAAMnP,EAAK4P,GAChB,MAAI5P,GAAYL,EAASK,GACpB4P,MACLC,GAAI5J,GADetG,EAAS,MAXhCA,EAAW4G,EAAS5G,GAAYgD,EAChC,IAAIkN,GAAMnP,EAAUzB,GAChB0Q,EAAQjP,EAAU+C,EAatBkM,GAAMR,GAGV,QAASc,IAAcjN,GACnB,MAAO,UAAUlE,EAAOmE,EAAOtD,GAC3B,MAAOqD,GAASlE,EAAOa,IA6D/B,QAASuQ,IAAUvK,EAAM3C,EAAUrD,GAC/B6H,GAAO7B,EAAMsK,GAAcvP,EAAUsC,IAAYrD,GAuBrD,QAASwQ,IAAYxK,EAAMc,EAAOzD,EAAUrD,GACxC6G,EAAaC,GAAOd,EAAMsK,GAAcvP,EAAUsC,IAAYrD,GA2DlE,QAASyQ,IAAYnR,GACjB,MAAIqB,GAAQrB,GAAYA,EACjBS,GAAc,SAAUL,EAAMM,GACjC,GAAI0Q,IAAO,CACXhR,GAAKsF,KAAK,WACN,GAAI2L,GAAYhR,SACZ+Q,GACAjQ,GAAe,WACXT,EAASJ,MAAM,KAAM+Q,KAGzB3Q,EAASJ,MAAM,KAAM+Q,KAG7BrR,EAAGM,MAAMrB,KAAMmB,GACfgR,GAAO,IAIf,QAASE,IAAMxI,GACX,OAAQA,EAmFZ,QAASyI,IAAa/L,GACpB,MAAO,UAASa,GACd,MAAiB,OAAVA,EAAiB7D,OAAY6D,EAAOb,IAI/C,QAASgM,IAAY5P,EAAQ6G,EAAK1E,EAAUrD,GACxC,GAAI+Q,GAAc,GAAI/R,OAAM+I,EAAIjJ,OAChCoC,GAAO6G,EAAK,SAAUkH,EAAG3L,EAAOtD,GAC5BqD,EAAS4L,EAAG,SAAU5O,EAAK+H,GACvB2I,EAAYzN,KAAW8E,EACvBpI,EAASK,MAEd,SAAUA,GACT,GAAIA,EAAK,MAAOL,GAASK,EAEzB,KAAK,GADD2H,MACK/B,EAAI,EAAGA,EAAI8B,EAAIjJ,OAAQmH,IACxB8K,EAAY9K,IAAI+B,EAAQhD,KAAK+C,EAAI9B,GAEzCjG,GAAS,KAAMgI,KAIvB,QAASgJ,IAAc9P,EAAQ8E,EAAM3C,EAAUrD,GAC3C,GAAIgI,KACJ9G,GAAO8E,EAAM,SAAUiJ,EAAG3L,EAAOtD,GAC7BqD,EAAS4L,EAAG,SAAU5O,EAAK+H,GACnB/H,EACAL,EAASK,IAEL+H,GACAJ,EAAQhD,MAAM1B,MAAOA,EAAOnE,MAAO8P,IAEvCjP,QAGT,SAAUK,GACLA,EACAL,EAASK,GAETL,EAAS,KAAMoJ,EAASpB,EAAQiJ,KAAK,SAAUC,EAAGC,GAC9C,MAAOD,GAAE5N,MAAQ6N,EAAE7N,QACnBuN,GAAa,aAK7B,QAASO,IAAQlQ,EAAQ8E,EAAM3C,EAAUrD,GACrC,GAAIqR,GAAStO,EAAYiD,GAAQ8K,GAAcE,EAC/CK,GAAOnQ,EAAQ8E,EAAMjF,EAAUsC,GAAWrD,GAAYgD,GAqG1D,QAASsO,IAAQhS,EAAIiS,GAIjB,QAASjL,GAAKjG,GACV,MAAIA,GAAYkG,EAAKlG,OACrBuN,GAAKtH,GALT,GAAIC,GAAOK,EAAS2K,GAAWvO,GAC3B4K,EAAO7M,EAAU0P,GAAYnR,GAMjCgH,KAiKJ,QAASkL,IAAe/K,EAAKK,EAAOzD,EAAUrD,GAC1CA,EAAWiD,EAAKjD,GAAYgD,EAC5B,IAAIyO,MACAvJ,EAAYnH,EAAUsC,EAC1BiE,GAAYb,EAAKK,EAAO,SAAS4K,EAAK5M,EAAKwB,GACvC4B,EAAUwJ,EAAK5M,EAAK,SAAUzE,EAAKJ,GAC/B,MAAII,GAAYiG,EAAKjG,IACrBoR,EAAO3M,GAAO7E,MACdqG,SAEL,SAAUjG,GACTL,EAASK,EAAKoR,KAwEtB,QAASE,IAAIlL,EAAK3B,GACd,MAAOA,KAAO2B,GAwClB,QAASmL,IAAQtS,EAAIuS,GACjB,GAAI9C,GAAOxM,OAAOuP,OAAO,MACrBC,EAASxP,OAAOuP,OAAO,KAC3BD,GAASA,GAAUvC,EACnB,IAAIY,GAAMnP,EAAUzB,GAChB0S,EAAWjS,GAAc,SAAkBL,EAAMM,GACjD,GAAI8E,GAAM+M,EAAOjS,MAAM,KAAMF,EACzBiS,IAAI5C,EAAMjK,GACVrE,GAAe,WACXT,EAASJ,MAAM,KAAMmP,EAAKjK,MAEvB6M,GAAII,EAAQjN,GACnBiN,EAAOjN,GAAKE,KAAKhF,IAEjB+R,EAAOjN,IAAQ9E,GACfkQ,EAAItQ,MAAM,KAAMF,EAAK6B,OAAO,WACxB,GAAI7B,GAAOlB,EAAMmB,UACjBoP,GAAKjK,GAAOpF,CACZ,IAAIuN,GAAI8E,EAAOjN,SACRiN,GAAOjN,EACd,KAAK,GAAImB,GAAI,EAAGoH,EAAIJ,EAAEnO,OAAQmH,EAAIoH,EAAGpH,IACjCgH,EAAEhH,GAAGrG,MAAM,KAAMF,QAOjC,OAFAsS,GAASjD,KAAOA,EAChBiD,EAASC,WAAa3S,EACf0S,EA8CX,QAASE,IAAUhR,EAAQsK,EAAOxL,GAC9BA,EAAWA,GAAYgD,CACvB,IAAIgF,GAAUjF,EAAYyI,QAE1BtK,GAAOsK,EAAO,SAAUoC,EAAM9I,EAAK9E,GAC/Be,EAAU6M,GAAM,SAAUvN,EAAKJ,GACvBN,UAAUb,OAAS,IACnBmB,EAASzB,EAAMmB,UAAW,IAE9BqI,EAAQlD,GAAO7E,EACfD,EAASK,MAEd,SAAUA,GACTL,EAASK,EAAK2H,KAyEtB,QAASmK,IAAc3G,EAAOxL,GAC1BkS,GAAUrK,GAAQ2D,EAAOxL,GAsB7B,QAASoS,IAAgB5G,EAAO1E,EAAO9G,GACnCkS,GAAUrL,EAAaC,GAAQ0E,EAAOxL,GA+N1C,QAASqS,IAAK7G,EAAOxL,GAEjB,GADAA,EAAWiD,EAAKjD,GAAYgD,IACvBqB,GAAQmH,GAAQ,MAAOxL,GAAS,GAAIsS,WAAU,wDACnD,KAAK9G,EAAM1M,OAAQ,MAAOkB,IAC1B,KAAK,GAAIiG,GAAI,EAAGoH,EAAI7B,EAAM1M,OAAQmH,EAAIoH,EAAGpH,IACrClF,EAAUyK,EAAMvF,IAAIjG,GA0B5B,QAASuS,IAAahK,EAAOwG,EAAM1L,EAAUrD,GACzC,GAAIwS,GAAWhU,EAAM+J,GAAOkK,SAC5B3D,IAAO0D,EAAUzD,EAAM1L,EAAUrD,GA0CrC,QAAS0S,IAAQpT,GACb,GAAI4Q,GAAMnP,EAAUzB,EACpB,OAAOS,IAAc,SAAmBL,EAAMiT,GAe1C,MAdAjT,GAAKsF,KAAK,SAAkBxE,EAAOoS,GAC/B,GAAIpS,EACAmS,EAAgB,MAAQnS,MAAOA,QAC5B,CACH,GAAIrB,EAEAA,GADAQ,UAAUb,QAAU,EACZ8T,EAEApU,EAAMmB,UAAW,GAE7BgT,EAAgB,MAAQxT,MAAOA,OAIhC+Q,EAAItQ,MAAMrB,KAAMmB,KAuE/B,QAASmT,IAAWrH,GAChB,GAAIxD,EASJ,OARI3D,IAAQmH,GACRxD,EAAUoB,EAASoC,EAAOkH,KAE1B1K,KACAY,EAAW4C,EAAO,SAASoC,EAAM9I,GAC7BkD,EAAQlD,GAAO4N,GAAQ/Q,KAAKpD,KAAMqP,MAGnC5F,EAGX,QAAS8K,IAAS5R,EAAQ6G,EAAK1E,EAAUrD,GACrCoR,GAAQlQ,EAAQ6G,EAAK,SAAS5I,EAAOmC,GACjC+B,EAASlE,EAAO,SAASkB,EAAK+H,GAC1B9G,EAAGjB,GAAM+H,MAEdpI,GA2FP,QAAS+S,IAAW5T,GAClB,MAAO,YACL,MAAOA,IAwFX,QAAS6T,IAAMC,EAAMrF,EAAM5N,GASvB,QAASkT,GAAWC,EAAKC,GACrB,GAAiB,gBAANA,GACPD,EAAIE,OAASD,EAAEC,OAASC,EAExBH,EAAII,aAAqC,kBAAfH,GAAEI,SACxBJ,EAAEI,SACFT,IAAYK,EAAEI,UAAYC,GAE9BN,EAAIO,YAAcN,EAAEM,gBACjB,CAAA,GAAiB,gBAANN,IAA+B,gBAANA,GAGvC,KAAM,IAAI7S,OAAM,oCAFhB4S,GAAIE,OAASD,GAAKE,GAqB1B,QAASK,KACLC,EAAM,SAASvT,GACPA,GAAOwT,IAAYC,EAAQT,QACI,kBAAvBS,GAAQJ,aACZI,EAAQJ,YAAYrT,IACxBd,WAAWoU,EAAcG,EAAQP,aAAaM,IAE9C7T,EAASJ,MAAM,KAAMD,aA9CjC,GAAI2T,GAAgB,EAChBG,EAAmB,EAEnBK,GACAT,MAAOC,EACPC,aAAcR,GAAWU,GA2B7B,IARI9T,UAAUb,OAAS,GAAqB,kBAATmU,IAC/BjT,EAAW4N,GAAQ5K,EACnB4K,EAAOqF,IAEPC,EAAWY,EAASb,GACpBjT,EAAWA,GAAYgD,GAGP,kBAAT4K,GACP,KAAM,IAAIrN,OAAM,oCAGpB,IAAIqT,GAAQ7S,EAAU6M,GAElBiG,EAAU,CAadF,KAgHJ,QAASI,IAAOvI,EAAOxL,GACnBkS,GAAUlD,GAAcxD,EAAOxL,GA+HnC,QAASgU,IAAQhO,EAAM3C,EAAUrD,GAY7B,QAASiU,GAAWC,EAAMC,GACtB,GAAIjD,GAAIgD,EAAKE,SAAUjD,EAAIgD,EAAMC,QACjC,OAAOlD,GAAIC,GAAI,EAAKD,EAAIC,EAAI,EAAI,EAbpC,GAAIjJ,GAAYnH,EAAUsC,EAC1BgI,IAAIrF,EAAM,SAAUiJ,EAAGjP,GACnBkI,EAAU+G,EAAG,SAAU5O,EAAK+T,GACxB,MAAI/T,GAAYL,EAASK,OACzBL,GAAS,MAAOb,MAAO8P,EAAGmF,SAAUA,OAEzC,SAAU/T,EAAK2H,GACd,MAAI3H,GAAYL,EAASK,OACzBL,GAAS,KAAMoJ,EAASpB,EAAQiJ,KAAKgD,GAAapD,GAAa,aAkDvE,QAASwD,IAAQrT,EAASsT,EAAcC,GACpC,GAAIjV,GAAKyB,EAAUC,EAEnB,OAAOjB,IAAc,SAAUL,EAAMM,GAIjC,QAASwU,KACL,GAAIzI,GAAO/K,EAAQ+K,MAAQ,YACvBvL,EAAS,GAAID,OAAM,sBAAwBwL,EAAO,eACtDvL,GAAMiU,KAAO,YACTF,IACA/T,EAAM+T,KAAOA,GAEjBG,GAAW,EACX1U,EAASQ,GAXb,GACImU,GADAD,GAAW,CAcfhV,GAAKsF,KAAK,WACD0P,IACD1U,EAASJ,MAAM,KAAMD,WACrBiV,aAAaD,MAKrBA,EAAQpV,WAAWiV,EAAiBF,GACpChV,EAAGM,MAAM,KAAMF,KAmBvB,QAASmV,IAAUnW,EAAOiL,EAAKmL,EAAMrM,GAKnC,IAJA,GAAInF,IAAQ,EACRxE,EAASiW,GAAUC,IAAYrL,EAAMjL,IAAUoW,GAAQ,IAAK,GAC5D7U,EAASjB,MAAMF,GAEZA,KACLmB,EAAOwI,EAAY3J,IAAWwE,GAAS5E,EACvCA,GAASoW,CAEX,OAAO7U,GAmBT,QAASgV,IAAUC,EAAOpO,EAAOzD,EAAUrD,GACvC,GAAIkI,GAAYnH,EAAUsC,EAC1B8R,IAASN,GAAU,EAAGK,EAAO,GAAIpO,EAAOoB,EAAWlI,GA+FvD,QAASwF,IAAWQ,EAAMoP,EAAa/R,EAAUrD,GACzCL,UAAUb,QAAU,IACpBkB,EAAWqD,EACXA,EAAW+R,EACXA,EAAc/Q,GAAQ2B,UAE1BhG,EAAWiD,EAAKjD,GAAYgD,EAC5B,IAAIkF,GAAYnH,EAAUsC,EAE1BwE,IAAO7B,EAAM,SAASoC,EAAGiN,EAAG/T,GACxB4G,EAAUkN,EAAahN,EAAGiN,EAAG/T,IAC9B,SAASjB,GACRL,EAASK,EAAK+U,KAyCtB,QAASE,IAAQ9J,EAAOxL,GACpB,GACIC,GADAO,EAAQ,IAEZR,GAAWA,GAAYgD,EACvBuS,GAAW/J,EAAO,SAASoC,EAAM5N,GAC7Be,EAAU6M,GAAM,SAAUvN,EAAKmV,GAEvBvV,EADAN,UAAUb,OAAS,EACVN,EAAMmB,UAAW,GAEjB6V,EAEbhV,EAAQH,EACRL,GAAUK,MAEf,WACCL,EAASQ,EAAOP,KAiBxB,QAASwV,IAAUnW,GACf,MAAO,YACH,OAAQA,EAAG2S,YAAc3S,GAAIM,MAAM,KAAMD,YAsCjD,QAAS+V,IAAO5R,EAAMT,EAAUrD,GAC5BA,EAAW4G,EAAS5G,GAAYgD,EAChC,IAAIkF,GAAYnH,EAAUsC,EAC1B,KAAKS,IAAQ,MAAO9D,GAAS,KAC7B,IAAIsG,GAAO,SAASjG,GAChB,GAAIA,EAAK,MAAOL,GAASK,EACzB,IAAIyD,IAAQ,MAAOoE,GAAU5B,EAC7B,IAAI5G,GAAOlB,EAAMmB,UAAW,EAC5BK,GAASJ,MAAM,MAAO,MAAM2B,OAAO7B,IAEvCwI,GAAU5B,GAyBd,QAASqP,IAAM7R,EAAMT,EAAUrD,GAC3B0V,GAAO,WACH,OAAQ5R,EAAKlE,MAAMrB,KAAMoB,YAC1B0D,EAAUrD,GAzkKjB,GA8DI4V,IA9DAhW,GAAQ,SAASN,GACjB,GAAII,GAAOlB,EAAMmB,UAAW,EAC5B,OAAO,YACH,GAAIkW,GAAWrX,EAAMmB,UACrB,OAAOL,GAAGM,MAAM,KAAMF,EAAK6B,OAAOsU,MAItC9V,GAAgB,SAAUT,GAC1B,MAAO,YACH,GAAII,GAAOlB,EAAMmB,WACbK,EAAWN,EAAKwM,KACpB5M,GAAGqC,KAAKpD,KAAMmB,EAAMM,KAkCxB8V,GAA0C,kBAAjBC,eAA+BA,aACxDC,GAAiC,gBAAZvI,UAAoD,kBAArBA,SAAQwI,QAkB5DL,IADAE,GACSC,aACFC,GACEvI,QAAQwI,SAER5W,CAGb,IAAIoB,IAAiBjB,EAAKoW,IA2FtBhV,GAAmC,kBAAXC,QA6BxBqV,GAA8B,gBAAVlY,SAAsBA,QAAUA,OAAOuE,SAAWA,QAAUvE,OAGhFmY,GAA0B,gBAARC,OAAoBA,MAAQA,KAAK7T,SAAWA,QAAU6T,KAGxEC,GAAOH,IAAcC,IAAYG,SAAS,iBAG1CC,GAAWF,GAAKxV,OAGhB2V,GAAcjU,OAAO8C,UAGrB3D,GAAiB8U,GAAY9U,eAO7BM,GAAuBwU,GAAY9L,SAGnC9I,GAAmB2U,GAAWA,GAASzV,YAAcgB,OA8BrD2U,GAAgBlU,OAAO8C,UAOvBnD,GAAyBuU,GAAc/L,SAcvCrI,GAAU,gBACVD,GAAe,qBAGfE,GAAiBiU,GAAWA,GAASzV,YAAcgB,OAmBnDa,GAAW,yBACXF,GAAU,oBACVC,GAAS,6BACTE,GAAW,iBA8BXE,GAAmB,iBAgEnBmE,MA2BAyP,GAAmC,kBAAX7V,SAAyBA,OAAOuF,SAExDO,GAAc,SAAUX,GACxB,MAAO0Q,KAAkB1Q,EAAK0Q,KAAmB1Q,EAAK0Q,OAmDtDjT,GAAU,qBAcVkT,GAAgBpU,OAAO8C,UAGvBuR,GAAmBD,GAAcjV,eAGjCmV,GAAuBF,GAAcE,qBAoBrCtS,GAAcf,EAAgB,WAAa,MAAO7D,eAAkB6D,EAAkB,SAASrE,GACjG,MAAOoE,GAAapE,IAAUyX,GAAiBjV,KAAKxC,EAAO,YACxD0X,GAAqBlV,KAAKxC,EAAO,WA0BlCkF,GAAUrF,MAAMqF,QAoBhByS,GAAgC,gBAAX5Y,IAAuBA,IAAYA,EAAQ6Y,UAAY7Y,EAG5E8Y,GAAaF,IAAgC,gBAAV3Y,SAAsBA,SAAWA,OAAO4Y,UAAY5Y,OAGvF8Y,GAAgBD,IAAcA,GAAW9Y,UAAY4Y,GAGrDI,GAASD,GAAgBZ,GAAKa,OAASpV,OAGvCqV,GAAiBD,GAASA,GAAOzS,SAAW3C,OAmB5C2C,GAAW0S,IAAkBzT,EAG7BE,GAAqB,iBAGrBC,GAAW,mBAqBXuT,GAAY,qBACZC,GAAW,iBACXC,GAAU,mBACVC,GAAU,gBACVC,GAAW,iBACXC,GAAY,oBACZC,GAAS,eACTC,GAAY,kBACZC,GAAY,kBACZC,GAAY,kBACZC,GAAS,eACTC,GAAY,kBACZC,GAAa,mBAEbC,GAAiB,uBACjBC,GAAc,oBACdC,GAAa,wBACbC,GAAa,wBACbC,GAAU,qBACVC,GAAW,sBACXC,GAAW,sBACXC,GAAW,sBACXC,GAAkB,6BAClBC,GAAY,uBACZC,GAAY,uBAGZ3U,KACJA,IAAemU,IAAcnU,GAAeoU,IAC5CpU,GAAeqU,IAAWrU,GAAesU,IACzCtU,GAAeuU,IAAYvU,GAAewU,IAC1CxU,GAAeyU,IAAmBzU,GAAe0U,IACjD1U,GAAe2U,KAAa,EAC5B3U,GAAeoT,IAAapT,GAAeqT,IAC3CrT,GAAeiU,IAAkBjU,GAAesT,IAChDtT,GAAekU,IAAelU,GAAeuT,IAC7CvT,GAAewT,IAAYxT,GAAeyT,IAC1CzT,GAAe0T,IAAU1T,GAAe2T,IACxC3T,GAAe4T,IAAa5T,GAAe6T,IAC3C7T,GAAe8T,IAAU9T,GAAe+T,IACxC/T,GAAegU,KAAc,CA4B7B,IAAIY,IAAkC,gBAAX1a,IAAuBA,IAAYA,EAAQ6Y,UAAY7Y,EAG9E2a,GAAeD,IAAkC,gBAAVza,SAAsBA,SAAWA,OAAO4Y,UAAY5Y,OAG3F2a,GAAkBD,IAAgBA,GAAa3a,UAAY0a,GAG3DG,GAAcD,IAAmB5C,GAAWzI,QAG5CuL,GAAY,WACd,IAEE,GAAIC,GAAQJ,IAAgBA,GAAaK,SAAWL,GAAaK,QAAQ,QAAQD,KAEjF,OAAIA,GACKA,EAIFF,IAAeA,GAAYI,SAAWJ,GAAYI,QAAQ,QACjE,MAAOjZ,QAIPkZ,GAAmBJ,IAAYA,GAASrU,aAmBxCA,GAAeyU,GAAmBnV,EAAUmV,IAAoBrV,EAGhEsV,GAAgB9W,OAAO8C,UAGvBN,GAAmBsU,GAAc3X,eAsCjC4D,GAAgB/C,OAAO8C,UA+BvBO,GAAaL,EAAQhD,OAAOuD,KAAMvD,QAGlC+W,GAAgB/W,OAAO8C,UAGvBQ,GAAmByT,GAAc5X,eA0MjC6X,GAAgBhS,EAAQD,EAAakS,EAAAA,GAyCrC3R,GAAS,SAAS7B,EAAM3C,EAAUrD,GAClC,GAAIyZ,GAAuB1W,EAAYiD,GAAQyB,EAAkB8R,EACjEE,GAAqBzT,EAAMjF,EAAUsC,GAAWrD,IA+DhDqL,GAAMzD,EAAWE,GAmCjB4R,GAAYzY,EAAYoK,IA2BxB8J,GAAW9M,EAAgBP,GAoB3B6R,GAAYpS,EAAQ4N,GAAU,GAqB9ByE,GAAkB3Y,EAAY0Y,IA0D9B9Q,GAAUL,IAoKV2D,GAAO,SAAUX,EAAOoB,EAAa5M,GAiErC,QAAS6Z,GAAY/U,EAAK8I,GACtBkM,EAAW9U,KAAK,WACZ+U,EAAQjV,EAAK8I,KAIrB,QAASoM,KACL,GAA0B,IAAtBF,EAAWhb,QAAiC,IAAjBmb,EAC3B,MAAOja,GAAS,KAAMgI,EAE1B,MAAM8R,EAAWhb,QAAUmb,EAAerN,GAAa,CACnD,GAAIsN,GAAMJ,EAAWhM,OACrBoM,MAKR,QAASC,GAAYC,EAAU9a,GAC3B,GAAI+a,GAAgBC,EAAUF,EACzBC,KACDA,EAAgBC,EAAUF,OAG9BC,EAAcrV,KAAK1F,GAGvB,QAASib,GAAaH,GAClB,GAAIC,GAAgBC,EAAUF,MAC9B9R,GAAU+R,EAAe,SAAU/a,GAC/BA,MAEJ0a,IAIJ,QAASD,GAAQjV,EAAK8I,GAClB,IAAI4M,EAAJ,CAEA,GAAIC,GAAe7T,EAAS,SAASvG,EAAKJ,GAKtC,GAJAga,IACIta,UAAUb,OAAS,IACnBmB,EAASzB,EAAMmB,UAAW,IAE1BU,EAAK,CACL,GAAIqa,KACJ9R,GAAWZ,EAAS,SAAS0J,EAAKiJ,GAC9BD,EAAYC,GAAQjJ,IAExBgJ,EAAY5V,GAAO7E,EACnBua,GAAW,EACXF,EAAY/X,OAAOuP,OAAO,MAE1B9R,EAASK,EAAKqa,OAEd1S,GAAQlD,GAAO7E,EACfsa,EAAazV,IAIrBmV,IACA,IAAIvO,GAAS3K,EAAU6M,EAAKA,EAAK9O,OAAS,GACtC8O,GAAK9O,OAAS,EACd4M,EAAO1D,EAASyS,GAEhB/O,EAAO+O,IAIf,QAASG,KAML,IAFA,GAAIC,GACA5S,EAAU,EACP6S,EAAahc,QAChB+b,EAAcC,EAAa5O,MAC3BjE,IACAK,EAAUyS,EAAcF,GAAc,SAAUG,GACD,MAArCC,EAAsBD,IACxBF,EAAa9V,KAAKgW,IAK9B,IAAI/S,IAAYiT,EACZ,KAAM,IAAI3a,OACN,iEAKZ,QAASwa,GAAcX,GACnB,GAAIna,KAMJ,OALA2I,GAAW4C,EAAO,SAAUoC,EAAM9I,GAC1BT,GAAQuJ,IAASzE,EAAYyE,EAAMwM,EAAU,IAAM,GACnDna,EAAO+E,KAAKF,KAGb7E,EAlKgB,kBAAhB2M,KAEP5M,EAAW4M,EACXA,EAAc,MAElB5M,EAAWiD,EAAKjD,GAAYgD,EAC5B,IAAImY,GAAUrV,EAAK0F,GACf0P,EAAWC,EAAQrc,MACvB,KAAKoc,EACD,MAAOlb,GAAS,KAEf4M,KACDA,EAAcsO,EAGlB,IAAIlT,MACAiS,EAAe,EACfO,GAAW,EAEXF,EAAY/X,OAAOuP,OAAO,MAE1BgI,KAGAgB,KAEAG,IAEJrS,GAAW4C,EAAO,SAAUoC,EAAM9I,GAC9B,IAAKT,GAAQuJ,GAIT,MAFAiM,GAAY/U,GAAM8I,QAClBkN,GAAa9V,KAAKF,EAItB,IAAIsW,GAAexN,EAAKpP,MAAM,EAAGoP,EAAK9O,OAAS,GAC3Cuc,EAAwBD,EAAatc,MACzC,OAA8B,KAA1Buc,GACAxB,EAAY/U,EAAK8I,OACjBkN,GAAa9V,KAAKF,KAGtBmW,EAAsBnW,GAAOuW,MAE7B/S,GAAU8S,EAAc,SAAUE,GAC9B,IAAK9P,EAAM8P,GACP,KAAM,IAAI/a,OAAM,oBAAsBuE,EAClC,oCACAwW,EAAiB,QACjBF,EAAapQ,KAAK,MAE1BmP,GAAYmB,EAAgB,WACxBD,IAC8B,IAA1BA,GACAxB,EAAY/U,EAAK8I,UAMjCgN,IACAZ,KA6HA1Q,GAAY,kBAyBZG,GAAW,EAAI,EAGf8R,GAAchF,GAAWA,GAASlR,UAAYvD,OAC9C0H,GAAiB+R,GAAcA,GAAY7Q,SAAW5I,OAoHtD0Z,GAAgB,kBAChBC,GAAoB,kBACpBC,GAAwB,kBACxBC,GAAsB,kBACtBC,GAAeH,GAAoBC,GAAwBC,GAC3DE,GAAa,iBAGbC,GAAQ,UAGRzR,GAAe0R,OAAO,IAAMD,GAAQN,GAAiBI,GAAeC,GAAa,KAcjFG,GAAkB,kBAClBC,GAAsB,kBACtBC,GAA0B,kBAC1BC,GAAwB,kBACxBC,GAAiBH,GAAsBC,GAA0BC,GACjEE,GAAe,iBAGfC,GAAW,IAAMN,GAAkB,IACnCO,GAAU,IAAMH,GAAiB,IACjCI,GAAS,2BACTC,GAAa,MAAQF,GAAU,IAAMC,GAAS,IAC9CE,GAAc,KAAOV,GAAkB,IACvCW,GAAa,kCACbC,GAAa,qCACbC,GAAU,UAGVC,GAAWL,GAAa,IACxBM,GAAW,IAAMV,GAAe,KAChCW,GAAY,MAAQH,GAAU,OAASH,GAAaC,GAAYC,IAAY5R,KAAK,KAAO,IAAM+R,GAAWD,GAAW,KACpHG,GAAQF,GAAWD,GAAWE,GAC9BE,GAAW,OAASR,GAAcH,GAAU,IAAKA,GAASI,GAAYC,GAAYN,IAAUtR,KAAK,KAAO,IAGxGR,GAAYuR,OAAOS,GAAS,MAAQA,GAAS,KAAOU,GAAWD,GAAO,KAoDtElS,GAAS,aAwCTI,GAAU,qDACVC,GAAe,IACfE,GAAS,eACTJ,GAAiB,kCAsJrBkB,IAAI/G,UAAU8X,WAAa,SAAS1Q,GAQhC,MAPIA,GAAK2Q,KAAM3Q,EAAK2Q,KAAK9W,KAAOmG,EAAKnG,KAChC/H,KAAK8N,KAAOI,EAAKnG,KAClBmG,EAAKnG,KAAMmG,EAAKnG,KAAK8W,KAAO3Q,EAAK2Q,KAChC7e,KAAK+N,KAAOG,EAAK2Q,KAEtB3Q,EAAK2Q,KAAO3Q,EAAKnG,KAAO,KACxB/H,KAAKO,QAAU,EACR2N,GAGXL,GAAI/G,UAAUgJ,MAAQ,WAClB,KAAM9P,KAAK8N,MAAM9N,KAAKuP,OACtB,OAAOvP,OAGX6N,GAAI/G,UAAUgY,YAAc,SAAS5Q,EAAM6Q,GACvCA,EAAQF,KAAO3Q,EACf6Q,EAAQhX,KAAOmG,EAAKnG,KAChBmG,EAAKnG,KAAMmG,EAAKnG,KAAK8W,KAAOE,EAC3B/e,KAAK+N,KAAOgR,EACjB7Q,EAAKnG,KAAOgX,EACZ/e,KAAKO,QAAU,GAGnBsN,GAAI/G,UAAUkY,aAAe,SAAS9Q,EAAM6Q,GACxCA,EAAQF,KAAO3Q,EAAK2Q,KACpBE,EAAQhX,KAAOmG,EACXA,EAAK2Q,KAAM3Q,EAAK2Q,KAAK9W,KAAOgX,EAC3B/e,KAAK8N,KAAOiR,EACjB7Q,EAAK2Q,KAAOE,EACZ/e,KAAKO,QAAU,GAGnBsN,GAAI/G,UAAUkI,QAAU,SAASd,GACzBlO,KAAK8N,KAAM9N,KAAKgf,aAAahf,KAAK8N,KAAMI,GACvCF,GAAWhO,KAAMkO,IAG1BL,GAAI/G,UAAUL,KAAO,SAASyH,GACtBlO,KAAK+N,KAAM/N,KAAK8e,YAAY9e,KAAK+N,KAAMG,GACtCF,GAAWhO,KAAMkO,IAG1BL,GAAI/G,UAAUyI,MAAQ,WAClB,MAAOvP,MAAK8N,MAAQ9N,KAAK4e,WAAW5e,KAAK8N,OAG7CD,GAAI/G,UAAU6G,IAAM,WAChB,MAAO3N,MAAK+N,MAAQ/N,KAAK4e,WAAW5e,KAAK+N,OAG7CF,GAAI/G,UAAUmY,QAAU,WAGpB,IAAI,GAFAzV,GAAM/I,MAAMT,KAAKO,QACjB2e,EAAOlf,KAAK8N,KACRpN,EAAM,EAAGA,EAAMV,KAAKO,OAAQG,IAChC8I,EAAI9I,GAAOwe,EAAK1Q,KAChB0Q,EAAOA,EAAKnX,IAEhB,OAAOyB,IAGXqE,GAAI/G,UAAUmJ,OAAS,SAAUC,GAE7B,IADA,GAAIgP,GAAOlf,KAAK8N,KACRoR,GAAM,CACV,GAAInX,GAAOmX,EAAKnX,IACZmI,GAAOgP,IACPlf,KAAK4e,WAAWM,GAEpBA,EAAOnX,EAEX,MAAO/H,MA0QX,IAi3CImf,IAj3CA1O,GAAezH,EAAQD,EAAa,GAyJpCqW,GAAU,WACV,MAAOzO,IAAItP,MAAM,KAAMpB,EAAMmB,WAAW8S,YAGxCmL,GAAU5e,MAAMqG,UAAU9D,OAoB1Bsc,GAAc,SAAS7X,EAAMc,EAAOzD,EAAUrD,GAC9CA,EAAWA,GAAYgD,CACvB,IAAIkF,GAAYnH,EAAUsC,EAC1B8R,IAASnP,EAAMc,EAAO,SAAS4K,EAAK1R,GAChCkI,EAAUwJ,EAAK,SAASrR,GACpB,MAAIA,GAAYL,EAASK,GAClBL,EAAS,KAAMxB,EAAMmB,UAAW,OAE5C,SAASU,EAAKyd,GAEb,IAAK,GADD7d,MACKgG,EAAI,EAAGA,EAAI6X,EAAWhf,OAAQmH,IAC/B6X,EAAW7X,KACXhG,EAAS2d,GAAQhe,MAAMK,EAAQ6d,EAAW7X,IAIlD,OAAOjG,GAASK,EAAKJ,MA6BzBsB,GAASgG,EAAQsW,GAAarE,EAAAA,GAoB9BuE,GAAexW,EAAQsW,GAAa,GA4CpCG,GAAW,WACX,GAAIC,GAASzf,EAAMmB,WACfD,GAAQ,MAAM6B,OAAO0c,EACzB,OAAO,YACH,GAAIje,GAAWL,UAAUA,UAAUb,OAAS,EAC5C,OAAOkB,GAASJ,MAAMrB,KAAMmB,KA0FhCwe,GAAStW,EAAW2H,GAAcD,GAAUM,KAwB5CuO,GAAc9V,EAAgBkH,GAAcD,GAAUM,KAsBtDwO,GAAe7W,EAAQ4W,GAAa,GAoDpCE,GAAMxO,GAAY,OA6QlB0F,GAAahO,EAAQiJ,GAAa,GAwFlC8N,GAAQ1W,EAAW2H,GAAcqB,GAAOA,KAsBxC2N,GAAalW,EAAgBkH,GAAcqB,GAAOA,KAqBlD4N,GAAcjX,EAAQgX,GAAY,GAwFlClN,GAASzJ,EAAWwJ,IAqBpBqN,GAAcpW,EAAgB+I,IAmB9BsN,GAAenX,EAAQkX,GAAa,GA6DpCE,GAAe,SAAS3Y,EAAMc,EAAOzD,EAAUrD,GAC/CA,EAAWA,GAAYgD,CACvB,IAAIkF,GAAYnH,EAAUsC,EAC1B8R,IAASnP,EAAMc,EAAO,SAAS4K,EAAK1R,GAChCkI,EAAUwJ,EAAK,SAASrR,EAAKyE,GACzB,MAAIzE,GAAYL,EAASK,GAClBL,EAAS,MAAO8E,IAAKA,EAAK4M,IAAKA,OAE3C,SAASrR,EAAKyd,GAKb,IAAK,GAJD7d,MAEAyB,EAAiBa,OAAO8C,UAAU3D,eAE7BuE,EAAI,EAAGA,EAAI6X,EAAWhf,OAAQmH,IACnC,GAAI6X,EAAW7X,GAAI,CACf,GAAInB,GAAMgZ,EAAW7X,GAAGnB,IACpB4M,EAAMoM,EAAW7X,GAAGyL,GAEpBhQ,GAAeC,KAAK1B,EAAQ6E,GAC5B7E,EAAO6E,GAAKE,KAAK0M,GAEjBzR,EAAO6E,IAAQ4M,GAK3B,MAAO1R,GAASK,EAAKJ,MAwCzB2e,GAAUrX,EAAQoX,GAAcnF,EAAAA,GAqBhCqF,GAAgBtX,EAAQoX,GAAc,GA6BtCG,GAAMjP,GAAY,OAmFlBkP,GAAYxX,EAAQiK,GAAgBgI,EAAAA,GAqBpCwF,GAAkBzX,EAAQiK,GAAgB,EA4G1CkM,IADA1H,GACWvI,QAAQwI,SACZH,GACIC,aAEA1W,CAGf,IAAI4W,IAAWzW,EAAKke,IA4NhBuB,GAAU,SAAUtS,EAAQC,GAC5B,GAAIsB,GAAUnN,EAAU4L,EACxB,OAAOD,IAAM,SAAUwS,EAAO5d,GAC1B4M,EAAQgR,EAAM,GAAI5d,IACnBsL,EAAa,IA0BhBuS,GAAgB,SAASxS,EAAQC,GAEjC,GAAIK,GAAIgS,GAAQtS,EAAQC,EA4CxB,OAzCAK,GAAEjI,KAAO,SAAS+H,EAAMqS,EAAUpf,GAE9B,GADgB,MAAZA,IAAkBA,EAAWgD,GACT,kBAAbhD,GACP,KAAM,IAAIO,OAAM,mCAMpB,IAJA0M,EAAEC,SAAU,EACP7I,GAAQ0I,KACTA,GAAQA,IAEQ,IAAhBA,EAAKjO,OAEL,MAAO2B,IAAe,WAClBwM,EAAEG,SAIVgS,GAAWA,GAAY,CAEvB,KADA,GAAIC,GAAWpS,EAAEK,OAAOjB,KACjBgT,GAAYD,GAAYC,EAASD,UACpCC,EAAWA,EAAS/Y,IAGxB,KAAK,GAAIL,GAAI,EAAGoH,EAAIN,EAAKjO,OAAQmH,EAAIoH,EAAGpH,IAAK,CACzC,GAAII,IACA0G,KAAMA,EAAK9G,GACXmZ,SAAUA,EACVpf,SAAUA,EAGVqf,GACApS,EAAEK,OAAOiQ,aAAa8B,EAAUhZ,GAEhC4G,EAAEK,OAAOtI,KAAKqB,GAGtB5F,GAAewM,EAAEQ,gBAIdR,GAAEM,QAEFN,GA0PPqS,GAAS1X,EAAWkL,IAqBpByM,GAAclX,EAAgByK,IAmB9B0M,GAAejY,EAAQgY,GAAa,GAkMpCE,GAAY,SAAUxM,EAAMrF,GACvBA,IACDA,EAAOqF,EACPA,EAAO,KAEX,IAAIW,GAAQ7S,EAAU6M,EACtB,OAAO7N,IAAc,SAAUL,EAAMM,GACjC,QAAS0L,GAAOpK,GACZsS,EAAMhU,MAAM,KAAMF,EAAK6B,OAAOD,IAG9B2R,EAAMD,GAAMC,EAAMvH,EAAQ1L,GACzBgT,GAAMtH,EAAQ1L,MAuGvB0f,GAAO9X,EAAW2H,GAAcoQ,QAASrQ,KAuBzCsQ,GAAYvX,EAAgBkH,GAAcoQ,QAASrQ,KAsBnDuQ,GAAatY,EAAQqY,GAAW,GA4IhC5K,GAAapW,KAAKkhB,KAClB/K,GAAYnW,KAAKC,IA8EjBwU,GAAQ9L,EAAQ0N,GAAWuE,EAAAA,GAgB3BuG,GAAcxY,EAAQ0N,GAAW,GA2QjC+K,GAAY,SAASxU,EAAOxL,GAM5B,QAASigB,GAASvgB,GACd,GAAIkO,GAAO7M,EAAUyK,EAAM0U,KAC3BxgB,GAAKsF,KAAK4B,EAASN,IACnBsH,EAAKhO,MAAM,KAAMF,GAGrB,QAAS4G,GAAKjG,GACV,MAAIA,IAAO6f,IAAc1U,EAAM1M,OACpBkB,EAASJ,MAAM,KAAMD,eAEhCsgB,GAASzhB,EAAMmB,UAAW,IAd9B,GADAK,EAAWiD,EAAKjD,GAAYgD,IACvBqB,GAAQmH,GAAQ,MAAOxL,GAAS,GAAIO,OAAM,6DAC/C,KAAKiL,EAAM1M,OAAQ,MAAOkB,IAC1B,IAAIkgB,GAAY,CAehBD,QAoEA3c,IACA1D,MAAOA,GACP8Z,UAAWA,GACXE,gBAAiBA,GACjB/Z,SAAUA,EACVsM,KAAMA,GACNZ,WAAYA,GACZsD,MAAOA,GACP8O,QAASA,GACTpc,OAAQA,GACRsc,YAAaA,GACbE,aAAcA,GACdC,SAAUA,GACVE,OAAQA,GACRC,YAAaA,GACbC,aAAcA,GACdC,IAAKA,GACLtO,SAAUA,GACVK,QAASA,GACTD,SAAUA,GACVE,OAAQA,GACR8P,KAAM5P,GACNA,UAAWC,GACX3I,OAAQA,GACRP,YAAaA,EACb0H,aAAcA,GACduG,WAAYA,GACZ9E,YAAaA,GACb6N,MAAOA,GACPC,WAAYA,GACZC,YAAaA,GACbnN,OAAQA,GACRoN,YAAaA,GACbC,aAAcA,GACdpN,QAASA,GACTsN,QAASA,GACTD,aAAcA,GACdE,cAAeA,GACfC,IAAKA,GACLzT,IAAKA,GACL8J,SAAUA,GACVwE,UAAWA,GACXoF,UAAWA,GACXvN,eAAgBA,GAChBwN,gBAAiBA,GACjBpN,QAASA,GACTqE,SAAUA,GACVmK,SAAUjO,GACVA,cAAeC,GACf+M,cAAeA,GACfzS,MAAOuS,GACP5M,KAAMA,GACNvD,OAAQA,GACRyD,YAAaA,GACbG,QAASA,GACTG,WAAYA,GACZyM,OAAQA,GACRC,YAAaA,GACbC,aAAcA,GACdxM,MAAOA,GACPyM,UAAWA,GACXvQ,IAAKA,GACL6E,OAAQA,GACRgC,aAActV,GACdif,KAAMA,GACNE,UAAWA,GACXC,WAAYA,GACZ7L,OAAQA,GACRK,QAASA,GACThB,MAAOA,GACPgN,WAAYpL,GACZ8K,YAAaA,GACbva,UAAWA,GACX8P,QAASA,GACTG,UAAWA,GACXE,MAAOA,GACPqK,UAAWA,GACXtK,OAAQA,GAGR4K,IAAKhC,GACLiC,SAAUhC,GACViC,UAAWhC,GACXiC,IAAKf,GACLgB,SAAUd,GACVe,UAAWd,GACXe,KAAM1C,GACN2C,UAAW1C,GACX2C,WAAY1C,GACZ2C,QAASxQ,GACTyQ,cAAezL,GACf0L,aAAczQ,GACd0Q,UAAWrZ,GACXsZ,gBAAiBnS,GACjBoS,eAAgB9Z,EAChB+Z,OAAQvS,GACRwS,MAAOxS,GACPyS,MAAOhP,GACPiP,OAAQnQ,GACRoQ,YAAahD,GACbiD,aAAchD,GACdiD,SAAU9hB,EAGd3B,GAAiB,QAAIoF,GACrBpF,EAAQ0B,MAAQA,GAChB1B,EAAQwb,UAAYA,GACpBxb,EAAQ0b,gBAAkBA,GAC1B1b,EAAQ2B,SAAWA,EACnB3B,EAAQiO,KAAOA,GACfjO,EAAQqN,WAAaA,GACrBrN,EAAQ2Q,MAAQA,GAChB3Q,EAAQyf,QAAUA,GAClBzf,EAAQqD,OAASA,GACjBrD,EAAQ2f,YAAcA,GACtB3f,EAAQ6f,aAAeA,GACvB7f,EAAQ8f,SAAWA,GACnB9f,EAAQggB,OAASA,GACjBhgB,EAAQigB,YAAcA,GACtBjgB,EAAQkgB,aAAeA,GACvBlgB,EAAQmgB,IAAMA,GACdngB,EAAQ6R,SAAWA,GACnB7R,EAAQkS,QAAUA,GAClBlS,EAAQiS,SAAWA,GACnBjS,EAAQmS,OAASA,GACjBnS,EAAQiiB,KAAO5P,GACfrS,EAAQqS,UAAYC,GACpBtS,EAAQ2J,OAASA,GACjB3J,EAAQoJ,YAAcA,EACtBpJ,EAAQ8Q,aAAeA,GACvB9Q,EAAQqX,WAAaA,GACrBrX,EAAQuS,YAAcA,GACtBvS,EAAQogB,MAAQA,GAChBpgB,EAAQqgB,WAAaA,GACrBrgB,EAAQsgB,YAAcA,GACtBtgB,EAAQmT,OAASA,GACjBnT,EAAQugB,YAAcA,GACtBvgB,EAAQwgB,aAAeA,GACvBxgB,EAAQoT,QAAUA,GAClBpT,EAAQ0gB,QAAUA,GAClB1gB,EAAQygB,aAAeA,GACvBzgB,EAAQ2gB,cAAgBA,GACxB3gB,EAAQ4gB,IAAMA,GACd5gB,EAAQmN,IAAMA,GACdnN,EAAQiX,SAAWA,GACnBjX,EAAQyb,UAAYA,GACpBzb,EAAQ6gB,UAAYA,GACpB7gB,EAAQsT,eAAiBA,GACzBtT,EAAQ8gB,gBAAkBA,GAC1B9gB,EAAQ0T,QAAUA,GAClB1T,EAAQ+X,SAAWA,GACnB/X,EAAQkiB,SAAWjO,GACnBjU,EAAQiU,cAAgBC,GACxBlU,EAAQihB,cAAgBA,GACxBjhB,EAAQwO,MAAQuS,GAChB/gB,EAAQmU,KAAOA,GACfnU,EAAQ4Q,OAASA,GACjB5Q,EAAQqU,YAAcA,GACtBrU,EAAQwU,QAAUA,GAClBxU,EAAQ2U,WAAaA,GACrB3U,EAAQohB,OAASA,GACjBphB,EAAQqhB,YAAcA,GACtBrhB,EAAQshB,aAAeA,GACvBthB,EAAQ8U,MAAQA,GAChB9U,EAAQuhB,UAAYA,GACpBvhB,EAAQgR,IAAMA,GACdhR,EAAQ6V,OAASA,GACjB7V,EAAQ6X,aAAetV,GACvBvC,EAAQwhB,KAAOA,GACfxhB,EAAQ0hB,UAAYA,GACpB1hB,EAAQ2hB,WAAaA,GACrB3hB,EAAQ8V,OAASA,GACjB9V,EAAQmW,QAAUA,GAClBnW,EAAQmV,MAAQA,GAChBnV,EAAQmiB,WAAapL,GACrB/W,EAAQ6hB,YAAcA,GACtB7hB,EAAQsH,UAAYA,GACpBtH,EAAQoX,QAAUA,GAClBpX,EAAQuX,UAAYA,GACpBvX,EAAQyX,MAAQA,GAChBzX,EAAQ8hB,UAAYA,GACpB9hB,EAAQwX,OAASA,GACjBxX,EAAQoiB,IAAMhC,GACdpgB,EAAQqiB,SAAWhC,GACnBrgB,EAAQsiB,UAAYhC,GACpBtgB,EAAQuiB,IAAMf,GACdxhB,EAAQwiB,SAAWd,GACnB1hB,EAAQyiB,UAAYd,GACpB3hB,EAAQ0iB,KAAO1C,GACfhgB,EAAQ2iB,UAAY1C,GACpBjgB,EAAQ4iB,WAAa1C,GACrBlgB,EAAQ6iB,QAAUxQ,GAClBrS,EAAQ8iB,cAAgBzL,GACxBrX,EAAQ+iB,aAAezQ,GACvBtS,EAAQgjB,UAAYrZ,GACpB3J,EAAQijB,gBAAkBnS,GAC1B9Q,EAAQkjB,eAAiB9Z,EACzBpJ,EAAQmjB,OAASvS,GACjB5Q,EAAQojB,MAAQxS,GAChB5Q,EAAQqjB,MAAQhP,GAChBrU,EAAQsjB,OAASnQ,GACjBnT,EAAQujB,YAAchD,GACtBvgB,EAAQwjB,aAAehD,GACvBxgB,EAAQyjB,SAAW9hB,EAEnB0C,OAAOqf,eAAe1jB,EAAS,cAAgBiB,OAAO","file":"build/dist/async.min.js"} \ No newline at end of file diff --git a/node_modules/async/doDuring.js b/node_modules/async/doDuring.js deleted file mode 100644 index 6812990b02b375d9aee658039e38161e615ed76a..0000000000000000000000000000000000000000 --- a/node_modules/async/doDuring.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doDuring; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in - * the order of operations, the arguments `test` and `fn` are switched. - * - * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. - * @name doDuring - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.during]{@link module:ControlFlow.during} - * @category Control Flow - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `fn`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error if one occurred, otherwise `null`. - */ -function doDuring(fn, test, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _fn = (0, _wrapAsync2.default)(fn); - var _test = (0, _wrapAsync2.default)(test); - - function next(err /*, ...args*/) { - if (err) return callback(err); - var args = (0, _slice2.default)(arguments, 1); - args.push(check); - _test.apply(this, args); - }; - - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - - check(null, true); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/doUntil.js b/node_modules/async/doUntil.js deleted file mode 100644 index 5a6a30f83568f1c08b3d2ecbe5d83f4b6e726ef3..0000000000000000000000000000000000000000 --- a/node_modules/async/doUntil.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doUntil; - -var _doWhilst = require('./doWhilst'); - -var _doWhilst2 = _interopRequireDefault(_doWhilst); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function doUntil(iteratee, test, callback) { - (0, _doWhilst2.default)(iteratee, function () { - return !test.apply(this, arguments); - }, callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/doWhilst.js b/node_modules/async/doWhilst.js deleted file mode 100644 index d9351131488982c2d06accb831d8eb1c1cf66215..0000000000000000000000000000000000000000 --- a/node_modules/async/doWhilst.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doWhilst; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - */ -function doWhilst(iteratee, test, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - var next = function (err /*, ...args*/) { - if (err) return callback(err); - var args = (0, _slice2.default)(arguments, 1); - if (test.apply(this, args)) return _iteratee(next); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/during.js b/node_modules/async/during.js deleted file mode 100644 index fd7343783e8b5ebe64a7aa2d731ed404bba9b89f..0000000000000000000000000000000000000000 --- a/node_modules/async/during.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = during; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that - * is passed a callback in the form of `function (err, truth)`. If error is - * passed to `test` or `fn`, the main callback is immediately called with the - * value of the error. - * - * @name during - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (callback). - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error, if one occurred, otherwise `null`. - * @example - * - * var count = 0; - * - * async.during( - * function (callback) { - * return callback(null, count < 5); - * }, - * function (callback) { - * count++; - * setTimeout(callback, 1000); - * }, - * function (err) { - * // 5 seconds have passed - * } - * ); - */ -function during(test, fn, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _fn = (0, _wrapAsync2.default)(fn); - var _test = (0, _wrapAsync2.default)(test); - - function next(err) { - if (err) return callback(err); - _test(check); - } - - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - - _test(check); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/each.js b/node_modules/async/each.js deleted file mode 100644 index 4b20af33db56195ba5c5ae088d965dad6d76e940..0000000000000000000000000000000000000000 --- a/node_modules/async/each.js +++ /dev/null @@ -1,82 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _withoutIndex = require('./internal/withoutIndex'); - -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` 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 `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // 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 - * }); - * - * // 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'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/eachLimit.js b/node_modules/async/eachLimit.js deleted file mode 100644 index fff721bce0f9fe87274aae90b3859b0814e02581..0000000000000000000000000000000000000000 --- a/node_modules/async/eachLimit.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; - -var _eachOfLimit = require('./internal/eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _withoutIndex = require('./internal/withoutIndex'); - -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/eachOf.js b/node_modules/async/eachOf.js deleted file mode 100644 index 055b9bde104f1c288b16742090728ac3da4df7d4..0000000000000000000000000000000000000000 --- a/node_modules/async/eachOf.js +++ /dev/null @@ -1,111 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll, iteratee, callback) { - var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); -}; - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _breakLoop = require('./internal/breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if (++completed === length || value === _breakLoop2.default) { - callback(null); - } - } - - for (; index < length; index++) { - iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); - } -} - -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); - -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * 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); - * }); - */ -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/eachOfLimit.js b/node_modules/async/eachOfLimit.js deleted file mode 100644 index 30a13299edeb7915be190add3b92724ff5f58376..0000000000000000000000000000000000000000 --- a/node_modules/async/eachOfLimit.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachOfLimit; - -var _eachOfLimit2 = require('./internal/eachOfLimit'); - -var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/eachOfSeries.js b/node_modules/async/eachOfSeries.js deleted file mode 100644 index 9dfd711340c176a909d828b657be9722ef2d2056..0000000000000000000000000000000000000000 --- a/node_modules/async/eachOfSeries.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. - * - * @name eachOfSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachOfLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/eachSeries.js b/node_modules/async/eachSeries.js deleted file mode 100644 index 55c78405ea8d87b6d85a4952ffb92a80b69bfcc7..0000000000000000000000000000000000000000 --- a/node_modules/async/eachSeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _eachLimit = require('./eachLimit'); - -var _eachLimit2 = _interopRequireDefault(_eachLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/ensureAsync.js b/node_modules/async/ensureAsync.js deleted file mode 100644 index 1f57aecdef5533559c28acce37d6fa5e561eaa16..0000000000000000000000000000000000000000 --- a/node_modules/async/ensureAsync.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = ensureAsync; - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./internal/wrapAsync'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * 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. ES2017 `async` functions are returned as-is -- they are immune - * to Zalgo's corrupting influences, as they always resolve on a later tick. - * - * @name ensureAsync - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - an async function, one that expects a node-style - * callback as its last argument. - * @returns {AsyncFunction} Returns a wrapped function with the exact same call - * signature as the function passed in. - * @example - * - * 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); - */ -function ensureAsync(fn) { - if ((0, _wrapAsync.isAsync)(fn)) return fn; - return (0, _initialParams2.default)(function (args, callback) { - var sync = true; - args.push(function () { - var innerArgs = arguments; - if (sync) { - (0, _setImmediate2.default)(function () { - callback.apply(null, innerArgs); - }); - } else { - callback.apply(null, innerArgs); - } - }); - fn.apply(this, args); - sync = false; - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/every.js b/node_modules/async/every.js deleted file mode 100644 index d0565b0454595ea7935f319cb882de0e97670423..0000000000000000000000000000000000000000 --- a/node_modules/async/every.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _notId = require('./internal/notId'); - -var _notId2 = _interopRequireDefault(_notId); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/everyLimit.js b/node_modules/async/everyLimit.js deleted file mode 100644 index a1a759a2b2eb0e6bedd3bbf7cc0c7ce0b3e7adcf..0000000000000000000000000000000000000000 --- a/node_modules/async/everyLimit.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _notId = require('./internal/notId'); - -var _notId2 = _interopRequireDefault(_notId); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/everySeries.js b/node_modules/async/everySeries.js deleted file mode 100644 index 23bfebb59f519fcff02e58aa4b8afd03122a4e05..0000000000000000000000000000000000000000 --- a/node_modules/async/everySeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _everyLimit = require('./everyLimit'); - -var _everyLimit2 = _interopRequireDefault(_everyLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -exports.default = (0, _doLimit2.default)(_everyLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/filter.js b/node_modules/async/filter.js deleted file mode 100644 index 54772d562fb5b60f29ee65fe2010b93624ef6390..0000000000000000000000000000000000000000 --- a/node_modules/async/filter.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filter = require('./internal/filter'); - -var _filter2 = _interopRequireDefault(_filter); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files - * }); - */ -exports.default = (0, _doParallel2.default)(_filter2.default); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/filterLimit.js b/node_modules/async/filterLimit.js deleted file mode 100644 index 06216f785fcf6d5503cd8dd07332680e4ec753a0..0000000000000000000000000000000000000000 --- a/node_modules/async/filterLimit.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filter = require('./internal/filter'); - -var _filter2 = _interopRequireDefault(_filter); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -exports.default = (0, _doParallelLimit2.default)(_filter2.default); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/filterSeries.js b/node_modules/async/filterSeries.js deleted file mode 100644 index e48d966cbc979a9305db1d6c6f9ca05756f020f2..0000000000000000000000000000000000000000 --- a/node_modules/async/filterSeries.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filterLimit = require('./filterLimit'); - -var _filterLimit2 = _interopRequireDefault(_filterLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - */ -exports.default = (0, _doLimit2.default)(_filterLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/find.js b/node_modules/async/find.js deleted file mode 100644 index db467835859db77d6651d85a35198aed8ff8655a..0000000000000000000000000000000000000000 --- a/node_modules/async/find.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _findGetResult = require('./internal/findGetResult'); - -var _findGetResult2 = _interopRequireDefault(_findGetResult); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. - - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @example - * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // result now equals the first file in the list that exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/findLimit.js b/node_modules/async/findLimit.js deleted file mode 100644 index 6bf656022254284851e735cce8608881cfb13d9a..0000000000000000000000000000000000000000 --- a/node_modules/async/findLimit.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _findGetResult = require('./internal/findGetResult'); - -var _findGetResult2 = _interopRequireDefault(_findGetResult); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/findSeries.js b/node_modules/async/findSeries.js deleted file mode 100644 index 6fe16c956514c0677ac142187bed2aa551ae4959..0000000000000000000000000000000000000000 --- a/node_modules/async/findSeries.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _detectLimit = require('./detectLimit'); - -var _detectLimit2 = _interopRequireDefault(_detectLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -exports.default = (0, _doLimit2.default)(_detectLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/foldl.js b/node_modules/async/foldl.js deleted file mode 100644 index 3fb8019e42a1f488e4707af8bfeac8dca676a0bf..0000000000000000000000000000000000000000 --- a/node_modules/async/foldl.js +++ /dev/null @@ -1,78 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reduce; - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Reduces `coll` into a single value using an async `iteratee` 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. - * - * @name reduce - * @static - * @memberOf module:Collections - * @method - * @alias inject - * @alias foldl - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - * @example - * - * 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 - * }); - */ -function reduce(coll, memo, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _eachOfSeries2.default)(coll, function (x, i, callback) { - _iteratee(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/foldr.js b/node_modules/async/foldr.js deleted file mode 100644 index 3d17d328ae7fc4f1f2e65e46e17d5f3338fda069..0000000000000000000000000000000000000000 --- a/node_modules/async/foldr.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reduceRight; - -var _reduce = require('./reduce'); - -var _reduce2 = _interopRequireDefault(_reduce); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - */ -function reduceRight(array, memo, iteratee, callback) { - var reversed = (0, _slice2.default)(array).reverse(); - (0, _reduce2.default)(reversed, memo, iteratee, callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/forEach.js b/node_modules/async/forEach.js deleted file mode 100644 index 4b20af33db56195ba5c5ae088d965dad6d76e940..0000000000000000000000000000000000000000 --- a/node_modules/async/forEach.js +++ /dev/null @@ -1,82 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _withoutIndex = require('./internal/withoutIndex'); - -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` 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 `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // 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 - * }); - * - * // 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'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/forEachLimit.js b/node_modules/async/forEachLimit.js deleted file mode 100644 index fff721bce0f9fe87274aae90b3859b0814e02581..0000000000000000000000000000000000000000 --- a/node_modules/async/forEachLimit.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; - -var _eachOfLimit = require('./internal/eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _withoutIndex = require('./internal/withoutIndex'); - -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/forEachOf.js b/node_modules/async/forEachOf.js deleted file mode 100644 index 055b9bde104f1c288b16742090728ac3da4df7d4..0000000000000000000000000000000000000000 --- a/node_modules/async/forEachOf.js +++ /dev/null @@ -1,111 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll, iteratee, callback) { - var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); -}; - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _breakLoop = require('./internal/breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if (++completed === length || value === _breakLoop2.default) { - callback(null); - } - } - - for (; index < length; index++) { - iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); - } -} - -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); - -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * 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); - * }); - */ -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/forEachOfLimit.js b/node_modules/async/forEachOfLimit.js deleted file mode 100644 index 30a13299edeb7915be190add3b92724ff5f58376..0000000000000000000000000000000000000000 --- a/node_modules/async/forEachOfLimit.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachOfLimit; - -var _eachOfLimit2 = require('./internal/eachOfLimit'); - -var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/forEachOfSeries.js b/node_modules/async/forEachOfSeries.js deleted file mode 100644 index 9dfd711340c176a909d828b657be9722ef2d2056..0000000000000000000000000000000000000000 --- a/node_modules/async/forEachOfSeries.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. - * - * @name eachOfSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachOfLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/forEachSeries.js b/node_modules/async/forEachSeries.js deleted file mode 100644 index 55c78405ea8d87b6d85a4952ffb92a80b69bfcc7..0000000000000000000000000000000000000000 --- a/node_modules/async/forEachSeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _eachLimit = require('./eachLimit'); - -var _eachLimit2 = _interopRequireDefault(_eachLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/forever.js b/node_modules/async/forever.js deleted file mode 100644 index 6c7b8a4cd8cf2b5c4ff019a2219758df37093472..0000000000000000000000000000000000000000 --- a/node_modules/async/forever.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = forever; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _ensureAsync = require('./ensureAsync'); - -var _ensureAsync2 = _interopRequireDefault(_ensureAsync); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * 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. - * - * @name forever - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} fn - an async function to call repeatedly. - * Invoked with (next). - * @param {Function} [errback] - when `fn` passes an error to it's callback, - * this function will be called, and execution stops. Invoked with (err). - * @example - * - * 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. - * } - * ); - */ -function forever(fn, errback) { - var done = (0, _onlyOnce2.default)(errback || _noop2.default); - var task = (0, _wrapAsync2.default)((0, _ensureAsync2.default)(fn)); - - function next(err) { - if (err) return done(err); - task(next); - } - next(); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/groupBy.js b/node_modules/async/groupBy.js deleted file mode 100644 index 755cba764b91231c1dfc2c0f19261e250ecad30f..0000000000000000000000000000000000000000 --- a/node_modules/async/groupBy.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _groupByLimit = require('./groupByLimit'); - -var _groupByLimit2 = _interopRequireDefault(_groupByLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns a new object, where each value corresponds to an array of items, from - * `coll`, that returned the corresponding key. That is, the keys of the object - * correspond to the values passed to the `iteratee` callback. - * - * Note: Since this function applies the `iteratee` to each item in parallel, - * there is no guarantee that the `iteratee` functions will complete in order. - * However, the values for each key in the `result` will be in the same order as - * the original `coll`. For Objects, the values will roughly be in the order of - * the original Objects' keys (but this can vary across JavaScript engines). - * - * @name groupBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @example - * - * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { - * db.findById(userId, function(err, user) { - * if (err) return callback(err); - * return callback(null, user.age); - * }); - * }, function(err, result) { - * // result is object containing the userIds grouped by age - * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; - * }); - */ -exports.default = (0, _doLimit2.default)(_groupByLimit2.default, Infinity); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/groupByLimit.js b/node_modules/async/groupByLimit.js deleted file mode 100644 index fec13f865e1360221a9966ecf9c1fd2dcda1eef2..0000000000000000000000000000000000000000 --- a/node_modules/async/groupByLimit.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll, limit, iteratee, callback) { - callback = callback || _noop2.default; - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _mapLimit2.default)(coll, limit, function (val, callback) { - _iteratee(val, function (err, key) { - if (err) return callback(err); - return callback(null, { key: key, val: val }); - }); - }, function (err, mapResults) { - var result = {}; - // from MDN, handle object having an `hasOwnProperty` prop - var hasOwnProperty = Object.prototype.hasOwnProperty; - - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - var key = mapResults[i].key; - var val = mapResults[i].val; - - if (hasOwnProperty.call(result, key)) { - result[key].push(val); - } else { - result[key] = [val]; - } - } - } - - return callback(err, result); - }); -}; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _mapLimit = require('./mapLimit'); - -var _mapLimit2 = _interopRequireDefault(_mapLimit); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -; -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. - * - * @name groupByLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/groupBySeries.js b/node_modules/async/groupBySeries.js deleted file mode 100644 index b94805e359ebc5a72bb80547702f7d7a3be14b97..0000000000000000000000000000000000000000 --- a/node_modules/async/groupBySeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _groupByLimit = require('./groupByLimit'); - -var _groupByLimit2 = _interopRequireDefault(_groupByLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. - * - * @name groupBySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -exports.default = (0, _doLimit2.default)(_groupByLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/index.js b/node_modules/async/index.js deleted file mode 100644 index c39d8d8ec03eb7ec2ba68407446716f898ff77f8..0000000000000000000000000000000000000000 --- a/node_modules/async/index.js +++ /dev/null @@ -1,582 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.wrapSync = exports.selectSeries = exports.selectLimit = exports.select = exports.foldr = exports.foldl = exports.inject = exports.forEachOfLimit = exports.forEachOfSeries = exports.forEachOf = exports.forEachLimit = exports.forEachSeries = exports.forEach = exports.findSeries = exports.findLimit = exports.find = exports.anySeries = exports.anyLimit = exports.any = exports.allSeries = exports.allLimit = exports.all = exports.whilst = exports.waterfall = exports.until = exports.unmemoize = exports.tryEach = exports.transform = exports.timesSeries = exports.timesLimit = exports.times = exports.timeout = exports.sortBy = exports.someSeries = exports.someLimit = exports.some = exports.setImmediate = exports.series = exports.seq = exports.retryable = exports.retry = exports.rejectSeries = exports.rejectLimit = exports.reject = exports.reflectAll = exports.reflect = exports.reduceRight = exports.reduce = exports.race = exports.queue = exports.priorityQueue = exports.parallelLimit = exports.parallel = exports.nextTick = exports.memoize = exports.mapValuesSeries = exports.mapValuesLimit = exports.mapValues = exports.mapSeries = exports.mapLimit = exports.map = exports.log = exports.groupBySeries = exports.groupByLimit = exports.groupBy = exports.forever = exports.filterSeries = exports.filterLimit = exports.filter = exports.everySeries = exports.everyLimit = exports.every = exports.ensureAsync = exports.eachSeries = exports.eachOfSeries = exports.eachOfLimit = exports.eachOf = exports.eachLimit = exports.each = exports.during = exports.doWhilst = exports.doUntil = exports.doDuring = exports.dir = exports.detectSeries = exports.detectLimit = exports.detect = exports.constant = exports.concatSeries = exports.concatLimit = exports.concat = exports.compose = exports.cargo = exports.autoInject = exports.auto = exports.asyncify = exports.applyEachSeries = exports.applyEach = exports.apply = undefined; - -var _apply = require('./apply'); - -var _apply2 = _interopRequireDefault(_apply); - -var _applyEach = require('./applyEach'); - -var _applyEach2 = _interopRequireDefault(_applyEach); - -var _applyEachSeries = require('./applyEachSeries'); - -var _applyEachSeries2 = _interopRequireDefault(_applyEachSeries); - -var _asyncify = require('./asyncify'); - -var _asyncify2 = _interopRequireDefault(_asyncify); - -var _auto = require('./auto'); - -var _auto2 = _interopRequireDefault(_auto); - -var _autoInject = require('./autoInject'); - -var _autoInject2 = _interopRequireDefault(_autoInject); - -var _cargo = require('./cargo'); - -var _cargo2 = _interopRequireDefault(_cargo); - -var _compose = require('./compose'); - -var _compose2 = _interopRequireDefault(_compose); - -var _concat = require('./concat'); - -var _concat2 = _interopRequireDefault(_concat); - -var _concatLimit = require('./concatLimit'); - -var _concatLimit2 = _interopRequireDefault(_concatLimit); - -var _concatSeries = require('./concatSeries'); - -var _concatSeries2 = _interopRequireDefault(_concatSeries); - -var _constant = require('./constant'); - -var _constant2 = _interopRequireDefault(_constant); - -var _detect = require('./detect'); - -var _detect2 = _interopRequireDefault(_detect); - -var _detectLimit = require('./detectLimit'); - -var _detectLimit2 = _interopRequireDefault(_detectLimit); - -var _detectSeries = require('./detectSeries'); - -var _detectSeries2 = _interopRequireDefault(_detectSeries); - -var _dir = require('./dir'); - -var _dir2 = _interopRequireDefault(_dir); - -var _doDuring = require('./doDuring'); - -var _doDuring2 = _interopRequireDefault(_doDuring); - -var _doUntil = require('./doUntil'); - -var _doUntil2 = _interopRequireDefault(_doUntil); - -var _doWhilst = require('./doWhilst'); - -var _doWhilst2 = _interopRequireDefault(_doWhilst); - -var _during = require('./during'); - -var _during2 = _interopRequireDefault(_during); - -var _each = require('./each'); - -var _each2 = _interopRequireDefault(_each); - -var _eachLimit = require('./eachLimit'); - -var _eachLimit2 = _interopRequireDefault(_eachLimit); - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -var _eachSeries = require('./eachSeries'); - -var _eachSeries2 = _interopRequireDefault(_eachSeries); - -var _ensureAsync = require('./ensureAsync'); - -var _ensureAsync2 = _interopRequireDefault(_ensureAsync); - -var _every = require('./every'); - -var _every2 = _interopRequireDefault(_every); - -var _everyLimit = require('./everyLimit'); - -var _everyLimit2 = _interopRequireDefault(_everyLimit); - -var _everySeries = require('./everySeries'); - -var _everySeries2 = _interopRequireDefault(_everySeries); - -var _filter = require('./filter'); - -var _filter2 = _interopRequireDefault(_filter); - -var _filterLimit = require('./filterLimit'); - -var _filterLimit2 = _interopRequireDefault(_filterLimit); - -var _filterSeries = require('./filterSeries'); - -var _filterSeries2 = _interopRequireDefault(_filterSeries); - -var _forever = require('./forever'); - -var _forever2 = _interopRequireDefault(_forever); - -var _groupBy = require('./groupBy'); - -var _groupBy2 = _interopRequireDefault(_groupBy); - -var _groupByLimit = require('./groupByLimit'); - -var _groupByLimit2 = _interopRequireDefault(_groupByLimit); - -var _groupBySeries = require('./groupBySeries'); - -var _groupBySeries2 = _interopRequireDefault(_groupBySeries); - -var _log = require('./log'); - -var _log2 = _interopRequireDefault(_log); - -var _map = require('./map'); - -var _map2 = _interopRequireDefault(_map); - -var _mapLimit = require('./mapLimit'); - -var _mapLimit2 = _interopRequireDefault(_mapLimit); - -var _mapSeries = require('./mapSeries'); - -var _mapSeries2 = _interopRequireDefault(_mapSeries); - -var _mapValues = require('./mapValues'); - -var _mapValues2 = _interopRequireDefault(_mapValues); - -var _mapValuesLimit = require('./mapValuesLimit'); - -var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); - -var _mapValuesSeries = require('./mapValuesSeries'); - -var _mapValuesSeries2 = _interopRequireDefault(_mapValuesSeries); - -var _memoize = require('./memoize'); - -var _memoize2 = _interopRequireDefault(_memoize); - -var _nextTick = require('./nextTick'); - -var _nextTick2 = _interopRequireDefault(_nextTick); - -var _parallel = require('./parallel'); - -var _parallel2 = _interopRequireDefault(_parallel); - -var _parallelLimit = require('./parallelLimit'); - -var _parallelLimit2 = _interopRequireDefault(_parallelLimit); - -var _priorityQueue = require('./priorityQueue'); - -var _priorityQueue2 = _interopRequireDefault(_priorityQueue); - -var _queue = require('./queue'); - -var _queue2 = _interopRequireDefault(_queue); - -var _race = require('./race'); - -var _race2 = _interopRequireDefault(_race); - -var _reduce = require('./reduce'); - -var _reduce2 = _interopRequireDefault(_reduce); - -var _reduceRight = require('./reduceRight'); - -var _reduceRight2 = _interopRequireDefault(_reduceRight); - -var _reflect = require('./reflect'); - -var _reflect2 = _interopRequireDefault(_reflect); - -var _reflectAll = require('./reflectAll'); - -var _reflectAll2 = _interopRequireDefault(_reflectAll); - -var _reject = require('./reject'); - -var _reject2 = _interopRequireDefault(_reject); - -var _rejectLimit = require('./rejectLimit'); - -var _rejectLimit2 = _interopRequireDefault(_rejectLimit); - -var _rejectSeries = require('./rejectSeries'); - -var _rejectSeries2 = _interopRequireDefault(_rejectSeries); - -var _retry = require('./retry'); - -var _retry2 = _interopRequireDefault(_retry); - -var _retryable = require('./retryable'); - -var _retryable2 = _interopRequireDefault(_retryable); - -var _seq = require('./seq'); - -var _seq2 = _interopRequireDefault(_seq); - -var _series = require('./series'); - -var _series2 = _interopRequireDefault(_series); - -var _setImmediate = require('./setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _some = require('./some'); - -var _some2 = _interopRequireDefault(_some); - -var _someLimit = require('./someLimit'); - -var _someLimit2 = _interopRequireDefault(_someLimit); - -var _someSeries = require('./someSeries'); - -var _someSeries2 = _interopRequireDefault(_someSeries); - -var _sortBy = require('./sortBy'); - -var _sortBy2 = _interopRequireDefault(_sortBy); - -var _timeout = require('./timeout'); - -var _timeout2 = _interopRequireDefault(_timeout); - -var _times = require('./times'); - -var _times2 = _interopRequireDefault(_times); - -var _timesLimit = require('./timesLimit'); - -var _timesLimit2 = _interopRequireDefault(_timesLimit); - -var _timesSeries = require('./timesSeries'); - -var _timesSeries2 = _interopRequireDefault(_timesSeries); - -var _transform = require('./transform'); - -var _transform2 = _interopRequireDefault(_transform); - -var _tryEach = require('./tryEach'); - -var _tryEach2 = _interopRequireDefault(_tryEach); - -var _unmemoize = require('./unmemoize'); - -var _unmemoize2 = _interopRequireDefault(_unmemoize); - -var _until = require('./until'); - -var _until2 = _interopRequireDefault(_until); - -var _waterfall = require('./waterfall'); - -var _waterfall2 = _interopRequireDefault(_waterfall); - -var _whilst = require('./whilst'); - -var _whilst2 = _interopRequireDefault(_whilst); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = { - apply: _apply2.default, - applyEach: _applyEach2.default, - applyEachSeries: _applyEachSeries2.default, - asyncify: _asyncify2.default, - auto: _auto2.default, - autoInject: _autoInject2.default, - cargo: _cargo2.default, - compose: _compose2.default, - concat: _concat2.default, - concatLimit: _concatLimit2.default, - concatSeries: _concatSeries2.default, - constant: _constant2.default, - detect: _detect2.default, - detectLimit: _detectLimit2.default, - detectSeries: _detectSeries2.default, - dir: _dir2.default, - doDuring: _doDuring2.default, - doUntil: _doUntil2.default, - doWhilst: _doWhilst2.default, - during: _during2.default, - each: _each2.default, - eachLimit: _eachLimit2.default, - eachOf: _eachOf2.default, - eachOfLimit: _eachOfLimit2.default, - eachOfSeries: _eachOfSeries2.default, - eachSeries: _eachSeries2.default, - ensureAsync: _ensureAsync2.default, - every: _every2.default, - everyLimit: _everyLimit2.default, - everySeries: _everySeries2.default, - filter: _filter2.default, - filterLimit: _filterLimit2.default, - filterSeries: _filterSeries2.default, - forever: _forever2.default, - groupBy: _groupBy2.default, - groupByLimit: _groupByLimit2.default, - groupBySeries: _groupBySeries2.default, - log: _log2.default, - map: _map2.default, - mapLimit: _mapLimit2.default, - mapSeries: _mapSeries2.default, - mapValues: _mapValues2.default, - mapValuesLimit: _mapValuesLimit2.default, - mapValuesSeries: _mapValuesSeries2.default, - memoize: _memoize2.default, - nextTick: _nextTick2.default, - parallel: _parallel2.default, - parallelLimit: _parallelLimit2.default, - priorityQueue: _priorityQueue2.default, - queue: _queue2.default, - race: _race2.default, - reduce: _reduce2.default, - reduceRight: _reduceRight2.default, - reflect: _reflect2.default, - reflectAll: _reflectAll2.default, - reject: _reject2.default, - rejectLimit: _rejectLimit2.default, - rejectSeries: _rejectSeries2.default, - retry: _retry2.default, - retryable: _retryable2.default, - seq: _seq2.default, - series: _series2.default, - setImmediate: _setImmediate2.default, - some: _some2.default, - someLimit: _someLimit2.default, - someSeries: _someSeries2.default, - sortBy: _sortBy2.default, - timeout: _timeout2.default, - times: _times2.default, - timesLimit: _timesLimit2.default, - timesSeries: _timesSeries2.default, - transform: _transform2.default, - tryEach: _tryEach2.default, - unmemoize: _unmemoize2.default, - until: _until2.default, - waterfall: _waterfall2.default, - whilst: _whilst2.default, - - // aliases - all: _every2.default, - allLimit: _everyLimit2.default, - allSeries: _everySeries2.default, - any: _some2.default, - anyLimit: _someLimit2.default, - anySeries: _someSeries2.default, - find: _detect2.default, - findLimit: _detectLimit2.default, - findSeries: _detectSeries2.default, - forEach: _each2.default, - forEachSeries: _eachSeries2.default, - forEachLimit: _eachLimit2.default, - forEachOf: _eachOf2.default, - forEachOfSeries: _eachOfSeries2.default, - forEachOfLimit: _eachOfLimit2.default, - inject: _reduce2.default, - foldl: _reduce2.default, - foldr: _reduceRight2.default, - select: _filter2.default, - selectLimit: _filterLimit2.default, - selectSeries: _filterSeries2.default, - wrapSync: _asyncify2.default -}; /** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. - * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) - * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. - * - * @typedef {Function} AsyncFunction - * @static - */ - -/** - * 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 --save async`, it can also be used directly in the browser. - * @module async - * @see AsyncFunction - */ - -/** - * A collection of `async` functions for manipulating collections, such as - * arrays and objects. - * @module Collections - */ - -/** - * A collection of `async` functions for controlling the flow through a script. - * @module ControlFlow - */ - -/** - * A collection of `async` utility functions. - * @module Utils - */ - -exports.apply = _apply2.default; -exports.applyEach = _applyEach2.default; -exports.applyEachSeries = _applyEachSeries2.default; -exports.asyncify = _asyncify2.default; -exports.auto = _auto2.default; -exports.autoInject = _autoInject2.default; -exports.cargo = _cargo2.default; -exports.compose = _compose2.default; -exports.concat = _concat2.default; -exports.concatLimit = _concatLimit2.default; -exports.concatSeries = _concatSeries2.default; -exports.constant = _constant2.default; -exports.detect = _detect2.default; -exports.detectLimit = _detectLimit2.default; -exports.detectSeries = _detectSeries2.default; -exports.dir = _dir2.default; -exports.doDuring = _doDuring2.default; -exports.doUntil = _doUntil2.default; -exports.doWhilst = _doWhilst2.default; -exports.during = _during2.default; -exports.each = _each2.default; -exports.eachLimit = _eachLimit2.default; -exports.eachOf = _eachOf2.default; -exports.eachOfLimit = _eachOfLimit2.default; -exports.eachOfSeries = _eachOfSeries2.default; -exports.eachSeries = _eachSeries2.default; -exports.ensureAsync = _ensureAsync2.default; -exports.every = _every2.default; -exports.everyLimit = _everyLimit2.default; -exports.everySeries = _everySeries2.default; -exports.filter = _filter2.default; -exports.filterLimit = _filterLimit2.default; -exports.filterSeries = _filterSeries2.default; -exports.forever = _forever2.default; -exports.groupBy = _groupBy2.default; -exports.groupByLimit = _groupByLimit2.default; -exports.groupBySeries = _groupBySeries2.default; -exports.log = _log2.default; -exports.map = _map2.default; -exports.mapLimit = _mapLimit2.default; -exports.mapSeries = _mapSeries2.default; -exports.mapValues = _mapValues2.default; -exports.mapValuesLimit = _mapValuesLimit2.default; -exports.mapValuesSeries = _mapValuesSeries2.default; -exports.memoize = _memoize2.default; -exports.nextTick = _nextTick2.default; -exports.parallel = _parallel2.default; -exports.parallelLimit = _parallelLimit2.default; -exports.priorityQueue = _priorityQueue2.default; -exports.queue = _queue2.default; -exports.race = _race2.default; -exports.reduce = _reduce2.default; -exports.reduceRight = _reduceRight2.default; -exports.reflect = _reflect2.default; -exports.reflectAll = _reflectAll2.default; -exports.reject = _reject2.default; -exports.rejectLimit = _rejectLimit2.default; -exports.rejectSeries = _rejectSeries2.default; -exports.retry = _retry2.default; -exports.retryable = _retryable2.default; -exports.seq = _seq2.default; -exports.series = _series2.default; -exports.setImmediate = _setImmediate2.default; -exports.some = _some2.default; -exports.someLimit = _someLimit2.default; -exports.someSeries = _someSeries2.default; -exports.sortBy = _sortBy2.default; -exports.timeout = _timeout2.default; -exports.times = _times2.default; -exports.timesLimit = _timesLimit2.default; -exports.timesSeries = _timesSeries2.default; -exports.transform = _transform2.default; -exports.tryEach = _tryEach2.default; -exports.unmemoize = _unmemoize2.default; -exports.until = _until2.default; -exports.waterfall = _waterfall2.default; -exports.whilst = _whilst2.default; -exports.all = _every2.default; -exports.allLimit = _everyLimit2.default; -exports.allSeries = _everySeries2.default; -exports.any = _some2.default; -exports.anyLimit = _someLimit2.default; -exports.anySeries = _someSeries2.default; -exports.find = _detect2.default; -exports.findLimit = _detectLimit2.default; -exports.findSeries = _detectSeries2.default; -exports.forEach = _each2.default; -exports.forEachSeries = _eachSeries2.default; -exports.forEachLimit = _eachLimit2.default; -exports.forEachOf = _eachOf2.default; -exports.forEachOfSeries = _eachOfSeries2.default; -exports.forEachOfLimit = _eachOfLimit2.default; -exports.inject = _reduce2.default; -exports.foldl = _reduce2.default; -exports.foldr = _reduceRight2.default; -exports.select = _filter2.default; -exports.selectLimit = _filterLimit2.default; -exports.selectSeries = _filterSeries2.default; -exports.wrapSync = _asyncify2.default; \ No newline at end of file diff --git a/node_modules/async/inject.js b/node_modules/async/inject.js deleted file mode 100644 index 3fb8019e42a1f488e4707af8bfeac8dca676a0bf..0000000000000000000000000000000000000000 --- a/node_modules/async/inject.js +++ /dev/null @@ -1,78 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reduce; - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Reduces `coll` into a single value using an async `iteratee` 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. - * - * @name reduce - * @static - * @memberOf module:Collections - * @method - * @alias inject - * @alias foldl - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - * @example - * - * 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 - * }); - */ -function reduce(coll, memo, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _eachOfSeries2.default)(coll, function (x, i, callback) { - _iteratee(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/DoublyLinkedList.js b/node_modules/async/internal/DoublyLinkedList.js deleted file mode 100644 index 7e71728e287967bf87ade4fd36cb5de2483626cb..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/DoublyLinkedList.js +++ /dev/null @@ -1,88 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = DLL; -// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation -// used for queues. This implementation assumes that the node provided by the user can be modified -// to adjust the next and last properties. We implement only the minimal functionality -// for queue support. -function DLL() { - this.head = this.tail = null; - this.length = 0; -} - -function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; -} - -DLL.prototype.removeLink = function (node) { - if (node.prev) node.prev.next = node.next;else this.head = node.next; - if (node.next) node.next.prev = node.prev;else this.tail = node.prev; - - node.prev = node.next = null; - this.length -= 1; - return node; -}; - -DLL.prototype.empty = function () { - while (this.head) this.shift(); - return this; -}; - -DLL.prototype.insertAfter = function (node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode;else this.tail = newNode; - node.next = newNode; - this.length += 1; -}; - -DLL.prototype.insertBefore = function (node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode;else this.head = newNode; - node.prev = newNode; - this.length += 1; -}; - -DLL.prototype.unshift = function (node) { - if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); -}; - -DLL.prototype.push = function (node) { - if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); -}; - -DLL.prototype.shift = function () { - return this.head && this.removeLink(this.head); -}; - -DLL.prototype.pop = function () { - return this.tail && this.removeLink(this.tail); -}; - -DLL.prototype.toArray = function () { - var arr = Array(this.length); - var curr = this.head; - for (var idx = 0; idx < this.length; idx++) { - arr[idx] = curr.data; - curr = curr.next; - } - return arr; -}; - -DLL.prototype.remove = function (testFn) { - var curr = this.head; - while (!!curr) { - var next = curr.next; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; -}; -module.exports = exports["default"]; \ No newline at end of file diff --git a/node_modules/async/internal/applyEach.js b/node_modules/async/internal/applyEach.js deleted file mode 100644 index 322e03ca74b5900c2b23c5b7eaa27f55180229c6..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/applyEach.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = applyEach; - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _initialParams = require('./initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function applyEach(eachfn) { - return function (fns /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - var go = (0, _initialParams2.default)(function (args, callback) { - var that = this; - return eachfn(fns, function (fn, cb) { - (0, _wrapAsync2.default)(fn).apply(that, args.concat(cb)); - }, callback); - }); - if (args.length) { - return go.apply(this, args); - } else { - return go; - } - }; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/breakLoop.js b/node_modules/async/internal/breakLoop.js deleted file mode 100644 index 106505824b1d9196c83a067b0e7e112adeba68aa..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/breakLoop.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -exports.default = {}; -module.exports = exports["default"]; \ No newline at end of file diff --git a/node_modules/async/internal/consoleFunc.js b/node_modules/async/internal/consoleFunc.js deleted file mode 100644 index 603f48e8ec4b65e76b35e316a15c5e474bbc303b..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/consoleFunc.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = consoleFunc; - -var _arrayEach = require('lodash/_arrayEach'); - -var _arrayEach2 = _interopRequireDefault(_arrayEach); - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function consoleFunc(name) { - return function (fn /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - args.push(function (err /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - if (typeof console === 'object') { - if (err) { - if (console.error) { - console.error(err); - } - } else if (console[name]) { - (0, _arrayEach2.default)(args, function (x) { - console[name](x); - }); - } - } - }); - (0, _wrapAsync2.default)(fn).apply(null, args); - }; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/createTester.js b/node_modules/async/internal/createTester.js deleted file mode 100644 index ce96e8b4e6ac1a4e436fc8d32ff33088ff063f0d..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/createTester.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _createTester; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _breakLoop = require('./breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _createTester(check, getResult) { - return function (eachfn, arr, iteratee, cb) { - cb = cb || _noop2.default; - var testPassed = false; - var testResult; - eachfn(arr, function (value, _, callback) { - iteratee(value, function (err, result) { - if (err) { - callback(err); - } else if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - callback(null, _breakLoop2.default); - } else { - callback(); - } - }); - }, function (err) { - if (err) { - cb(err); - } else { - cb(null, testPassed ? testResult : getResult(false)); - } - }); - }; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/doLimit.js b/node_modules/async/internal/doLimit.js deleted file mode 100644 index 963c6088f422abc396e6bb7bca416e9d75ede0c0..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/doLimit.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doLimit; -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} -module.exports = exports["default"]; \ No newline at end of file diff --git a/node_modules/async/internal/doParallel.js b/node_modules/async/internal/doParallel.js deleted file mode 100644 index bb402077cdc4949040ecd73b897448a943b6582c..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/doParallel.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doParallel; - -var _eachOf = require('../eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function doParallel(fn) { - return function (obj, iteratee, callback) { - return fn(_eachOf2.default, obj, (0, _wrapAsync2.default)(iteratee), callback); - }; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/doParallelLimit.js b/node_modules/async/internal/doParallelLimit.js deleted file mode 100644 index a7e963d53e6e4c8f030533b5e008b2b1614cc16a..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/doParallelLimit.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doParallelLimit; - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function doParallelLimit(fn) { - return function (obj, limit, iteratee, callback) { - return fn((0, _eachOfLimit2.default)(limit), obj, (0, _wrapAsync2.default)(iteratee), callback); - }; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/eachOfLimit.js b/node_modules/async/internal/eachOfLimit.js deleted file mode 100644 index 6f6fe55d06124cb4b818d3b6e78afb8cfd0b9cee..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/eachOfLimit.js +++ /dev/null @@ -1,74 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _eachOfLimit; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./once'); - -var _once2 = _interopRequireDefault(_once); - -var _iterator = require('./iterator'); - -var _iterator2 = _interopRequireDefault(_iterator); - -var _onlyOnce = require('./onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _breakLoop = require('./breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = (0, _iterator2.default)(obj); - var done = false; - var running = 0; - var looping = false; - - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } else if (value === _breakLoop2.default || done && running <= 0) { - done = true; - return callback(null); - } else if (!looping) { - replenish(); - } - } - - function replenish() { - looping = true; - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); - } - looping = false; - } - - replenish(); - }; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/filter.js b/node_modules/async/internal/filter.js deleted file mode 100644 index 74f3986357f4972a480f5af5f116f30da514db0f..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/filter.js +++ /dev/null @@ -1,75 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _filter; - -var _arrayMap = require('lodash/_arrayMap'); - -var _arrayMap2 = _interopRequireDefault(_arrayMap); - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _baseProperty = require('lodash/_baseProperty'); - -var _baseProperty2 = _interopRequireDefault(_baseProperty); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, function (x, index, callback) { - iteratee(x, function (err, v) { - truthValues[index] = !!v; - callback(err); - }); - }, function (err) { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); -} - -function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, function (x, index, callback) { - iteratee(x, function (err, v) { - if (err) { - callback(err); - } else { - if (v) { - results.push({ index: index, value: x }); - } - callback(); - } - }); - }, function (err) { - if (err) { - callback(err); - } else { - callback(null, (0, _arrayMap2.default)(results.sort(function (a, b) { - return a.index - b.index; - }), (0, _baseProperty2.default)('value'))); - } - }); -} - -function _filter(eachfn, coll, iteratee, callback) { - var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback || _noop2.default); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/findGetResult.js b/node_modules/async/internal/findGetResult.js deleted file mode 100644 index f8d3fe0637e11f9c4bfa1f7beb8065fc2e402e77..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/findGetResult.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _findGetResult; -function _findGetResult(v, x) { - return x; -} -module.exports = exports["default"]; \ No newline at end of file diff --git a/node_modules/async/internal/getIterator.js b/node_modules/async/internal/getIterator.js deleted file mode 100644 index 3eadd24d00807720104b712468a48acc33879cf2..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/getIterator.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); -}; - -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; - -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/initialParams.js b/node_modules/async/internal/initialParams.js deleted file mode 100644 index df02cb1f12de855764278cd764679aa43714085d..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/initialParams.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (fn) { - return function () /*...args, callback*/{ - var args = (0, _slice2.default)(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; -}; - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/iterator.js b/node_modules/async/internal/iterator.js deleted file mode 100644 index 3d32942ff4b5f07b57216b31f05616a9435cbc9a..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/iterator.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = iterator; - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _getIterator = require('./getIterator'); - -var _getIterator2 = _interopRequireDefault(_getIterator); - -var _keys = require('lodash/keys'); - -var _keys2 = _interopRequireDefault(_keys); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? { value: coll[i], key: i } : null; - }; -} - -function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) return null; - i++; - return { value: item.value, key: i }; - }; -} - -function createObjectIterator(obj) { - var okeys = (0, _keys2.default)(obj); - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - return i < len ? { value: obj[key], key: key } : null; - }; -} - -function iterator(coll) { - if ((0, _isArrayLike2.default)(coll)) { - return createArrayIterator(coll); - } - - var iterator = (0, _getIterator2.default)(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/map.js b/node_modules/async/internal/map.js deleted file mode 100644 index f4f2aa59444368e9204fef845b8821e7c9b70e7a..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/map.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _asyncMap; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _asyncMap(eachfn, arr, iteratee, callback) { - callback = callback || _noop2.default; - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = (0, _wrapAsync2.default)(iteratee); - - eachfn(arr, function (value, _, callback) { - var index = counter++; - _iteratee(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/notId.js b/node_modules/async/internal/notId.js deleted file mode 100644 index 0106c92c0436b3ca4ced4f094b3b9f1ff19b7db3..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/notId.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = notId; -function notId(v) { - return !v; -} -module.exports = exports["default"]; \ No newline at end of file diff --git a/node_modules/async/internal/once.js b/node_modules/async/internal/once.js deleted file mode 100644 index f0c379f7572694bad5ed6b562f677becda4982be..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/once.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = once; -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} -module.exports = exports["default"]; \ No newline at end of file diff --git a/node_modules/async/internal/onlyOnce.js b/node_modules/async/internal/onlyOnce.js deleted file mode 100644 index f2e3001dc3f8eda598f0c09447dff2ec5a3cd15c..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/onlyOnce.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = onlyOnce; -function onlyOnce(fn) { - return function () { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} -module.exports = exports["default"]; \ No newline at end of file diff --git a/node_modules/async/internal/parallel.js b/node_modules/async/internal/parallel.js deleted file mode 100644 index c97293b6c0414d1ed389462712fd1e700dd641e1..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/parallel.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _parallel; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _parallel(eachfn, tasks, callback) { - callback = callback || _noop2.default; - var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; - - eachfn(tasks, function (task, key, callback) { - (0, _wrapAsync2.default)(task)(function (err, result) { - if (arguments.length > 2) { - result = (0, _slice2.default)(arguments, 1); - } - results[key] = result; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/queue.js b/node_modules/async/internal/queue.js deleted file mode 100644 index 19534a749f43622b351be34e357862aabcbdd04b..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/queue.js +++ /dev/null @@ -1,204 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = queue; - -var _baseIndexOf = require('lodash/_baseIndexOf'); - -var _baseIndexOf2 = _interopRequireDefault(_baseIndexOf); - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _onlyOnce = require('./onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _setImmediate = require('./setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _DoublyLinkedList = require('./DoublyLinkedList'); - -var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } else if (concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - - var _worker = (0, _wrapAsync2.default)(worker); - var numRunning = 0; - var workersList = []; - - var processingScheduled = false; - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!(0, _isArray2.default)(data)) { - data = [data]; - } - if (data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - return (0, _setImmediate2.default)(function () { - q.drain(); - }); - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - callback: callback || _noop2.default - }; - - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - } - - if (!processingScheduled) { - processingScheduled = true; - (0, _setImmediate2.default)(function () { - processingScheduled = false; - q.process(); - }); - } - } - - function _next(tasks) { - return function (err) { - numRunning -= 1; - - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; - - var index = (0, _baseIndexOf2.default)(workersList, task, 0); - if (index === 0) { - workersList.shift(); - } else if (index > 0) { - workersList.splice(index, 1); - } - - task.callback.apply(task, arguments); - - if (err != null) { - q.error(err, task.data); - } - } - - if (numRunning <= q.concurrency - q.buffer) { - q.unsaturated(); - } - - if (q.idle()) { - q.drain(); - } - q.process(); - }; - } - - var isProcessing = false; - var q = { - _tasks: new _DoublyLinkedList2.default(), - concurrency: concurrency, - payload: payload, - saturated: _noop2.default, - unsaturated: _noop2.default, - buffer: concurrency / 4, - empty: _noop2.default, - drain: _noop2.default, - error: _noop2.default, - started: false, - paused: false, - push: function (data, callback) { - _insert(data, false, callback); - }, - kill: function () { - q.drain = _noop2.default; - q._tasks.empty(); - }, - unshift: function (data, callback) { - _insert(data, true, callback); - }, - remove: function (testFn) { - q._tasks.remove(testFn); - }, - process: function () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while (!q.paused && numRunning < q.concurrency && q._tasks.length) { - var tasks = [], - data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } - - numRunning += 1; - - if (q._tasks.length === 0) { - q.empty(); - } - - if (numRunning === q.concurrency) { - q.saturated(); - } - - var cb = (0, _onlyOnce2.default)(_next(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length: function () { - return q._tasks.length; - }, - running: function () { - return numRunning; - }, - workersList: function () { - return workersList; - }, - idle: function () { - return q._tasks.length + numRunning === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { - return; - } - q.paused = false; - (0, _setImmediate2.default)(q.process); - } - }; - return q; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/reject.js b/node_modules/async/internal/reject.js deleted file mode 100644 index 5dbfcfb151af59fbeabf70de1d199d2e53120abc..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/reject.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reject; - -var _filter = require('./filter'); - -var _filter2 = _interopRequireDefault(_filter); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function reject(eachfn, arr, iteratee, callback) { - (0, _filter2.default)(eachfn, arr, function (value, cb) { - iteratee(value, function (err, v) { - cb(err, !v); - }); - }, callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/internal/setImmediate.js b/node_modules/async/internal/setImmediate.js deleted file mode 100644 index 3545f2bcdab140a9f299d7fab3398f3cf2af983f..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/setImmediate.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.hasNextTick = exports.hasSetImmediate = undefined; -exports.fallback = fallback; -exports.wrap = wrap; - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - -function fallback(fn) { - setTimeout(fn, 0); -} - -function wrap(defer) { - return function (fn /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; -} - -var _defer; - -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; -} - -exports.default = wrap(_defer); \ No newline at end of file diff --git a/node_modules/async/internal/slice.js b/node_modules/async/internal/slice.js deleted file mode 100644 index 56f10c03e2a55dc07ba39d577617029cde611d44..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/slice.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = slice; -function slice(arrayLike, start) { - start = start | 0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for (var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; - } - return newArr; -} -module.exports = exports["default"]; \ No newline at end of file diff --git a/node_modules/async/internal/withoutIndex.js b/node_modules/async/internal/withoutIndex.js deleted file mode 100644 index 2bd35796a6b8a964ea3fcac8630a4e2f4464d872..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/withoutIndex.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _withoutIndex; -function _withoutIndex(iteratee) { - return function (value, index, callback) { - return iteratee(value, callback); - }; -} -module.exports = exports["default"]; \ No newline at end of file diff --git a/node_modules/async/internal/wrapAsync.js b/node_modules/async/internal/wrapAsync.js deleted file mode 100644 index bc6c96668ca0a77214e4a9590221f75cd6219f78..0000000000000000000000000000000000000000 --- a/node_modules/async/internal/wrapAsync.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isAsync = undefined; - -var _asyncify = require('../asyncify'); - -var _asyncify2 = _interopRequireDefault(_asyncify); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var supportsSymbol = typeof Symbol === 'function'; - -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} - -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; -} - -exports.default = wrapAsync; -exports.isAsync = isAsync; \ No newline at end of file diff --git a/node_modules/async/log.js b/node_modules/async/log.js deleted file mode 100644 index c643867bcfb4948f26c160ddbba299aed4c53c00..0000000000000000000000000000000000000000 --- a/node_modules/async/log.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _consoleFunc = require('./internal/consoleFunc'); - -var _consoleFunc2 = _interopRequireDefault(_consoleFunc); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * 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. - * - * @name log - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, 'hello ' + name); - * }, 1000); - * }; - * - * // in the node repl - * node> async.log(hello, 'world'); - * 'hello world' - */ -exports.default = (0, _consoleFunc2.default)('log'); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/map.js b/node_modules/async/map.js deleted file mode 100644 index 67c9cda930d40a8a7b405f4907605ae36c69d577..0000000000000000000000000000000000000000 --- a/node_modules/async/map.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _map = require('./internal/map'); - -var _map2 = _interopRequireDefault(_map); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callback - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` 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 `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @example - * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file - * }); - */ -exports.default = (0, _doParallel2.default)(_map2.default); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/mapLimit.js b/node_modules/async/mapLimit.js deleted file mode 100644 index c8b60d8dcf24b2723b111281a531aa809d84ffd4..0000000000000000000000000000000000000000 --- a/node_modules/async/mapLimit.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _map = require('./internal/map'); - -var _map2 = _interopRequireDefault(_map); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -exports.default = (0, _doParallelLimit2.default)(_map2.default); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/mapSeries.js b/node_modules/async/mapSeries.js deleted file mode 100644 index 61b42d01b7aa59e6d8236f30582451d3dfd658a9..0000000000000000000000000000000000000000 --- a/node_modules/async/mapSeries.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _mapLimit = require('./mapLimit'); - -var _mapLimit2 = _interopRequireDefault(_mapLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. - * - * @name mapSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -exports.default = (0, _doLimit2.default)(_mapLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/mapValues.js b/node_modules/async/mapValues.js deleted file mode 100644 index 3d838ca1ec7ae734791464f29efa4898d0aff5c3..0000000000000000000000000000000000000000 --- a/node_modules/async/mapValues.js +++ /dev/null @@ -1,63 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _mapValuesLimit = require('./mapValuesLimit'); - -var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. - * - * Produces a new Object by mapping each value of `obj` through the `iteratee` - * function. The `iteratee` is called each `value` and `key` from `obj` and a - * callback for when it has finished processing. Each of these callbacks takes - * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` - * passes an error to its callback, the main `callback` (for the `mapValues` - * function) is immediately called with the error. - * - * Note, the order of the keys in the result is not guaranteed. The keys will - * be roughly in the order they complete, (but this is very engine-specific) - * - * @name mapValues - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @example - * - * async.mapValues({ - * f1: 'file1', - * f2: 'file2', - * f3: 'file3' - * }, function (file, key, callback) { - * fs.stat(file, callback); - * }, function(err, result) { - * // result is now a map of stats for each file, e.g. - * // { - * // f1: [stats for file1], - * // f2: [stats for file2], - * // f3: [stats for file3] - * // } - * }); - */ - -exports.default = (0, _doLimit2.default)(_mapValuesLimit2.default, Infinity); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/mapValuesLimit.js b/node_modules/async/mapValuesLimit.js deleted file mode 100644 index 912a8b5224936306c64bc36f3473040b3eb17e01..0000000000000000000000000000000000000000 --- a/node_modules/async/mapValuesLimit.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = mapValuesLimit; - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a - * time. - * - * @name mapValuesLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -function mapValuesLimit(obj, limit, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var newObj = {}; - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _eachOfLimit2.default)(obj, limit, function (val, key, next) { - _iteratee(val, key, function (err, result) { - if (err) return next(err); - newObj[key] = result; - next(); - }); - }, function (err) { - callback(err, newObj); - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/mapValuesSeries.js b/node_modules/async/mapValuesSeries.js deleted file mode 100644 index b378c4a1ab3e4e34252961a610f4d5bf6bebf875..0000000000000000000000000000000000000000 --- a/node_modules/async/mapValuesSeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _mapValuesLimit = require('./mapValuesLimit'); - -var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. - * - * @name mapValuesSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -exports.default = (0, _doLimit2.default)(_mapValuesLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/memoize.js b/node_modules/async/memoize.js deleted file mode 100644 index 1f2b56691c454c50644f9a80227e2708c01cb45c..0000000000000000000000000000000000000000 --- a/node_modules/async/memoize.js +++ /dev/null @@ -1,101 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = memoize; - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function has(obj, key) { - return key in obj; -} - -/** - * 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`. - * - * @name memoize - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function to proxy and cache results from. - * @param {Function} 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. - * @returns {AsyncFunction} a memoized version of `fn` - * @example - * - * 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 - * }); - */ -function memoize(fn, hasher) { - var memo = Object.create(null); - var queues = Object.create(null); - hasher = hasher || _identity2.default; - var _fn = (0, _wrapAsync2.default)(fn); - var memoized = (0, _initialParams2.default)(function memoized(args, callback) { - var key = hasher.apply(null, args); - if (has(memo, key)) { - (0, _setImmediate2.default)(function () { - callback.apply(null, memo[key]); - }); - } else if (has(queues, key)) { - queues[key].push(callback); - } else { - queues[key] = [callback]; - _fn.apply(null, args.concat(function () /*args*/{ - var args = (0, _slice2.default)(arguments); - memo[key] = args; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, args); - } - })); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/nextTick.js b/node_modules/async/nextTick.js deleted file mode 100644 index 886f58ef09d4068a66867f122d5023d7db041f56..0000000000000000000000000000000000000000 --- a/node_modules/async/nextTick.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _setImmediate = require('./internal/setImmediate'); - -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `process.nextTick`. In the browser it will use `setImmediate` 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. - * - * @name nextTick - * @static - * @memberOf module:Utils - * @method - * @see [async.setImmediate]{@link module:Utils.setImmediate} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -var _defer; - -if (_setImmediate.hasNextTick) { - _defer = process.nextTick; -} else if (_setImmediate.hasSetImmediate) { - _defer = setImmediate; -} else { - _defer = _setImmediate.fallback; -} - -exports.default = (0, _setImmediate.wrap)(_defer); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/package.json b/node_modules/async/package.json deleted file mode 100644 index 32086f98c05455d6a8b559179dda500a4dd867a1..0000000000000000000000000000000000000000 --- a/node_modules/async/package.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "_from": "async@2.6.1", - "_id": "async@2.6.1", - "_inBundle": false, - "_integrity": "sha512-fNEiL2+AZt6AlAw/29Cr0UDe4sRAHCpEHh54WMz+Bb7QfNcFw4h3loofyJpLeQs4Yx7yuqu/2dLgM5hKOs6HlQ==", - "_location": "/async", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "async@2.6.1", - "name": "async", - "escapedName": "async", - "rawSpec": "2.6.1", - "saveSpec": null, - "fetchSpec": "2.6.1" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/async/-/async-2.6.1.tgz", - "_shasum": "b245a23ca71930044ec53fa46aa00a3e87c6a610", - "_spec": "async@2.6.1", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongoose", - "author": { - "name": "Caolan McMahon" - }, - "bugs": { - "url": "https://github.com/caolan/async/issues" - }, - "bundleDependencies": false, - "dependencies": { - "lodash": "^4.17.10" - }, - "deprecated": false, - "description": "Higher-order functions and common patterns for asynchronous code", - "devDependencies": { - "babel-cli": "^6.24.0", - "babel-core": "^6.26.3", - "babel-plugin-add-module-exports": "^0.2.1", - "babel-plugin-istanbul": "^2.0.1", - "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", - "babel-preset-es2015": "^6.3.13", - "babel-preset-es2017": "^6.22.0", - "babelify": "^8.0.0", - "benchmark": "^2.1.1", - "bluebird": "^3.4.6", - "browserify": "^16.2.2", - "chai": "^4.1.2", - "cheerio": "^0.22.0", - "coveralls": "^3.0.1", - "es6-promise": "^2.3.0", - "eslint": "^2.13.1", - "fs-extra": "^0.26.7", - "gh-pages-deploy": "^0.5.0", - "jsdoc": "^3.4.0", - "karma": "^2.0.2", - "karma-browserify": "^5.2.0", - "karma-firefox-launcher": "^1.1.0", - "karma-mocha": "^1.2.0", - "karma-mocha-reporter": "^2.2.0", - "mocha": "^5.2.0", - "native-promise-only": "^0.8.0-a", - "nyc": "^11.8.0", - "rimraf": "^2.5.0", - "rollup": "^0.36.3", - "rollup-plugin-node-resolve": "^2.0.0", - "rollup-plugin-npm": "^2.0.0", - "rsvp": "^3.0.18", - "semver": "^5.5.0", - "uglify-js": "~2.7.3", - "yargs": "^11.0.0" - }, - "gh-pages-deploy": { - "staticpath": "docs" - }, - "homepage": "https://caolan.github.io/async/", - "keywords": [ - "async", - "callback", - "module", - "utility" - ], - "license": "MIT", - "main": "dist/async.js", - "name": "async", - "nyc": { - "exclude": [ - "mocha_test" - ] - }, - "repository": { - "type": "git", - "url": "git+https://github.com/caolan/async.git" - }, - "scripts": { - "coverage": "nyc npm run mocha-node-test -- --grep @nycinvalid --invert", - "coveralls": "npm run coverage && nyc report --reporter=text-lcov | coveralls", - "jsdoc": "jsdoc -c ./support/jsdoc/jsdoc.json && node support/jsdoc/jsdoc-fix-html.js", - "lint": "eslint lib/ mocha_test/ perf/memory.js perf/suites.js perf/benchmark.js support/build/ support/*.js karma.conf.js", - "mocha-browser-test": "karma start", - "mocha-node-test": "mocha mocha_test/ --compilers js:babel-core/register", - "mocha-test": "npm run mocha-node-test && npm run mocha-browser-test", - "test": "npm run lint && npm run mocha-node-test" - }, - "version": "2.6.1" -} diff --git a/node_modules/async/parallel.js b/node_modules/async/parallel.js deleted file mode 100644 index da28a4def6cfc61b7dfc42087253d0ba2ed11e7e..0000000000000000000000000000000000000000 --- a/node_modules/async/parallel.js +++ /dev/null @@ -1,90 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = parallelLimit; - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _parallel = require('./internal/parallel'); - -var _parallel2 = _interopRequireDefault(_parallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Run the `tasks` collection 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. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * 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 {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * - * @example - * 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} - * }); - */ -function parallelLimit(tasks, callback) { - (0, _parallel2.default)(_eachOf2.default, tasks, callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/parallelLimit.js b/node_modules/async/parallelLimit.js deleted file mode 100644 index a026526f4d0855b239f7fa9dc0e73b0fdd921df8..0000000000000000000000000000000000000000 --- a/node_modules/async/parallelLimit.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = parallelLimit; - -var _eachOfLimit = require('./internal/eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _parallel = require('./internal/parallel'); - -var _parallel2 = _interopRequireDefault(_parallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a - * time. - * - * @name parallelLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.parallel]{@link module:ControlFlow.parallel} - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - */ -function parallelLimit(tasks, limit, callback) { - (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/priorityQueue.js b/node_modules/async/priorityQueue.js deleted file mode 100644 index 3a5f023e5c87ff6d722b1b28938b92dcb28e68d6..0000000000000000000000000000000000000000 --- a/node_modules/async/priorityQueue.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (worker, concurrency) { - // Start with a normal queue - var q = (0, _queue2.default)(worker, concurrency); - - // Override push to accept second parameter representing priority - q.push = function (data, priority, callback) { - if (callback == null) callback = _noop2.default; - if (typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!(0, _isArray2.default)(data)) { - data = [data]; - } - if (data.length === 0) { - // call drain immediately if there are no tasks - return (0, _setImmediate2.default)(function () { - q.drain(); - }); - } - - priority = priority || 0; - var nextNode = q._tasks.head; - while (nextNode && priority >= nextNode.priority) { - nextNode = nextNode.next; - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - priority: priority, - callback: callback - }; - - if (nextNode) { - q._tasks.insertBefore(nextNode, item); - } else { - q._tasks.push(item); - } - } - (0, _setImmediate2.default)(q.process); - }; - - // Remove unshift function - delete q.unshift; - - return q; -}; - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _setImmediate = require('./setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _queue = require('./queue'); - -var _queue2 = _interopRequireDefault(_queue); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} 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. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. 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. - */ \ No newline at end of file diff --git a/node_modules/async/queue.js b/node_modules/async/queue.js deleted file mode 100644 index 0ca8ba2bb39c1649ea28559d16372034994d5a0e..0000000000000000000000000000000000000000 --- a/node_modules/async/queue.js +++ /dev/null @@ -1,130 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (worker, concurrency) { - var _worker = (0, _wrapAsync2.default)(worker); - return (0, _queue2.default)(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); -}; - -var _queue = require('./internal/queue'); - -var _queue2 = _interopRequireDefault(_queue); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * A queue of tasks for the worker function to complete. - * @typedef {Object} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} 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. - * @property {Function} push - 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. Invoke with `queue.push(task, [callback])`, - * @property {Function} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a callback that is called when the number of - * running workers hits the `concurrency` limit, and further tasks will be - * queued. - * @property {Function} unsaturated - a callback that is called when the number - * of running workers is less than the `concurrency` & `buffer` limits, and - * further tasks will not be queued. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - a callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} error - a callback that is called when a task errors. - * Has the signature `function(error, task)`. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - */ - -/** - * 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. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - 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. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // 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'); - * }); - */ \ No newline at end of file diff --git a/node_modules/async/race.js b/node_modules/async/race.js deleted file mode 100644 index 6713c74af85d81b76fe6c0d3ce160d3012ac4cb9..0000000000000000000000000000000000000000 --- a/node_modules/async/race.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = race; - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Runs the `tasks` array of functions in parallel, without waiting until the - * previous function has completed. Once any of the `tasks` complete or pass an - * error to its callback, the main `callback` is immediately called. It's - * equivalent to `Promise.race()`. - * - * @name race - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} - * to run. Each function can complete with an optional `result` value. - * @param {Function} callback - A callback to run once any of the functions have - * completed. This function gets an error or result from the first function that - * completed. Invoked with (err, result). - * @returns undefined - * @example - * - * async.race([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // main callback - * function(err, result) { - * // the result will be equal to 'two' as it finishes earlier - * }); - */ -function race(tasks, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (!(0, _isArray2.default)(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); - if (!tasks.length) return callback(); - for (var i = 0, l = tasks.length; i < l; i++) { - (0, _wrapAsync2.default)(tasks[i])(callback); - } -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/reduce.js b/node_modules/async/reduce.js deleted file mode 100644 index 3fb8019e42a1f488e4707af8bfeac8dca676a0bf..0000000000000000000000000000000000000000 --- a/node_modules/async/reduce.js +++ /dev/null @@ -1,78 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reduce; - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Reduces `coll` into a single value using an async `iteratee` 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. - * - * @name reduce - * @static - * @memberOf module:Collections - * @method - * @alias inject - * @alias foldl - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - * @example - * - * 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 - * }); - */ -function reduce(coll, memo, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _eachOfSeries2.default)(coll, function (x, i, callback) { - _iteratee(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/reduceRight.js b/node_modules/async/reduceRight.js deleted file mode 100644 index 3d17d328ae7fc4f1f2e65e46e17d5f3338fda069..0000000000000000000000000000000000000000 --- a/node_modules/async/reduceRight.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reduceRight; - -var _reduce = require('./reduce'); - -var _reduce2 = _interopRequireDefault(_reduce); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - */ -function reduceRight(array, memo, iteratee, callback) { - var reversed = (0, _slice2.default)(array).reverse(); - (0, _reduce2.default)(reversed, memo, iteratee, callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/reflect.js b/node_modules/async/reflect.js deleted file mode 100644 index 098ba8650d0e148a3358f44abbf36bf7a998071d..0000000000000000000000000000000000000000 --- a/node_modules/async/reflect.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reflect; - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Wraps the async function in another function that always completes with a - * result object, even when it errors. - * - * The result object has either the property `error` or `value`. - * - * @name reflect - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function you want to wrap - * @returns {Function} - A function that always passes null to it's callback as - * the error. The second argument to the callback will be an `object` with - * either an `error` or a `value` property. - * @example - * - * async.parallel([ - * async.reflect(function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }), - * async.reflect(function(callback) { - * // do some more stuff but error ... - * callback('bad stuff happened'); - * }), - * async.reflect(function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * }) - * ], - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = 'bad stuff happened' - * // results[2].value = 'two' - * }); - */ -function reflect(fn) { - var _fn = (0, _wrapAsync2.default)(fn); - return (0, _initialParams2.default)(function reflectOn(args, reflectCallback) { - args.push(function callback(error, cbArg) { - if (error) { - reflectCallback(null, { error: error }); - } else { - var value; - if (arguments.length <= 2) { - value = cbArg; - } else { - value = (0, _slice2.default)(arguments, 1); - } - reflectCallback(null, { value: value }); - } - }); - - return _fn.apply(this, args); - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/reflectAll.js b/node_modules/async/reflectAll.js deleted file mode 100644 index 966e83de570837effbbada8f3053b237af1f4105..0000000000000000000000000000000000000000 --- a/node_modules/async/reflectAll.js +++ /dev/null @@ -1,105 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reflectAll; - -var _reflect = require('./reflect'); - -var _reflect2 = _interopRequireDefault(_reflect); - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _arrayMap2 = require('lodash/_arrayMap'); - -var _arrayMap3 = _interopRequireDefault(_arrayMap2); - -var _baseForOwn = require('lodash/_baseForOwn'); - -var _baseForOwn2 = _interopRequireDefault(_baseForOwn); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * A helper function that wraps an array or an object of functions with `reflect`. - * - * @name reflectAll - * @static - * @memberOf module:Utils - * @method - * @see [async.reflect]{@link module:Utils.reflect} - * @category Util - * @param {Array|Object|Iterable} tasks - The collection of - * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. - * @returns {Array} Returns an array of async functions, each wrapped in - * `async.reflect` - * @example - * - * let tasks = [ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * // do some more stuff but error ... - * callback(new Error('bad stuff happened')); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = Error('bad stuff happened') - * // results[2].value = 'two' - * }); - * - * // an example using an object instead of an array - * let tasks = { - * one: function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * two: function(callback) { - * callback('two'); - * }, - * three: function(callback) { - * setTimeout(function() { - * callback(null, 'three'); - * }, 100); - * } - * }; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results.one.value = 'one' - * // results.two.error = 'two' - * // results.three.value = 'three' - * }); - */ -function reflectAll(tasks) { - var results; - if ((0, _isArray2.default)(tasks)) { - results = (0, _arrayMap3.default)(tasks, _reflect2.default); - } else { - results = {}; - (0, _baseForOwn2.default)(tasks, function (task, key) { - results[key] = _reflect2.default.call(this, task); - }); - } - return results; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/reject.js b/node_modules/async/reject.js deleted file mode 100644 index 53802b531e6845606f9ff03003f914d49087d2f1..0000000000000000000000000000000000000000 --- a/node_modules/async/reject.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _reject = require('./internal/reject'); - -var _reject2 = _interopRequireDefault(_reject); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); - * }); - */ -exports.default = (0, _doParallel2.default)(_reject2.default); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/rejectLimit.js b/node_modules/async/rejectLimit.js deleted file mode 100644 index 74bba7fbadacca0f1259865fd274f7a7093f1982..0000000000000000000000000000000000000000 --- a/node_modules/async/rejectLimit.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _reject = require('./internal/reject'); - -var _reject2 = _interopRequireDefault(_reject); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a - * time. - * - * @name rejectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -exports.default = (0, _doParallelLimit2.default)(_reject2.default); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/rejectSeries.js b/node_modules/async/rejectSeries.js deleted file mode 100644 index f905588f413443fe5ef7f410d6bff19d7b57f640..0000000000000000000000000000000000000000 --- a/node_modules/async/rejectSeries.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _rejectLimit = require('./rejectLimit'); - -var _rejectLimit2 = _interopRequireDefault(_rejectLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. - * - * @name rejectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -exports.default = (0, _doLimit2.default)(_rejectLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/retry.js b/node_modules/async/retry.js deleted file mode 100644 index 6a1aa1ec8c34838183d538a06abe5b1df444b911..0000000000000000000000000000000000000000 --- a/node_modules/async/retry.js +++ /dev/null @@ -1,156 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = retry; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _constant = require('lodash/constant'); - -var _constant2 = _interopRequireDefault(_constant); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * 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. - * - * @name retry - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @see [async.retryable]{@link module:ControlFlow.retryable} - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an - * object with `times` and `interval` or a number. - * * `times` - The number of attempts to make before giving up. The default - * is `5`. - * * `interval` - The time to wait between retries, in milliseconds. The - * default is `0`. The interval may also be specified as a function of the - * retry count (see example). - * * `errorFilter` - An optional synchronous function that is invoked on - * erroneous result. If it returns `true` the retry attempts will continue; - * if the function returns `false` the retry flow is aborted with the current - * attempt's error and result being returned to the final callback. - * Invoked with (err). - * * If `opts` is a number, the number specifies the number of times to retry, - * with the default interval of `0`. - * @param {AsyncFunction} task - An async function to retry. - * Invoked with (callback). - * @param {Function} [callback] - 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`. Invoked - * with (err, results). - * - * @example - * - * // The `retry` function can be used as a stand-alone control flow by passing - * // a callback, as shown below: - * - * // try calling apiMethod 3 times - * async.retry(3, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 3 times, waiting 200 ms between each retry - * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 10 times with exponential backoff - * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) - * async.retry({ - * times: 10, - * interval: function(retryCount) { - * return 50 * Math.pow(2, retryCount); - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod the default 5 times no delay between each retry - * async.retry(apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod only when error condition satisfies, all other - * // errors will abort the retry control flow and return to final callback - * async.retry({ - * errorFilter: function(err) { - * return err.message === 'Temporary error'; // only retry on a specific error - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // to retry individual methods that are not as reliable within other - * // control flow functions, use the `retryable` wrapper: - * async.auto({ - * users: api.getUsers.bind(api), - * payments: async.retryable(3, api.getPayments.bind(api)) - * }, function(err, results) { - * // do something with the results - * }); - * - */ -function retry(opts, task, callback) { - var DEFAULT_TIMES = 5; - var DEFAULT_INTERVAL = 0; - - var options = { - times: DEFAULT_TIMES, - intervalFunc: (0, _constant2.default)(DEFAULT_INTERVAL) - }; - - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; - - acc.intervalFunc = typeof t.interval === 'function' ? t.interval : (0, _constant2.default)(+t.interval || DEFAULT_INTERVAL); - - acc.errorFilter = t.errorFilter; - } else if (typeof t === 'number' || typeof t === 'string') { - acc.times = +t || DEFAULT_TIMES; - } else { - throw new Error("Invalid arguments for async.retry"); - } - } - - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || _noop2.default; - task = opts; - } else { - parseTimes(options, opts); - callback = callback || _noop2.default; - } - - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } - - var _task = (0, _wrapAsync2.default)(task); - - var attempt = 1; - function retryAttempt() { - _task(function (err) { - if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { - setTimeout(retryAttempt, options.intervalFunc(attempt)); - } else { - callback.apply(null, arguments); - } - }); - } - - retryAttempt(); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/retryable.js b/node_modules/async/retryable.js deleted file mode 100644 index 002bfb0f0defe25aea750970a5faaac0d449dd93..0000000000000000000000000000000000000000 --- a/node_modules/async/retryable.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (opts, task) { - if (!task) { - task = opts; - opts = null; - } - var _task = (0, _wrapAsync2.default)(task); - return (0, _initialParams2.default)(function (args, callback) { - function taskFn(cb) { - _task.apply(null, args.concat(cb)); - } - - if (opts) (0, _retry2.default)(opts, taskFn, callback);else (0, _retry2.default)(taskFn, callback); - }); -}; - -var _retry = require('./retry'); - -var _retry2 = _interopRequireDefault(_retry); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method - * wraps a task and makes it retryable, rather than immediately calling it - * with retries. - * - * @name retryable - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.retry]{@link module:ControlFlow.retry} - * @category Control Flow - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional - * options, exactly the same as from `retry` - * @param {AsyncFunction} task - the asynchronous function to wrap. - * This function will be passed any arguments passed to the returned wrapper. - * Invoked with (...args, callback). - * @returns {AsyncFunction} The wrapped function, which when invoked, will - * retry on an error, based on the parameters specified in `opts`. - * This function will accept the same parameters as `task`. - * @example - * - * async.auto({ - * dep1: async.retryable(3, getFromFlakyService), - * process: ["dep1", async.retryable(3, function (results, cb) { - * maybeProcessData(results.dep1, cb); - * })] - * }, callback); - */ \ No newline at end of file diff --git a/node_modules/async/select.js b/node_modules/async/select.js deleted file mode 100644 index 54772d562fb5b60f29ee65fe2010b93624ef6390..0000000000000000000000000000000000000000 --- a/node_modules/async/select.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filter = require('./internal/filter'); - -var _filter2 = _interopRequireDefault(_filter); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files - * }); - */ -exports.default = (0, _doParallel2.default)(_filter2.default); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/selectLimit.js b/node_modules/async/selectLimit.js deleted file mode 100644 index 06216f785fcf6d5503cd8dd07332680e4ec753a0..0000000000000000000000000000000000000000 --- a/node_modules/async/selectLimit.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filter = require('./internal/filter'); - -var _filter2 = _interopRequireDefault(_filter); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -exports.default = (0, _doParallelLimit2.default)(_filter2.default); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/selectSeries.js b/node_modules/async/selectSeries.js deleted file mode 100644 index e48d966cbc979a9305db1d6c6f9ca05756f020f2..0000000000000000000000000000000000000000 --- a/node_modules/async/selectSeries.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filterLimit = require('./filterLimit'); - -var _filterLimit2 = _interopRequireDefault(_filterLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - */ -exports.default = (0, _doLimit2.default)(_filterLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/seq.js b/node_modules/async/seq.js deleted file mode 100644 index ff86ef92dbc7de4ae897a8d4f76422d7625353be..0000000000000000000000000000000000000000 --- a/node_modules/async/seq.js +++ /dev/null @@ -1,91 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = seq; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _reduce = require('./reduce'); - -var _reduce2 = _interopRequireDefault(_reduce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -var _arrayMap = require('lodash/_arrayMap'); - -var _arrayMap2 = _interopRequireDefault(_arrayMap); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * 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]{@link module:ControlFlow.compose} with the arguments reversed. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name seq - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.compose]{@link module:ControlFlow.compose} - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} a function that composes the `functions` in order - * @example - * - * // 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 }); - * } - * }); - * }); - */ -function seq() /*...functions*/{ - var _functions = (0, _arrayMap2.default)(arguments, _wrapAsync2.default); - return function () /*...args*/{ - var args = (0, _slice2.default)(arguments); - var that = this; - - var cb = args[args.length - 1]; - if (typeof cb == 'function') { - args.pop(); - } else { - cb = _noop2.default; - } - - (0, _reduce2.default)(_functions, args, function (newargs, fn, cb) { - fn.apply(that, newargs.concat(function (err /*, ...nextargs*/) { - var nextargs = (0, _slice2.default)(arguments, 1); - cb(err, nextargs); - })); - }, function (err, results) { - cb.apply(that, [err].concat(results)); - }); - }; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/series.js b/node_modules/async/series.js deleted file mode 100644 index e8c292816db1a1cf1fa4fa2991430e414f609396..0000000000000000000000000000000000000000 --- a/node_modules/async/series.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = series; - -var _parallel = require('./internal/parallel'); - -var _parallel2 = _interopRequireDefault(_parallel); - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Run the functions in the `tasks` collection 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 {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](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. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - 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. Invoked - * with (err, result). - * @example - * 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'] - * }); - * - * 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} - * }); - */ -function series(tasks, callback) { - (0, _parallel2.default)(_eachOfSeries2.default, tasks, callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/setImmediate.js b/node_modules/async/setImmediate.js deleted file mode 100644 index e52f7c54bb820842e13351cddd4ca0bf4c405e82..0000000000000000000000000000000000000000 --- a/node_modules/async/setImmediate.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `setImmediate`. In the browser it will use `setImmediate` 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. - * - * @name setImmediate - * @static - * @memberOf module:Utils - * @method - * @see [async.nextTick]{@link module:Utils.nextTick} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -exports.default = _setImmediate2.default; -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/some.js b/node_modules/async/some.js deleted file mode 100644 index a8e70f714a89a615bdd14d6ea7bf538fa37b1700..0000000000000000000000000000000000000000 --- a/node_modules/async/some.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(Boolean, _identity2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/someLimit.js b/node_modules/async/someLimit.js deleted file mode 100644 index 24ca3f4919d0eab978e8b72b4eb42abd2250df55..0000000000000000000000000000000000000000 --- a/node_modules/async/someLimit.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(Boolean, _identity2.default)); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/someSeries.js b/node_modules/async/someSeries.js deleted file mode 100644 index dc24ed254cec1e8b32c7756efd4b3cb4229d24b7..0000000000000000000000000000000000000000 --- a/node_modules/async/someSeries.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _someLimit = require('./someLimit'); - -var _someLimit2 = _interopRequireDefault(_someLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -exports.default = (0, _doLimit2.default)(_someLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/sortBy.js b/node_modules/async/sortBy.js deleted file mode 100644 index ee5e93dc0944bc24649ed06fe6ab4a2e31f55fb2..0000000000000000000000000000000000000000 --- a/node_modules/async/sortBy.js +++ /dev/null @@ -1,91 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = sortBy; - -var _arrayMap = require('lodash/_arrayMap'); - -var _arrayMap2 = _interopRequireDefault(_arrayMap); - -var _baseProperty = require('lodash/_baseProperty'); - -var _baseProperty2 = _interopRequireDefault(_baseProperty); - -var _map = require('./map'); - -var _map2 = _interopRequireDefault(_map); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Sorts a list by the results of running each `coll` value through an async - * `iteratee`. - * - * @name sortBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a value to use as the sort criteria as - * its `result`. - * Invoked with (item, callback). - * @param {Function} callback - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is the items - * from the original `coll` sorted by the values returned by the `iteratee` - * calls. Invoked with (err, results). - * @example - * - * 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 - * }); - * - * // By modifying the callback parameter the - * // sorting order can be influenced: - * - * // 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 - * }); - */ -function sortBy(coll, iteratee, callback) { - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _map2.default)(coll, function (x, callback) { - _iteratee(x, function (err, criteria) { - if (err) return callback(err); - callback(null, { value: x, criteria: criteria }); - }); - }, function (err, results) { - if (err) return callback(err); - callback(null, (0, _arrayMap2.default)(results.sort(comparator), (0, _baseProperty2.default)('value'))); - }); - - function comparator(left, right) { - var a = left.criteria, - b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - } -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/timeout.js b/node_modules/async/timeout.js deleted file mode 100644 index b5cb505eb5d08c1837d4c1805842448a6619bf36..0000000000000000000000000000000000000000 --- a/node_modules/async/timeout.js +++ /dev/null @@ -1,89 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = timeout; - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ -function timeout(asyncFn, milliseconds, info) { - var fn = (0, _wrapAsync2.default)(asyncFn); - - return (0, _initialParams2.default)(function (args, callback) { - var timedOut = false; - var timer; - - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } - - args.push(function () { - if (!timedOut) { - callback.apply(null, arguments); - clearTimeout(timer); - } - }); - - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args); - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/times.js b/node_modules/async/times.js deleted file mode 100644 index b5ca24dff14e6bbf0e0af8472cd634a39fc61d34..0000000000000000000000000000000000000000 --- a/node_modules/async/times.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _timesLimit = require('./timesLimit'); - -var _timesLimit2 = _interopRequireDefault(_timesLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. - * - * @name times - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @example - * - * // 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 - * }); - */ -exports.default = (0, _doLimit2.default)(_timesLimit2.default, Infinity); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/timesLimit.js b/node_modules/async/timesLimit.js deleted file mode 100644 index aad84955cac3934125fa41700abcebe9693d80e6..0000000000000000000000000000000000000000 --- a/node_modules/async/timesLimit.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = timeLimit; - -var _mapLimit = require('./mapLimit'); - -var _mapLimit2 = _interopRequireDefault(_mapLimit); - -var _baseRange = require('lodash/_baseRange'); - -var _baseRange2 = _interopRequireDefault(_baseRange); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. - * - * @name timesLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - */ -function timeLimit(count, limit, iteratee, callback) { - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _mapLimit2.default)((0, _baseRange2.default)(0, count, 1), limit, _iteratee, callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/timesSeries.js b/node_modules/async/timesSeries.js deleted file mode 100644 index f187a35b2512ed63a72c5625a6c9c10d57c09ba9..0000000000000000000000000000000000000000 --- a/node_modules/async/timesSeries.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _timesLimit = require('./timesLimit'); - -var _timesLimit2 = _interopRequireDefault(_timesLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. - * - * @name timesSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - */ -exports.default = (0, _doLimit2.default)(_timesLimit2.default, 1); -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/transform.js b/node_modules/async/transform.js deleted file mode 100644 index 84ee217e828f8f8e70b63eb9368fdb543da887bd..0000000000000000000000000000000000000000 --- a/node_modules/async/transform.js +++ /dev/null @@ -1,87 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = transform; - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * A relative of `reduce`. Takes an Object or Array, and iterates over each - * element in series, each step potentially mutating an `accumulator` value. - * The type of the accumulator defaults to the type of collection passed in. - * - * @name transform - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} [accumulator] - The initial state of the transform. If omitted, - * it will default to an empty Object or Array, depending on the type of `coll` - * @param {AsyncFunction} iteratee - A function applied to each item in the - * collection that potentially modifies the accumulator. - * Invoked with (accumulator, item, key, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the transformed accumulator. - * Invoked with (err, result). - * @example - * - * async.transform([1,2,3], function(acc, item, index, callback) { - * // pointless async: - * process.nextTick(function() { - * acc.push(item * 2) - * callback(null) - * }); - * }, function(err, result) { - * // result is now equal to [2, 4, 6] - * }); - * - * @example - * - * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { - * setImmediate(function () { - * obj[key] = val * 2; - * callback(); - * }) - * }, function (err, result) { - * // result is equal to {a: 2, b: 4, c: 6} - * }) - */ -function transform(coll, accumulator, iteratee, callback) { - if (arguments.length <= 3) { - callback = iteratee; - iteratee = accumulator; - accumulator = (0, _isArray2.default)(coll) ? [] : {}; - } - callback = (0, _once2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - - (0, _eachOf2.default)(coll, function (v, k, cb) { - _iteratee(accumulator, v, k, cb); - }, function (err) { - callback(err, accumulator); - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/tryEach.js b/node_modules/async/tryEach.js deleted file mode 100644 index f4e4c97d7112cbab2ce9a699d1742e69ae0c0d5c..0000000000000000000000000000000000000000 --- a/node_modules/async/tryEach.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = tryEach; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _eachSeries = require('./eachSeries'); - -var _eachSeries2 = _interopRequireDefault(_eachSeries); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * It runs each task in series but stops whenever any of the functions were - * successful. If one of the tasks were successful, the `callback` will be - * passed the result of the successful task. If all tasks fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name tryEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection 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. - * @param {Function} [callback] - An optional callback which is called when one - * of the tasks has succeeded, or all have failed. It receives the `err` and - * `result` arguments of the last attempt at completing the `task`. Invoked with - * (err, results). - * @example - * async.tryEach([ - * function getDataFromFirstWebsite(callback) { - * // Try getting the data from the first website - * callback(err, data); - * }, - * function getDataFromSecondWebsite(callback) { - * // First website failed, - * // Try getting the data from the backup website - * callback(err, data); - * } - * ], - * // optional callback - * function(err, results) { - * Now do something with the data. - * }); - * - */ -function tryEach(tasks, callback) { - var error = null; - var result; - callback = callback || _noop2.default; - (0, _eachSeries2.default)(tasks, function (task, callback) { - (0, _wrapAsync2.default)(task)(function (err, res /*, ...args*/) { - if (arguments.length > 2) { - result = (0, _slice2.default)(arguments, 1); - } else { - result = res; - } - error = err; - callback(!err); - }); - }, function () { - callback(error, result); - }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/unmemoize.js b/node_modules/async/unmemoize.js deleted file mode 100644 index 08f9f9fb3949bc2d4b944af84e369f43f83b3644..0000000000000000000000000000000000000000 --- a/node_modules/async/unmemoize.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = unmemoize; -/** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function - */ -function unmemoize(fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; -} -module.exports = exports["default"]; \ No newline at end of file diff --git a/node_modules/async/until.js b/node_modules/async/until.js deleted file mode 100644 index 29955ab1bbc7e29ec6420c23dd73d8e6d6dea559..0000000000000000000000000000000000000000 --- a/node_modules/async/until.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = until; - -var _whilst = require('./whilst'); - -var _whilst2 = _interopRequireDefault(_whilst); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function until(test, iteratee, callback) { - (0, _whilst2.default)(function () { - return !test.apply(this, arguments); - }, iteratee, callback); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/waterfall.js b/node_modules/async/waterfall.js deleted file mode 100644 index d547d6b1e44ee9a6bc308b5281207b8255868104..0000000000000000000000000000000000000000 --- a/node_modules/async/waterfall.js +++ /dev/null @@ -1,113 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (tasks, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (!(0, _isArray2.default)(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; - - function nextTask(args) { - var task = (0, _wrapAsync2.default)(tasks[taskIndex++]); - args.push((0, _onlyOnce2.default)(next)); - task.apply(null, args); - } - - function next(err /*, ...args*/) { - if (err || taskIndex === tasks.length) { - return callback.apply(null, arguments); - } - nextTask((0, _slice2.default)(arguments, 1)); - } - - nextTask([]); -}; - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * 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. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns undefined - * @example - * - * 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' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ \ No newline at end of file diff --git a/node_modules/async/whilst.js b/node_modules/async/whilst.js deleted file mode 100644 index 9c4d8f6cab844f55a81f5bf93f227c9729707bfd..0000000000000000000000000000000000000000 --- a/node_modules/async/whilst.js +++ /dev/null @@ -1,72 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = whilst; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns undefined - * @example - * - * var count = 0; - * async.whilst( - * function() { return count < 5; }, - * function(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ -function whilst(test, iteratee, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - if (!test()) return callback(null); - var next = function (err /*, ...args*/) { - if (err) return callback(err); - if (test()) return _iteratee(next); - var args = (0, _slice2.default)(arguments, 1); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/async/wrapSync.js b/node_modules/async/wrapSync.js deleted file mode 100644 index 5e3fc91557debb47ebe5d30f10783bd6cf2d20ce..0000000000000000000000000000000000000000 --- a/node_modules/async/wrapSync.js +++ /dev/null @@ -1,110 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = asyncify; - -var _isObject = require('lodash/isObject'); - -var _isObject2 = _interopRequireDefault(_isObject); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return (0, _initialParams2.default)(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if ((0, _isObject2.default)(result) && typeof result.then === 'function') { - result.then(function (value) { - invokeCallback(callback, null, value); - }, function (err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); -} - -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - (0, _setImmediate2.default)(rethrow, e); - } -} - -function rethrow(error) { - throw error; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/sliced/LICENSE b/node_modules/bignumber.js/LICENCE similarity index 92% rename from node_modules/sliced/LICENSE rename to node_modules/bignumber.js/LICENCE index 38c529daa677faf963fc24fcd00cdb5b61f07102..d730ec5d025b2c0130ae74a02c08f6219511416e 100644 --- a/node_modules/sliced/LICENSE +++ b/node_modules/bignumber.js/LICENCE @@ -1,22 +1,23 @@ -(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. +The MIT Licence. + +Copyright (c) 2017 Michael Mclaughlin + +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/bignumber.js/README.md b/node_modules/bignumber.js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8a8bb9e8812519b7af23d413abcc8036afaf6ce6 --- /dev/null +++ b/node_modules/bignumber.js/README.md @@ -0,0 +1,415 @@ + + +A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic. + +[](https://travis-ci.org/MikeMcl/bignumber.js) + +<br /> + +## Features + + - Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal + - 8 KB minified and gzipped + - Simple API but full-featured + - Works with numbers with or without fraction digits in bases from 2 to 64 inclusive + - Replicates the `toExponential`, `toFixed`, `toPrecision` and `toString` methods of JavaScript's Number type + - Includes a `toFraction` and a correctly-rounded `squareRoot` method + - Supports cryptographically-secure pseudo-random number generation + - No dependencies + - Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only + - Comprehensive [documentation](http://mikemcl.github.io/bignumber.js/) and test set + + + +If a smaller and simpler library is required see [big.js](https://github.com/MikeMcl/big.js/). +It's less than half the size but only works with decimal numbers and only has half the methods. +It also does not allow `NaN` or `Infinity`, or have the configuration options of this library. + +See also [decimal.js](https://github.com/MikeMcl/decimal.js/), which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits. + +## Load + +The library is the single JavaScript file *bignumber.js* (or minified, *bignumber.min.js*). + +```html +<script src='relative/path/to/bignumber.js'></script> +``` + +For [Node.js](http://nodejs.org), the library is available from the [npm](https://npmjs.org/) registry + + $ npm install bignumber.js + +```javascript +var BigNumber = require('bignumber.js'); +``` + +To load with AMD loader libraries such as [requireJS](http://requirejs.org/): + +```javascript +require(['path/to/bignumber'], function(BigNumber) { + // Use BigNumber here in local scope. No global BigNumber. +}); +``` + +## Use + +*In all examples below, `var`, semicolons and `toString` calls are not shown. +If a commented-out value is in quotes it means `toString` has been called on the preceding expression.* + +The library exports a single function: `BigNumber`, the constructor of BigNumber instances. + +It accepts a value of type number *(up to 15 significant digits only)*, string or BigNumber object, + +```javascript +x = new BigNumber(123.4567) +y = new BigNumber('123456.7e-3') +z = new BigNumber(x) +x.equals(y) && y.equals(z) && x.equals(z) // true +``` + + +and a base from 2 to 64 inclusive can be specified. + +```javascript +x = new BigNumber(1011, 2) // "11" +y = new BigNumber('zz.9', 36) // "1295.25" +z = x.plus(y) // "1306.25" +``` + +A BigNumber is immutable in the sense that it is not changed by its methods. + +```javascript +0.3 - 0.1 // 0.19999999999999998 +x = new BigNumber(0.3) +x.minus(0.1) // "0.2" +x // "0.3" +``` + +The methods that return a BigNumber can be chained. + +```javascript +x.dividedBy(y).plus(z).times(9).floor() +x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').ceil() +``` + +Many method names have a shorter alias. + +```javascript +x.squareRoot().dividedBy(y).toPower(3).equals(x.sqrt().div(y).pow(3)) // true +x.cmp(y.mod(z).neg()) == 1 && x.comparedTo(y.modulo(z).negated()) == 1 // true +``` + +Like JavaScript's number type, there are `toExponential`, `toFixed` and `toPrecision` methods + +```javascript +x = new BigNumber(255.5) +x.toExponential(5) // "2.55500e+2" +x.toFixed(5) // "255.50000" +x.toPrecision(5) // "255.50" +x.toNumber() // 255.5 +``` + + and a base can be specified for `toString`. + + ```javascript + x.toString(16) // "ff.8" + ``` + +There is also a `toFormat` method which may be useful for internationalisation + +```javascript +y = new BigNumber('1234567.898765') +y.toFormat(2) // "1,234,567.90" +``` + +The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the `config` method of the `BigNumber` constructor. + +The other arithmetic operations always give the exact result. + +```javascript +BigNumber.config({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 }) + +x = new BigNumber(2); +y = new BigNumber(3); +z = x.div(y) // "0.6666666667" +z.sqrt() // "0.8164965809" +z.pow(-3) // "3.3749999995" +z.toString(2) // "0.1010101011" +z.times(z) // "0.44444444448888888889" +z.times(z).round(10) // "0.4444444445" +``` + +There is a `toFraction` method with an optional *maximum denominator* argument + +```javascript +y = new BigNumber(355) +pi = y.dividedBy(113) // "3.1415929204" +pi.toFraction() // [ "7853982301", "2500000000" ] +pi.toFraction(1000) // [ "355", "113" ] +``` + +and `isNaN` and `isFinite` methods, as `NaN` and `Infinity` are valid `BigNumber` values. + +```javascript +x = new BigNumber(NaN) // "NaN" +y = new BigNumber(Infinity) // "Infinity" +x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true +``` + +The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign. + + +```javascript +x = new BigNumber(-123.456); +x.c // [ 123, 45600000000000 ] coefficient (i.e. significand) +x.e // 2 exponent +x.s // -1 sign +``` + + +Multiple BigNumber constructors can be created, each with their own independent configuration which applies to all BigNumber's created from it. + +```javascript +// Set DECIMAL_PLACES for the original BigNumber constructor +BigNumber.config({ DECIMAL_PLACES: 10 }) + +// Create another BigNumber constructor, optionally passing in a configuration object +BN = BigNumber.another({ DECIMAL_PLACES: 5 }) + +x = new BigNumber(1) +y = new BN(1) + +x.div(3) // '0.3333333333' +y.div(3) // '0.33333' +``` + +For futher information see the [API](http://mikemcl.github.io/bignumber.js/) reference in the *doc* directory. + +## Test + +The *test* directory contains the test scripts for each method. + +The tests can be run with Node or a browser. For Node use + + $ npm test + +or + + $ node test/every-test + +To test a single method, e.g. + + $ node test/toFraction + +For the browser, see *every-test.html* and *single-test.html* in the *test/browser* directory. + +*bignumber-vs-number.html* enables some of the methods of bignumber.js to be compared with those of JavaScript's number type. + +## Versions + +Version 1.x.x of this library is still supported on the 'original' branch. The advantages of later versions are that they are considerably faster for numbers with many digits and that there are some added methods (see Change Log below). The disadvantages are more lines of code and increased code complexity, and the loss of simplicity in no longer having the coefficient of a BigNumber stored in base 10. + +## Performance + +See the [README](https://github.com/MikeMcl/bignumber.js/tree/master/perf) in the *perf* directory. + +## Build + +For Node, if [uglify-js](https://github.com/mishoo/UglifyJS2) is installed + + npm install uglify-js -g + +then + + npm run build + +will create *bignumber.min.js*. + +A source map will also be created in the root directory. + +## Feedback + +Open an issue, or email + +Michael + +<a href="mailto:M8ch88l@gmail.com">M8ch88l@gmail.com</a> + +## Licence + +MIT. + +See [LICENCE](https://github.com/MikeMcl/bignumber.js/blob/master/LICENCE). + +## Change Log + + +#### 4.1.0 +* 26/09/2017 +* Remove node 0.6 from *.travis.yml*. +* Add *bignumber.mjs*. + +#### 4.0.4 +* 03/09/2017 +* Add missing aliases to *bignumber.d.ts*. + +#### 4.0.3 +* 30/08/2017 +* Add types: *bignumber.d.ts*. + +#### 4.0.2 +* 03/05/2017 +* #120 Workaround Safari/Webkit bug. + +#### 4.0.1 +* 05/04/2017 +* #121 BigNumber.default to BigNumber['default']. + +#### 4.0.0 +* 09/01/2017 +* Replace BigNumber.isBigNumber method with isBigNumber prototype property. + +#### 3.1.2 +* 08/01/2017 +* Minor documentation edit. + +#### 3.1.1 +* 08/01/2017 +* Uncomment `isBigNumber` tests. +* Ignore dot files. + +#### 3.1.0 +* 08/01/2017 +* Add `isBigNumber` method. + +#### 3.0.2 +* 08/01/2017 +* Bugfix: Possible incorrect value of `ERRORS` after a `BigNumber.another` call (due to `parseNumeric` declaration in outer scope). + +#### 3.0.1 +* 23/11/2016 +* Apply fix for old ipads with `%` issue, see #57 and #102. +* Correct error message. + +#### 3.0.0 +* 09/11/2016 +* Remove `require('crypto')` - leave it to the user. +* Add `BigNumber.set` as `BigNumber.config` alias. +* Default `POW_PRECISION` to `0`. + +#### 2.4.0 +* 14/07/2016 +* #97 Add exports to support ES6 imports. + +#### 2.3.0 +* 07/03/2016 +* #86 Add modulus parameter to `toPower`. + +#### 2.2.0 +* 03/03/2016 +* #91 Permit larger JS integers. + +#### 2.1.4 +* 15/12/2015 +* Correct UMD. + +#### 2.1.3 +* 13/12/2015 +* Refactor re global object and crypto availability when bundling. + +#### 2.1.2 +* 10/12/2015 +* Bugfix: `window.crypto` not assigned to `crypto`. + +#### 2.1.1 +* 09/12/2015 +* Prevent code bundler from adding `crypto` shim. + +#### 2.1.0 +* 26/10/2015 +* For `valueOf` and `toJSON`, include the minus sign with negative zero. + +#### 2.0.8 +* 2/10/2015 +* Internal round function bugfix. + +#### 2.0.6 +* 31/03/2015 +* Add bower.json. Tweak division after in-depth review. + +#### 2.0.5 +* 25/03/2015 +* Amend README. Remove bitcoin address. + +#### 2.0.4 +* 25/03/2015 +* Critical bugfix #58: division. + +#### 2.0.3 +* 18/02/2015 +* Amend README. Add source map. + +#### 2.0.2 +* 18/02/2015 +* Correct links. + +#### 2.0.1 +* 18/02/2015 +* Add `max`, `min`, `precision`, `random`, `shift`, `toDigits` and `truncated` methods. +* Add the short-forms: `add`, `mul`, `sd`, `sub` and `trunc`. +* Add an `another` method to enable multiple independent constructors to be created. +* Add support for the base 2, 8 and 16 prefixes `0b`, `0o` and `0x`. +* Enable a rounding mode to be specified as a second parameter to `toExponential`, `toFixed`, `toFormat` and `toPrecision`. +* Add a `CRYPTO` configuration property so cryptographically-secure pseudo-random number generation can be specified. +* Add a `MODULO_MODE` configuration property to enable the rounding mode used by the `modulo` operation to be specified. +* Add a `POW_PRECISION` configuration property to enable the number of significant digits calculated by the power operation to be limited. +* Improve code quality. +* Improve documentation. + +#### 2.0.0 +* 29/12/2014 +* Add `dividedToIntegerBy`, `isInteger` and `toFormat` methods. +* Remove the following short-forms: `isF`, `isZ`, `toE`, `toF`, `toFr`, `toN`, `toP`, `toS`. +* Store a BigNumber's coefficient in base 1e14, rather than base 10. +* Add fast path for integers to BigNumber constructor. +* Incorporate the library into the online documentation. + +#### 1.5.0 +* 13/11/2014 +* Add `toJSON` and `decimalPlaces` methods. + +#### 1.4.1 +* 08/06/2014 +* Amend README. + +#### 1.4.0 +* 08/05/2014 +* Add `toNumber`. + +#### 1.3.0 +* 08/11/2013 +* Ensure correct rounding of `sqrt` in all, rather than almost all, cases. +* Maximum radix to 64. + +#### 1.2.1 +* 17/10/2013 +* Sign of zero when x < 0 and x + (-x) = 0. + +#### 1.2.0 +* 19/9/2013 +* Throw Error objects for stack. + +#### 1.1.1 +* 22/8/2013 +* Show original value in constructor error message. + +#### 1.1.0 +* 1/8/2013 +* Allow numbers with trailing radix point. + +#### 1.0.1 +* Bugfix: error messages with incorrect method name + +#### 1.0.0 +* 8/11/2012 +* Initial release diff --git a/node_modules/bignumber.js/bignumber.d.ts b/node_modules/bignumber.js/bignumber.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d663196dcdbf260d31bd9a78ece151e28a7e914 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.d.ts @@ -0,0 +1,1295 @@ +// Type definitions for Bignumber.js +// Project: bignumber.js +// Definitions by: Felix Becker https://github.com/felixfbecker + +export interface Format { + /** the decimal separator */ + decimalSeparator?: string; + /** the grouping separator of the integer part */ + groupSeparator?: string; + /** the primary grouping size of the integer part */ + groupSize?: number; + /** the secondary grouping size of the integer part */ + secondaryGroupSize?: number; + /** the grouping separator of the fraction part */ + fractionGroupSeparator?: string; + /** the grouping size of the fraction part */ + fractionGroupSize?: number; +} + +export interface Configuration { + + /** + * integer, `0` to `1e+9` inclusive + * + * The maximum number of decimal places of the results of operations involving division, i.e. division, square root + * and base conversion operations, and power operations with negative exponents. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BigNumber.config(5) // equivalent + * ``` + * @default 20 + */ + DECIMAL_PLACES?: number; + + /** + * The rounding mode used in the above operations and the default rounding mode of round, toExponential, toFixed, + * toFormat and toPrecision. The modes are available as enumerated properties of the BigNumber constructor. + * @default [[RoundingMode.ROUND_HALF_UP]] + */ + ROUNDING_MODE?: RoundingMode; + + /** + * - `number`: integer, magnitude `0` to `1e+9` inclusive + * - `number[]`: [ integer `-1e+9` to `0` inclusive, integer `0` to `1e+9` inclusive ] + * + * The exponent value(s) at which `toString` returns exponential notation. + * + * If a single number is assigned, the value + * is the exponent magnitude. + * + * If an array of two numbers is assigned then the first number is the negative exponent + * value at and beneath which exponential notation is used, and the second number is the positive exponent value at + * and above which the same. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which + * they begin to use exponential notation, use [-7, 20]. + * + * ```ts + * BigNumber.config({ EXPONENTIAL_AT: 2 }) + * new BigNumber(12.3) // '12.3' e is only 1 + * new BigNumber(123) // '1.23e+2' + * new BigNumber(0.123) // '0.123' e is only -1 + * new BigNumber(0.0123) // '1.23e-2' + * + * BigNumber.config({ EXPONENTIAL_AT: [-7, 20] }) + * new BigNumber(123456789) // '123456789' e is only 8 + * new BigNumber(0.000000123) // '1.23e-7' + * + * // Almost never return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 1e+9 }) + * + * // Always return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 0 }) + * ``` + * Regardless of the value of `EXPONENTIAL_AT`, the `toFixed` method will always return a value in normal notation + * and the `toExponential` method will always return a value in exponential form. + * + * Calling `toString` with a base argument, e.g. `toString(10)`, will also always return normal notation. + * + * @default `[-7, 20]` + */ + EXPONENTIAL_AT?: number | [number, number]; + + /** + * - number: integer, magnitude `1` to `1e+9` inclusive + * - number[]: [ integer `-1e+9` to `-1` inclusive, integer `1` to `1e+9` inclusive ] + * + * The exponent value(s) beyond which overflow to `Infinity` and underflow to zero occurs. + * + * If a single number is + * assigned, it is the maximum exponent magnitude: values wth a positive exponent of greater magnitude become + * Infinity and those with a negative exponent of greater magnitude become zero. + * + * If an array of two numbers is + * assigned then the first number is the negative exponent limit and the second number is the positive exponent + * limit. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they become zero and + * Infinity, use [-324, 308]. + * + * ```ts + * BigNumber.config({ RANGE: 500 }) + * BigNumber.config().RANGE // [ -500, 500 ] + * new BigNumber('9.999e499') // '9.999e+499' + * new BigNumber('1e500') // 'Infinity' + * new BigNumber('1e-499') // '1e-499' + * new BigNumber('1e-500') // '0' + * BigNumber.config({ RANGE: [-3, 4] }) + * new BigNumber(99999) // '99999' e is only 4 + * new BigNumber(100000) // 'Infinity' e is 5 + * new BigNumber(0.001) // '0.01' e is only -3 + * new BigNumber(0.0001) // '0' e is -4 + * ``` + * + * The largest possible magnitude of a finite BigNumber is `9.999...e+1000000000`. + * + * The smallest possible magnitude of a non-zero BigNumber is `1e-1000000000`. + * + * @default `[-1e+9, 1e+9]` + */ + RANGE?: number | [number, number]; + + /** + * + * The value that determines whether BigNumber Errors are thrown. If ERRORS is false, no errors will be thrown. + * `true`, `false`, `0` or `1`. + * ```ts + * BigNumber.config({ ERRORS: false }) + * ``` + * + * @default `true` + */ + ERRORS?: boolean | number; + + /** + * `true`, `false`, `0` or `1`. + * + * The value that determines whether cryptographically-secure pseudo-random number generation is used. + * + * If `CRYPTO` is set to `true` then the random method will generate random digits using `crypto.getRandomValues` in + * browsers that support it, or `crypto.randomBytes` if using a version of Node.js that supports it. + * + * If neither function is supported by the host environment then attempting to set `CRYPTO` to `true` will fail, and + * if [[Configuration.ERRORS]] is `true` an exception will be thrown. + * + * If `CRYPTO` is `false` then the source of randomness used will be `Math.random` (which is assumed to generate at + * least 30 bits of randomness). + * + * See [[BigNumber.random]]. + * + * ```ts + * BigNumber.config({ CRYPTO: true }) + * BigNumber.config().CRYPTO // true + * BigNumber.random() // 0.54340758610486147524 + * ``` + * + * @default `false` + */ + CRYPTO?: boolean | number; + + /** + * The modulo mode used when calculating the modulus: `a mod n`. + * + * The quotient, `q = a / n`, is calculated according to + * the [[Configuration.ROUNDING_MODE]] that corresponds to the chosen MODULO_MODE. + * + * The remainder, r, is calculated as: `r = a - n * q`. + * + * The modes that are most commonly used for the modulus/remainder operation are shown in the following table. + * Although the other rounding modes can be used, they may not give useful results. + * + * Property | Value | Description + * -------------------|:-----:|--------------------------------------------------------------------------------------- + * `ROUND_UP` | 0 | The remainder is positive if the dividend is negative, otherwise it is negative. + * `ROUND_DOWN` | 1 | The remainder has the same sign as the dividend. This uses 'truncating division' and matches the behaviour of JavaScript's remainder operator `%`. + * `ROUND_FLOOR` | 3 | The remainder has the same sign as the divisor. + * | | This matches Python's % operator. + * `ROUND_HALF_EVEN` | 6 | The IEEE 754 remainder function. + * `EUCLID` | 9 | The remainder is always positive. Euclidian division: `q = sign(n) * floor(a / abs(n))` + * + * The rounding/modulo modes are available as enumerated properties of the BigNumber constructor. + * + * See [[BigNumber.modulo]] + * + * ```ts + * BigNumber.config({ MODULO_MODE: BigNumber.EUCLID }) + * BigNumber.config({ MODULO_MODE: 9 }) // equivalent + * ``` + * + * @default [[RoundingMode.ROUND_DOWN]] + */ + MODULO_MODE?: RoundingMode; + + /** + * integer, `0` to `1e+9` inclusive. + * + * The maximum number of significant digits of the result of the power operation (unless a modulus is specified). + * + * If set to 0, the number of signifcant digits will not be limited. + * + * See [[BigNumber.toPower]] + * + * ```ts + * BigNumber.config({ POW_PRECISION: 100 }) + * ``` + * + * @default 100 + */ + POW_PRECISION?: number; + + /** + * The FORMAT object configures the format of the string returned by the `toFormat` method. The example below shows + * the properties of the FORMAT object that are recognised, and their default values. Unlike the other configuration + * properties, the values of the properties of the FORMAT object will not be checked for validity. The existing + * FORMAT object will simply be replaced by the object that is passed in. Note that all the properties shown below + * do not have to be included. + * + * See `toFormat` for examples of usage. + * + * ```ts + * BigNumber.config({ + * FORMAT: { + * // the decimal separator + * decimalSeparator: '.', + * // the grouping separator of the integer part + * groupSeparator: ',', + * // the primary grouping size of the integer part + * groupSize: 3, + * // the secondary grouping size of the integer part + * secondaryGroupSize: 0, + * // the grouping separator of the fraction part + * fractionGroupSeparator: ' ', + * // the grouping size of the fraction part + * fractionGroupSize: 0 + * } + * }); + * ``` + */ + FORMAT?: Format; +} + +/** + * The library's enumerated rounding modes are stored as properties of the constructor. + * (They are not referenced internally by the library itself.) + * Rounding modes 0 to 6 (inclusive) are the same as those of Java's BigDecimal class. + */ +declare enum RoundingMode { + /** Rounds away from zero */ + ROUND_UP = 0, + /** Rounds towards zero */ + ROUND_DOWN = 1, + /** Rounds towards Infinity */ + ROUND_CEIL = 2, + /** Rounds towards -Infinity */ + ROUND_FLOOR = 3, + /** + * Rounds towards nearest neighbour. If equidistant, rounds away from zero + */ + ROUND_HALF_UP = 4, + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards zero + */ + ROUND_HALF_DOWN = 5, + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour + */ + ROUND_HALF_EVEN = 6, + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards `Infinity` + */ + ROUND_HALF_CEIL = 7, + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards `-Infinity` + */ + ROUND_HALF_FLOOR = 8, + /** + * The remainder is always positive. Euclidian division: `q = sign(n) * floor(a / abs(n))` + */ + EUCLID = 9 +} + +export class BigNumber { + + /** Rounds away from zero */ + static ROUND_UP: RoundingMode; + + /** Rounds towards zero */ + static ROUND_DOWN: RoundingMode; + + /** Rounds towards Infinity */ + static ROUND_CEIL: RoundingMode; + + /** Rounds towards -Infinity */ + static ROUND_FLOOR: RoundingMode; + + /** + * Rounds towards nearest neighbour. If equidistant, rounds away from zero + */ + static ROUND_HALF_UP: RoundingMode; + + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards zero + */ + static ROUND_HALF_DOWN: RoundingMode; + + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour + */ + static ROUND_HALF_EVEN: RoundingMode; + + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards `Infinity` + */ + static ROUND_HALF_CEIL: RoundingMode; + + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards `-Infinity` + */ + static ROUND_HALF_FLOOR: RoundingMode; + + /** + * The remainder is always positive. Euclidian division: `q = sign(n) * floor(a / abs(n))` + */ + static EUCLID: RoundingMode; + + /** + * Returns a new independent BigNumber constructor with configuration as described by `obj` (see `config`), or with + * the default configuration if `obj` is `null` or `undefined`. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BN = BigNumber.another({ DECIMAL_PLACES: 9 }) + * + * x = new BigNumber(1) + * y = new BN(1) + * + * x.div(3) // 0.33333 + * y.div(3) // 0.333333333 + * + * // BN = BigNumber.another({ DECIMAL_PLACES: 9 }) is equivalent to: + * BN = BigNumber.another() + * BN.config({ DECIMAL_PLACES: 9 }) + * ``` + */ + static another(config?: Configuration): typeof BigNumber; + + /** + * Configures the 'global' settings for this particular BigNumber constructor. Returns an object with the above + * properties and their current values. If the value to be assigned to any of the above properties is `null` or + * `undefined` it is ignored. See Errors for the treatment of invalid values. + */ + static config(config?: Configuration): Configuration; + + /** + * Configures the 'global' settings for this particular BigNumber constructor. Returns an object with the above + * properties and their current values. If the value to be assigned to any of the above properties is `null` or + * `undefined` it is ignored. See Errors for the treatment of invalid values. + */ + static config( + decimalPlaces?: number, + roundingMode?: RoundingMode, + exponentialAt?: number | [number, number], + range?: number | [number, number], + errors?: boolean | number, + crypto?: boolean | number, + moduloMode?: RoundingMode, + powPrecision?: number, + format?: Format + ): Configuration; + + /** + * Returns a BigNumber whose value is the maximum of `arg1`, `arg2`,... . The argument to this method can also be an + * array of values. The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.max(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.max(arr) // '14' + * ``` + */ + static max(...args: Array<number | string | BigNumber>): BigNumber; + static max(args: Array<number | string | BigNumber>): BigNumber; + + /** + * See BigNumber for further parameter details. Returns a BigNumber whose value is the minimum of arg1, arg2,... . + * The argument to this method can also be an array of values. The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.min(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.min(arr) // '-15.9999' + * ``` + */ + static min(...args: Array<number | string | BigNumber>): BigNumber; + static min(args: Array<number | string | BigNumber>): BigNumber; + + /** + * Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and less than 1. + * + * The return value + * will have dp decimal places (or less if trailing zeros are produced). If dp is omitted then the number of decimal + * places will default to the current `DECIMAL_PLACES` setting. + * + * Depending on the value of this BigNumber constructor's + * `CRYPTO` setting and the support for the crypto object in the host environment, the random digits of the return + * value are generated by either `Math.random` (fastest), `crypto.getRandomValues` (Web Cryptography API in recent + * browsers) or `crypto.randomBytes` (Node.js). + * + * If `CRYPTO` is true, i.e. one of the crypto methods is to be used, the + * value of a returned BigNumber should be cryptographically-secure and statistically indistinguishable from a + * random value. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 10 }) + * BigNumber.random() // '0.4117936847' + * BigNumber.random(20) // '0.78193327636914089009' + * ``` + * + * @param dp integer, `0` to `1e+9` inclusive + */ + static random(dp?: number): BigNumber; + + /** + * Coefficient: Array of base `1e14` numbers or `null` + * @readonly + */ + c: number[]; + + /** + * Exponent: Integer, `-1000000000` to `1000000000` inclusive or `null` + * @readonly + */ + e: number; + + /** + * Sign: `-1`, `1` or `null` + * @readonly + */ + s: number; + + /** + * Returns a new instance of a BigNumber object. If a base is specified, the value is rounded according to the + * current [[Configuration.DECIMAL_PLACES]] and [[Configuration.ROUNDING_MODE]] configuration. See Errors for the treatment of an invalid value or base. + * + * ```ts + * x = new BigNumber(9) // '9' + * y = new BigNumber(x) // '9' + * + * // 'new' is optional if ERRORS is false + * BigNumber(435.345) // '435.345' + * + * new BigNumber('5032485723458348569331745.33434346346912144534543') + * new BigNumber('4.321e+4') // '43210' + * new BigNumber('-735.0918e-430') // '-7.350918e-428' + * new BigNumber(Infinity) // 'Infinity' + * new BigNumber(NaN) // 'NaN' + * new BigNumber('.5') // '0.5' + * new BigNumber('+2') // '2' + * new BigNumber(-10110100.1, 2) // '-180.5' + * new BigNumber(-0b10110100.1) // '-180.5' + * new BigNumber('123412421.234324', 5) // '607236.557696' + * new BigNumber('ff.8', 16) // '255.5' + * new BigNumber('0xff.8') // '255.5' + * ``` + * + * The following throws `not a base 2 number` if [[Configuration.ERRORS]] is true, otherwise it returns a BigNumber with value `NaN`. + * + * ```ts + * new BigNumber(9, 2) + * ``` + * + * The following throws `number type has more than 15 significant digits` if [[Configuration.ERRORS]] is true, otherwise it returns a BigNumber with value `96517860459076820`. + * + * ```ts + * new BigNumber(96517860459076817.4395) + * ``` + * + * The following throws `not a number` if [[Configuration.ERRORS]] is true, otherwise it returns a BigNumber with value `NaN`. + * + * ```ts + * new BigNumber('blurgh') + * ``` + * + * A value is only rounded by the constructor if a base is specified. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * new BigNumber(1.23456789) // '1.23456789' + * new BigNumber(1.23456789, 10) // '1.23457' + * ``` + * + * @param value A numeric value. + * + * Legitimate values include `±0`, `±Infinity` and `NaN`. + * + * Values of type `number` with more than 15 significant digits are considered invalid (if [[Configuration.ERRORS]] + * is `true`) as calling `toString` or `valueOf` on such numbers may not result in the intended value. + * + * There is no limit to the number of digits of a value of type `string` (other than that of JavaScript's maximum + * array size). + * + * Decimal string values may be in exponential, as well as normal (fixed-point) notation. Non-decimal values must be + * in normal notation. String values in hexadecimal literal form, e.g. `'0xff'`, are valid, as are string values + * with the octal and binary prefixs `'0o'` and `'0b'`. + * + * String values in octal literal form without the prefix will be interpreted as decimals, e.g. `'011'` is + * interpreted as 11, not 9. + * + * Values in any base may have fraction digits. + * + * For bases from 10 to 36, lower and/or upper case letters can be used to represent values from 10 to 35. + * + * For bases above 36, a-z represents values from 10 to 35, A-Z from 36 to 61, and $ and _ represent 62 and 63 + * respectively (this can be changed by editing the ALPHABET variable near the top of the source file). + * + * @param base integer, 2 to 64 inclusive + * + * The base of value. If base is omitted, or is `null` or `undefined`, base 10 is assumed. + */ + constructor(value: number | string | BigNumber, base?: number); + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this BigNumber. The + * return value is always exact and unrounded. + * ```ts + * x = new BigNumber(-0.8) + * y = x.absoluteValue() // '0.8' + * z = y.abs() // '0.8' + * ``` + * @alias [[BigNumber.abs]] + */ + absoluteValue(): BigNumber; + + /** + * See [[BigNumber.absoluteValue]] + */ + abs(): BigNumber; + + /** + * See [[plus]] + */ + add(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a whole number in the direction of + * positive `Infinity`. + * + * ```ts + * x = new BigNumber(1.3) + * x.ceil() // '2' + * y = new BigNumber(-1.8) + * y.ceil() // '-1' + * ``` + */ + ceil(): BigNumber; + + /** + * Returns | | + * :-------:|---------------------------------------------------------------| + * 1 | If the value of this BigNumber is greater than the value of n + * -1 | If the value of this BigNumber is less than the value of n + * 0 | If this BigNumber and n have the same value + * null | If the value of either this BigNumber or n is NaN + * + * ```ts + * x = new BigNumber(Infinity) + * y = new BigNumber(5) + * x.comparedTo(y) // 1 + * x.comparedTo(x.minus(1)) // 0 + * y.cmp(NaN) // null + * y.cmp('110', 2) // -1 + * ``` + * + * @alias [[cmp]] + */ + comparedTo(n: number | string | BigNumber, base?: number): number; + + /** + * See [[comparedTo]] + */ + cmp(n: number | string | BigNumber, base?: number): number; + + /** + * Return the number of decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * `±Infinity` or `NaN`. + * + * ```ts + * x = new BigNumber(123.45) + * x.decimalPlaces() // 2 + * y = new BigNumber('9.9e-101') + * y.dp() // 102 + * ``` + * + * @alias [[dp]] + */ + decimalPlaces(): number; + + /** + * See [[decimalPlaces]] + */ + dp(): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by n, rounded according to the current + * DECIMAL_PLACES and ROUNDING_MODE configuration. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.dividedBy(y) // '3.14159292035398230088' + * x.div(5) // '71' + * x.div(47, 16) // '5' + * ``` + * + * @alias [[div]] + */ + dividedBy(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * See [[dividedBy]] + */ + div(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * Return a BigNumber whose value is the integer part of dividing the value of this BigNumber by n. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.dividedToIntegerBy(y) // '1' + * x.divToInt(0.7) // '7' + * x.divToInt('0.f', 16) // '5' + * ``` + * + * @alias [[divToInt]] + */ + dividedToIntegerBy(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * See [[dividedToIntegerBy]] + */ + divToInt(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * Returns true if the value of this BigNumber equals the value of `n`, otherwise returns `false`. As with JavaScript, + * `NaN` does not equal `NaN`. + * + * Note: This method uses the [[comparedTo]] internally. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.equals('1e-324') // false + * BigNumber(-0).eq(x) // true ( -0 === 0 ) + * BigNumber(255).eq('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.equals(NaN) // false + * ``` + * + * @alias [[eq]] + */ + equals(n: number | string | BigNumber, base?: number): boolean; + + /** + * See [[equals]] + */ + eq(n: number | string | BigNumber, base?: number): boolean; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a whole number in the direction of + * negative `Infinity`. + * + * ```ts + * x = new BigNumber(1.8) + * x.floor() // '1' + * y = new BigNumber(-1.3) + * y.floor() // '-2' + * ``` + */ + floor(): BigNumber; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise returns `false`. + * + * Note: This method uses the comparedTo method internally. + * + * ```ts + * 0.1 > (0.3 - 0.2) // true + * x = new BigNumber(0.1) + * x.greaterThan(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).gt(x) // false + * BigNumber(11, 3).gt(11.1, 2) // true + * ``` + * + * @alias [[gt]] + */ + greaterThan(n: number | string | BigNumber, base?: number): boolean; + + /** + * See [[greaterThan]] + */ + gt(n: number | string | BigNumber, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, otherwise returns `false`. + * + * Note: This method uses the comparedTo method internally. + * + * @alias [[gte]] + */ + greaterThanOrEqualTo(n: number | string | BigNumber, base?: number): boolean; + + /** + * See [[greaterThanOrEqualTo]] + */ + gte(n: number | string | BigNumber, base?: number): boolean; + + /** + * Returns true if the value of this BigNumber is a finite number, otherwise returns false. The only possible + * non-finite values of a BigNumber are `NaN`, `Infinity` and `-Infinity`. + * + * Note: The native method `isFinite()` can be used if `n <= Number.MAX_VALUE`. + */ + isFinite(): boolean; + + /** + * Returns true if the value of this BigNumber is a whole number, otherwise returns false. + * @alias [[isInt]] + */ + isInteger(): boolean; + + /** + * See [[isInteger]] + */ + isInt(): boolean; + + /** + * Returns `true` if the value of this BigNumber is `NaN`, otherwise returns `false`. + * + * Note: The native method isNaN() can also be used. + */ + isNaN(): boolean; + + /** + * Returns true if the value of this BigNumber is negative, otherwise returns false. + * + * Note: `n < 0` can be used if `n <= * -Number.MIN_VALUE`. + * + * @alias [[isNeg]] + */ + isNegative(): boolean; + + /** + * See [[isNegative]] + */ + isNeg(): boolean; + + /** + * Returns true if the value of this BigNumber is zero or minus zero, otherwise returns false. + * + * Note: `n == 0` can be used if `n >= Number.MIN_VALUE`. + */ + isZero(): boolean; + + /** + * Returns true if the value of this BigNumber is less than the value of n, otherwise returns false. + * + * Note: This method uses [[comparedTo]] internally. + * + * @alias [[lt]] + */ + lessThan(n: number | string | BigNumber, base?: number): boolean; + + /** + * See [[lessThan]] + */ + lt(n: number | string | BigNumber, base?: number): boolean; + + /** + * Returns true if the value of this BigNumber is less than or equal the value of n, otherwise returns false. + * + * Note: This method uses [[comparedTo]] internally. + */ + lessThanOrEqualTo(n: number | string | BigNumber, base?: number): boolean; + + /** + * See [[lessThanOrEqualTo]] + */ + lte(n: number | string | BigNumber, base?: number): boolean; + + /** + * Returns a BigNumber whose value is the value of this BigNumber minus `n`. + * + * The return value is always exact and unrounded. + * + * @alias [[sub]] + */ + minus(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo n, i.e. the integer remainder of dividing + * this BigNumber by n. + * + * The value returned, and in particular its sign, is dependent on the value of the [[Configuration.MODULO_MODE]] + * setting of this BigNumber constructor. If it is `1` (default value), the result will have the same sign as this + * BigNumber, and it will match that of Javascript's `%` operator (within the limits of double precision) and + * BigDecimal's remainder method. + * + * The return value is always exact and unrounded. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.modulo(0.9) // '0.1' + * y = new BigNumber(33) + * y.mod('a', 33) // '3' + * ``` + * + * @alias [[mod]] + */ + modulo(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * See [[modulo]] + */ + mod(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * See [[times]] + */ + mul(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by -1. + * + * ```ts + * x = new BigNumber(1.8) + * x.negated() // '-1.8' + * y = new BigNumber(-1.3) + * y.neg() // '1.3' + * ``` + * + * @alias [[neg]] + */ + negated(): BigNumber; + + /** + * See [[negated]] + */ + neg(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber plus `n`. + * + * The return value is always exact and unrounded. + * + * @alias [[add]] + */ + plus(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * If z is true or 1 then any trailing zeros of the integer part of a number are counted as significant digits, + * otherwise they are not. + * + * @param z true, false, 0 or 1 + * @alias [[sd]] + */ + precision(z?: boolean | number): number; + + /** + * See [[precision]] + */ + sd(z?: boolean | number): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode rm to a maximum of dp + * decimal places. + * + * - if dp is omitted, or is null or undefined, the return value is n rounded to a whole number. + * - if rm is omitted, or is null or undefined, ROUNDING_MODE is used. + * + * ```ts + * x = 1234.56 + * Math.round(x) // 1235 + * y = new BigNumber(x) + * y.round() // '1235' + * y.round(1) // '1234.6' + * y.round(2) // '1234.56' + * y.round(10) // '1234.56' + * y.round(0, 1) // '1234' + * y.round(0, 6) // '1235' + * y.round(1, 1) // '1234.5' + * y.round(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * y // '1234.56' + * ``` + * + * @param dp integer, 0 to 1e+9 inclusive + * @param rm integer, 0 to 8 inclusive + */ + round(dp?: number, rm?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber shifted n places. + * + * The shift is of the decimal point, i.e. of powers of ten, and is to the left if n is negative or to the right if + * n is positive. The return value is always exact and unrounded. + * + * @param n integer, -9007199254740991 to 9007199254740991 inclusive + */ + shift(n: number): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded according to the + * current DECIMAL_PLACES and ROUNDING_MODE configuration. + * + * The return value will be correctly rounded, i.e. rounded + * as if the result was first calculated to an infinite number of correct digits before rounding. + * + * @alias [[sqrt]] + */ + squareRoot(): BigNumber; + + /** + * See [[squareRoot]] + */ + sqrt(): BigNumber; + + /** + * See [[minus]] + */ + sub(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber times n. + * + * The return value is always exact and unrounded. + * + * @alias [[mul]] + */ + times(n: number | string | BigNumber, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to sd significant digits using rounding mode rm. + * + * If sd is omitted or is null or undefined, the return value will not be rounded. + * + * If rm is omitted or is null or undefined, ROUNDING_MODE will be used. + * + * ```ts + * BigNumber.config({ precision: 5, rounding: 4 }) + * x = new BigNumber(9876.54321) + * + * x.toDigits() // '9876.5' + * x.toDigits(6) // '9876.54' + * x.toDigits(6, BigNumber.ROUND_UP) // '9876.55' + * x.toDigits(2) // '9900' + * x.toDigits(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param sd integer, 1 to 1e+9 inclusive + * @param rm integer, 0 to 8 inclusive + */ + toDigits(sd?: number, rm?: number): BigNumber; + + /** + * Returns a string representing the value of this BigNumber in exponential notation rounded using rounding mode rm + * to dp decimal places, i.e with one digit before the decimal point and dp digits after it. + * + * If the value of this BigNumber in exponential notation has fewer than dp fraction digits, the return value will + * be appended with zeros accordingly. + * + * If dp is omitted, or is null or undefined, the number of digits after the decimal point defaults to the minimum + * number of digits necessary to represent the value exactly. + * + * If rm is omitted or is null or undefined, ROUNDING_MODE is used. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toExponential() // '4.56e+1' + * y.toExponential() // '4.56e+1' + * x.toExponential(0) // '5e+1' + * y.toExponential(0) // '5e+1' + * x.toExponential(1) // '4.6e+1' + * y.toExponential(1) // '4.6e+1' + * y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN) + * x.toExponential(3) // '4.560e+1' + * y.toExponential(3) // '4.560e+1' + * ``` + * + * @param dp integer, 0 to 1e+9 inclusive + * @param rm integer, 0 to 8 inclusive + */ + toExponential(dp?: number, rm?: number): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation rounded to dp decimal + * places using rounding mode `rm`. + * + * If the value of this BigNumber in normal notation has fewer than `dp` fraction digits, the return value will be + * appended with zeros accordingly. + * + * Unlike `Number.prototype.toFixed`, which returns exponential notation if a number is greater or equal to 10<sup>21</sup>, this + * method will always return normal notation. + * + * If dp is omitted or is `null` or `undefined`, the return value will be unrounded and in normal notation. This is also + * unlike `Number.prototype.toFixed`, which returns the value to zero decimal places. + * + * It is useful when fixed-point notation is required and the current `EXPONENTIAL_AT` setting causes toString to + * return exponential notation. + * + * If `rm` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * ```ts + * x = 3.456 + * y = new BigNumber(x) + * x.toFixed() // '3' + * y.toFixed() // '3.456' + * y.toFixed(0) // '3' + * x.toFixed(2) // '3.46' + * y.toFixed(2) // '3.46' + * y.toFixed(2, 1) // '3.45' (ROUND_DOWN) + * x.toFixed(5) // '3.45600' + * y.toFixed(5) // '3.45600' + * ``` + * + * @param dp integer, 0 to 1e+9 inclusive + * @param rm integer, 0 to 8 inclusive + */ + toFixed(dp?: number, rm?: number): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation rounded to dp decimal + * places using rounding mode `rm`, and formatted according to the properties of the FORMAT object. + * + * See the examples below for the properties of the `FORMAT` object, their types and their usage. + * + * If `dp` is omitted or is `null` or `undefined`, then the return value is not rounded to a fixed number of decimal + * places. + * + * If `rm` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * ```ts + * format = { + * decimalSeparator: '.', + * groupSeparator: ',', + * groupSize: 3, + * secondaryGroupSize: 0, + * fractionGroupSeparator: ' ', + * fractionGroupSize: 0 + * } + * BigNumber.config({ FORMAT: format }) + * + * x = new BigNumber('123456789.123456789') + * x.toFormat() // '123,456,789.123456789' + * x.toFormat(1) // '123,456,789.1' + * + * // If a reference to the object assigned to FORMAT has been retained, + * // the format properties can be changed directly + * format.groupSeparator = ' ' + * format.fractionGroupSize = 5 + * x.toFormat() // '123 456 789.12345 6789' + * + * BigNumber.config({ + * FORMAT: { + * decimalSeparator = ',', + * groupSeparator = '.', + * groupSize = 3, + * secondaryGroupSize = 2 + * } + * }) + * + * x.toFormat(6) // '12.34.56.789,123' + * ``` + * + * @param dp integer, 0 to 1e+9 inclusive + * @param rm integer, 0 to 8 inclusive + */ + toFormat(dp?: number, rm?: number): string; + + /** + * Returns a string array representing the value of this BigNumber as a simple fraction with an integer numerator + * and an integer denominator. The denominator will be a positive non-zero value less than or equal to max. + * + * If a maximum denominator, max, is not specified, or is null or undefined, the denominator will be the lowest + * value necessary to represent the number exactly. + * + * ```ts + * x = new BigNumber(1.75) + * x.toFraction() // '7, 4' + * + * pi = new BigNumber('3.14159265358') + * pi.toFraction() // '157079632679,50000000000' + * pi.toFraction(100000) // '312689, 99532' + * pi.toFraction(10000) // '355, 113' + * pi.toFraction(100) // '311, 99' + * pi.toFraction(10) // '22, 7' + * pi.toFraction(1) // '3, 1' + * ``` + * + * @param max integer >= `1` and < `Infinity` + */ + toFraction(max?: number | string | BigNumber): [string, string]; + + /** + * Same as [[valueOf]] + * + * ```ts + * x = new BigNumber('177.7e+457') + * y = new BigNumber(235.4325) + * z = new BigNumber('0.0098074') + * + * // Serialize an array of three BigNumbers + * str = JSON.stringify( [x, y, z] ) + * // "["1.777e+459","235.4325","0.0098074"]" + * + * // Return an array of three BigNumbers + * JSON.parse(str, function (key, val) { + * return key === '' ? val : new BigNumber(val) + * }) + * ``` + */ + toJSON(): string; + + /** + * Returns the value of this BigNumber as a JavaScript number primitive. + * + * Type coercion with, for example, the unary plus operator will also work, except that a BigNumber with the value + * minus zero will be converted to positive zero. + * + * ```ts + * x = new BigNumber(456.789) + * x.toNumber() // 456.789 + * +x // 456.789 + * + * y = new BigNumber('45987349857634085409857349856430985') + * y.toNumber() // 4.598734985763409e+34 + * + * z = new BigNumber(-0) + * 1 / +z // Infinity + * 1 / z.toNumber() // -Infinity + * ``` + */ + toNumber(): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber raised to the power `n`, and optionally modulo `a` + * modulus `m`. + * + * If `n` is negative the result is rounded according to the current [[Configuration.DECIMAL_PLACES]] and + * [[Configuration.ROUNDING_MODE]] configuration. + * + * If `n` is not an integer or is out of range: + * - If `ERRORS` is `true` a BigNumber Error is thrown, + * - else if `n` is greater than `9007199254740991`, it is interpreted as `Infinity`; + * - else if n is less than `-9007199254740991`, it is interpreted as `-Infinity`; + * - else if `n` is otherwise a number, it is truncated to an integer; + * - else it is interpreted as `NaN`. + * + * As the number of digits of the result of the power operation can grow so large so quickly, e.g. + * 123.456<sup>10000</sup> has over 50000 digits, the number of significant digits calculated is limited to the + * value of the [[Configuration.POW_PRECISION]] setting (default value: `100`) unless a modulus `m` is specified. + * + * Set [[Configuration.POW_PRECISION]] to `0` for an unlimited number of significant digits to be calculated (this + * will cause the method to slow dramatically for larger exponents). + * + * Negative exponents will be calculated to the number of decimal places specified by + * [[Configuration.DECIMAL_PLACES]] (but not to more than [[Configuration.POW_PRECISION]] significant digits). + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are positive integers, then a fast modular + * exponentiation algorithm is used, otherwise if any of the values is not a positive integer the operation will + * simply be performed as `x.toPower(n).modulo(m)` with a `POW_PRECISION` of `0`. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.toPower(2) // '0.49' + * BigNumber(3).pow(-2) // '0.11111111111111111111' + * ``` + * + * @param n integer, -9007199254740991 to 9007199254740991 inclusive + * @alias [[pow]] + */ + toPower(n: number, m?: number | string | BigNumber): BigNumber; + + /** + * See [[toPower]] + */ + pow(n: number, m?: number | string | BigNumber): BigNumber; + + /** + * Returns a string representing the value of this BigNumber rounded to `sd` significant digits using rounding mode + * rm. + * + * - If `sd` is less than the number of digits necessary to represent the integer part of the value in normal + * (fixed-point) notation, then exponential notation is used. + * - If `sd` is omitted, or is `null` or `undefined`, then the return value is the same as `n.toString()`. + * - If `rm` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toPrecision() // '45.6' + * y.toPrecision() // '45.6' + * x.toPrecision(1) // '5e+1' + * y.toPrecision(1) // '5e+1' + * y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP) + * y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN) + * x.toPrecision(5) // '45.600' + * y.toPrecision(5) // '45.600' + * ``` + * + * @param sd integer, 1 to 1e+9 inclusive + * @param rm integer, 0 to 8 inclusive + */ + toPrecision(sd?: number, rm?: number): string; + + /** + * Returns a string representing the value of this BigNumber in the specified base, or base 10 if base is omitted or + * is `null` or `undefined`. + * + * For bases above 10, values from 10 to 35 are represented by a-z (as with `Number.prototype.toString`), 36 to 61 by + * A-Z, and 62 and 63 by `$` and `_` respectively. + * + * If a base is specified the value is rounded according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` + * configuration. + * + * If a base is not specified, and this BigNumber has a positive exponent that is equal to or greater than the + * positive component of the current `EXPONENTIAL_AT` setting, or a negative exponent equal to or less than the + * negative component of the setting, then exponential notation is returned. + * + * If base is `null` or `undefined` it is ignored. + * + * ```ts + * x = new BigNumber(750000) + * x.toString() // '750000' + * BigNumber.config({ EXPONENTIAL_AT: 5 }) + * x.toString() // '7.5e+5' + * + * y = new BigNumber(362.875) + * y.toString(2) // '101101010.111' + * y.toString(9) // '442.77777777777777777778' + * y.toString(32) // 'ba.s' + * + * BigNumber.config({ DECIMAL_PLACES: 4 }); + * z = new BigNumber('1.23456789') + * z.toString() // '1.23456789' + * z.toString(10) // '1.2346' + * ``` + * + * @param base integer, 2 to 64 inclusive + */ + toString(base?: number): string; + + /** + * Returns a BigNumber whose value is the value of this BigNumber truncated to a whole number. + * + * ```ts + * x = new BigNumber(123.456) + * x.truncated() // '123' + * y = new BigNumber(-12.3) + * y.trunc() // '-12' + * ``` + * + * @alias [[trunc]] + */ + truncated(): BigNumber; + + /** + * See [[truncated]] + */ + trunc(): BigNumber; + + /** + * As [[toString]], but does not accept a base argument and includes the minus sign for negative zero.` + * + * ```ts + * x = new BigNumber('-0') + * x.toString() // '0' + * x.valueOf() // '-0' + * y = new BigNumber('1.777e+457') + * y.valueOf() // '1.777e+457' + * ``` + */ + valueOf(): string; +} + +export default BigNumber; diff --git a/node_modules/bignumber.js/bignumber.js b/node_modules/bignumber.js/bignumber.js new file mode 100644 index 0000000000000000000000000000000000000000..421f5444452baa126f2b18bd382dbabb9083ba57 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.js @@ -0,0 +1,2734 @@ +/*! bignumber.js v4.1.0 https://github.com/MikeMcl/bignumber.js/LICENCE */ + +;(function (globalObj) { + 'use strict'; + + /* + bignumber.js v4.1.0 + A JavaScript library for arbitrary-precision arithmetic. + https://github.com/MikeMcl/bignumber.js + Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com> + MIT Expat Licence + */ + + + var BigNumber, + isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + notBool = ' not a boolean or binary digit', + roundingMode = 'rounding mode', + tooManyDigits = 'number type has more than 15 significant digits', + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_', + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + /* + * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an + * exception is thrown (if ERRORS is true). + */ + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function constructorFactory(config) { + var div, parseNumeric, + + // id tracks the caller function, so its name can be included in error messages. + id = 0, + P = BigNumber.prototype, + ONE = new BigNumber(1), + + + /********************************* EDITABLE DEFAULTS **********************************/ + + + /* + * The default values below must be integers within the inclusive ranges stated. + * The values can also be changed at run-time using BigNumber.config. + */ + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + /* + * The rounding mode used when rounding to the above decimal places, and when using + * toExponential, toFixed, toFormat and toPrecision, and round (default value). + * UP 0 Away from zero. + * DOWN 1 Towards zero. + * CEIL 2 Towards +Infinity. + * FLOOR 3 Towards -Infinity. + * HALF_UP 4 Towards nearest neighbour. If equidistant, up. + * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + */ + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether BigNumber Errors are ever thrown. + ERRORS = true, // true or false + + // Change to intValidatorNoErrors if ERRORS is false. + isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + /* + * The modulo mode used when calculating the modulus: a mod n. + * The quotient (q = a / n) is calculated according to the corresponding rounding mode. + * The remainder (r) is calculated as: r = a - n * q. + * + * UP 0 The remainder is positive if the dividend is negative, else is negative. + * DOWN 1 The remainder has the same sign as the dividend. + * This modulo mode is commonly known as 'truncated division' and is + * equivalent to (a % n) in JavaScript. + * FLOOR 3 The remainder has the same sign as the divisor (Python %). + * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + * The remainder is always positive. + * + * The truncated division, floored division, Euclidian division and IEEE 754 remainder + * modes are commonly used for the modulus operation. + * Although the other rounding modes can also be used, they may not give useful results. + */ + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the toPower operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + decimalSeparator: '.', + groupSeparator: ',', + groupSize: 3, + secondaryGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + fractionGroupSize: 0 + }; + + + /******************************************************************************************/ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * n {number|string|BigNumber} A numeric value. + * [b] {number} The base of n. Integer, 2 to 64 inclusive. + */ + function BigNumber( n, b ) { + var c, e, i, num, len, str, + x = this; + + // Enable constructor usage without new. + if ( !( x instanceof BigNumber ) ) { + + // 'BigNumber() constructor call without new: {n}' + if (ERRORS) raise( 26, 'constructor call without new', n ); + return new BigNumber( n, b ); + } + + // 'new BigNumber() base not an integer: {b}' + // 'new BigNumber() base out of range: {b}' + if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { + + // Duplicate. + if ( n instanceof BigNumber ) { + x.s = n.s; + x.e = n.e; + x.c = ( n = n.c ) ? n.slice() : n; + id = 0; + return; + } + + if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { + x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; + + // Fast path for integers. + if ( n === ~~n ) { + for ( e = 0, i = n; i >= 10; i /= 10, e++ ); + x.e = e; + x.c = [n]; + id = 0; + return; + } + + str = n + ''; + } else { + if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); + x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; + } + } else { + b = b | 0; + str = n + ''; + + // Ensure return value is rounded to DECIMAL_PLACES as with other bases. + // Allow exponential notation to be used with base 10 argument. + if ( b == 10 ) { + x = new BigNumber( n instanceof BigNumber ? n : str ); + return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); + } + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + // Any number in exponential form will fail due to the [Ee][+-]. + if ( ( num = typeof n == 'number' ) && n * 0 != 0 || + !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + + '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { + return parseNumeric( x, str, num, b ); + } + + if (num) { + x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; + + if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { + + // 'new BigNumber() number type has more than 15 significant digits: {n}' + raise( id, tooManyDigits, n ); + } + + // Prevent later check for length on converted number. + num = false; + } else { + x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; + } + + str = convertBase( str, 10, b, x.s ); + } + + // Decimal point? + if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); + + // Exponential form? + if ( ( i = str.search( /e/i ) ) > 0 ) { + + // Determine exponent. + if ( e < 0 ) e = i; + e += +str.slice( i + 1 ); + str = str.substring( 0, i ); + } else if ( e < 0 ) { + + // Integer. + e = str.length; + } + + // Determine leading zeros. + for ( i = 0; str.charCodeAt(i) === 48; i++ ); + + // Determine trailing zeros. + for ( len = str.length; str.charCodeAt(--len) === 48; ); + str = str.slice( i, len + 1 ); + + if (str) { + len = str.length; + + // Disallow numbers with over 15 significant digits if number type. + // 'new BigNumber() number type has more than 15 significant digits: {n}' + if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) { + raise( id, tooManyDigits, x.s * n ); + } + + e = e - i - 1; + + // Overflow? + if ( e > MAX_EXP ) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if ( e < MIN_EXP ) { + + // Zero. + x.c = [ x.e = 0 ]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = ( e + 1 ) % LOG_BASE; + if ( e < 0 ) i += LOG_BASE; + + if ( i < len ) { + if (i) x.c.push( +str.slice( 0, i ) ); + + for ( len -= LOG_BASE; i < len; ) { + x.c.push( +str.slice( i, i += LOG_BASE ) ); + } + + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } + + for ( ; i--; str += '0' ); + x.c.push( +str ); + } + } else { + + // Zero. + x.c = [ x.e = 0 ]; + } + + id = 0; + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.another = constructorFactory; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object or an argument list, with one or many of the following properties or + * parameters respectively: + * + * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive + * ROUNDING_MODE {number} Integer, 0 to 8 inclusive + * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or + * [integer -MAX to 0 incl., 0 to MAX incl.] + * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + * [integer -MAX to -1 incl., integer 1 to MAX incl.] + * ERRORS {boolean|number} true, false, 1 or 0 + * CRYPTO {boolean|number} true, false, 1 or 0 + * MODULO_MODE {number} 0 to 9 inclusive + * POW_PRECISION {number} 0 to MAX inclusive + * FORMAT {object} See BigNumber.prototype.toFormat + * decimalSeparator {string} + * groupSeparator {string} + * groupSize {number} + * secondaryGroupSize {number} + * fractionGroupSeparator {string} + * fractionGroupSize {number} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config(20, 4) is equivalent to + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined. + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function () { + var v, p, + i = 0, + r = {}, + a = arguments, + o = a[0], + has = o && typeof o == 'object' + ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; } + : function () { if ( a.length > i ) return ( v = a[i++] ) != null; }; + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // 'config() DECIMAL_PLACES not an integer: {v}' + // 'config() DECIMAL_PLACES out of range: {v}' + if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) { + DECIMAL_PLACES = v | 0; + } + r[p] = DECIMAL_PLACES; + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // 'config() ROUNDING_MODE not an integer: {v}' + // 'config() ROUNDING_MODE out of range: {v}' + if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) { + ROUNDING_MODE = v | 0; + } + r[p] = ROUNDING_MODE; + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // 'config() EXPONENTIAL_AT not an integer: {v}' + // 'config() EXPONENTIAL_AT out of range: {v}' + if ( has( p = 'EXPONENTIAL_AT' ) ) { + + if ( isArray(v) ) { + if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) { + TO_EXP_NEG = v[0] | 0; + TO_EXP_POS = v[1] | 0; + } + } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { + TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 ); + } + } + r[p] = [ TO_EXP_NEG, TO_EXP_POS ]; + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // 'config() RANGE not an integer: {v}' + // 'config() RANGE cannot be zero: {v}' + // 'config() RANGE out of range: {v}' + if ( has( p = 'RANGE' ) ) { + + if ( isArray(v) ) { + if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) { + MIN_EXP = v[0] | 0; + MAX_EXP = v[1] | 0; + } + } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { + if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 ); + else if (ERRORS) raise( 2, p + ' cannot be zero', v ); + } + } + r[p] = [ MIN_EXP, MAX_EXP ]; + + // ERRORS {boolean|number} true, false, 1 or 0. + // 'config() ERRORS not a boolean or binary digit: {v}' + if ( has( p = 'ERRORS' ) ) { + + if ( v === !!v || v === 1 || v === 0 ) { + id = 0; + isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors; + } else if (ERRORS) { + raise( 2, p + notBool, v ); + } + } + r[p] = ERRORS; + + // CRYPTO {boolean|number} true, false, 1 or 0. + // 'config() CRYPTO not a boolean or binary digit: {v}' + // 'config() crypto unavailable: {crypto}' + if ( has( p = 'CRYPTO' ) ) { + + if ( v === true || v === false || v === 1 || v === 0 ) { + if (v) { + v = typeof crypto == 'undefined'; + if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = true; + } else if (ERRORS) { + raise( 2, 'crypto unavailable', v ? void 0 : crypto ); + } else { + CRYPTO = false; + } + } else { + CRYPTO = false; + } + } else if (ERRORS) { + raise( 2, p + notBool, v ); + } + } + r[p] = CRYPTO; + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // 'config() MODULO_MODE not an integer: {v}' + // 'config() MODULO_MODE out of range: {v}' + if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) { + MODULO_MODE = v | 0; + } + r[p] = MODULO_MODE; + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // 'config() POW_PRECISION not an integer: {v}' + // 'config() POW_PRECISION out of range: {v}' + if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) { + POW_PRECISION = v | 0; + } + r[p] = POW_PRECISION; + + // FORMAT {object} + // 'config() FORMAT not an object: {v}' + if ( has( p = 'FORMAT' ) ) { + + if ( typeof v == 'object' ) { + FORMAT = v; + } else if (ERRORS) { + raise( 2, p + ' not an object', v ); + } + } + r[p] = FORMAT; + + return r; + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.max = function () { return maxOrMin( arguments, P.lt ); }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.min = function () { return maxOrMin( arguments, P.gt ); }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * 'random() decimal places not an integer: {dp}' + * 'random() decimal places out of range: {dp}' + * 'random() crypto unavailable: {crypto}' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor( Math.random() * pow2_53 ); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0; + k = mathceil( dp / LOG_BASE ); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues( new Uint32Array( k *= 2 ) ); + + for ( ; i < k; ) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if ( v >= 9e15 ) { + b = crypto.getRandomValues( new Uint32Array(2) ); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push( v % 1e14 ); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes( k *= 7 ); + + for ( ; i < k; ) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) + + ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) + + ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6]; + + if ( v >= 9e15 ) { + crypto.randomBytes(7).copy( a, i ); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push( v % 1e14 ); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + if (ERRORS) raise( 14, 'crypto unavailable', crypto ); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for ( ; i < k; ) { + v = random53bitInt(); + if ( v < 9e15 ) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if ( k && dp ) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor( k / v ) * v; + } + + // Remove trailing elements which are zero. + for ( ; c[i] === 0; c.pop(), i-- ); + + // Zero? + if ( i < 0 ) { + c = [ e = 0 ]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for ( i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if ( i < LOG_BASE ) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + // PRIVATE FUNCTIONS + + + // Convert a numeric string of baseIn to a numeric string of baseOut. + function convertBase( str, baseOut, baseIn, sign ) { + var d, e, k, r, x, xc, y, + i = str.indexOf( '.' ), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + if ( baseIn < 37 ) str = str.toLowerCase(); + + // Non-integer. + if ( i >= 0 ) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace( '.', '' ); + y = new BigNumber(baseIn); + x = y.pow( str.length - i ); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut ); + y.e = y.c.length; + } + + // Convert the number as integer. + xc = toBaseOut( str, baseIn, baseOut ); + e = k = xc.length; + + // Remove trailing zeros. + for ( ; xc[--k] == 0; xc.pop() ); + if ( !xc[0] ) return '0'; + + if ( i < 0 ) { + --e; + } else { + x.c = xc; + x.e = e; + + // sign is needed for correct rounding. + x.s = sign; + x = div( x, y, dp, rm, baseOut ); + xc = x.c; + r = x.r; + e = x.e; + } + + d = e + dp + 1; + + // The rounding digit, i.e. the digit to the right of the digit that may be rounded up. + i = xc[d]; + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) + : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == ( x.s < 0 ? 8 : 7 ) ); + + if ( d < 1 || !xc[0] ) { + + // 1^-dp or 0. + str = r ? toFixedPoint( '1', -dp ) : '0'; + } else { + xc.length = d; + + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for ( --baseOut; ++xc[--d] > baseOut; ) { + xc[d] = 0; + + if ( !d ) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for ( k = xc.length; !xc[--k]; ); + + // E.g. [4, 11, 15] becomes 4bf. + for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) ); + str = toFixedPoint( str, e ); + } + + // The caller will add the sign. + return str; + } + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply( x, k, base ) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for ( x = x.slice(); i--; ) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry; + carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare( a, b, aL, bL ) { + var i, cmp; + + if ( aL != bL ) { + cmp = aL > bL ? 1 : -1; + } else { + + for ( i = cmp = 0; i < aL; i++ ) { + + if ( a[i] != b[i] ) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + return cmp; + } + + function subtract( a, b, aL, base ) { + var i = 0; + + // Subtract b from a. + for ( ; aL--; ) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for ( ; !a[0] && a.length > 1; a.splice(0, 1) ); + } + + // x: dividend, y: divisor. + return function ( x, y, dp, rm, base ) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if ( !xc || !xc[0] || !yc || !yc[0] ) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if ( !base ) { + base = BASE; + e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE ); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ ); + if ( yc[i] > ( xc[i] || 0 ) ) e--; + + if ( s < 0 ) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor( base / ( yc[0] + 1 ) ); + + // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1. + // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) { + if ( n > 1 ) { + yc = multiply( yc, n, base ); + xc = multiply( xc, n, base ); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice( 0, yL ); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for ( ; remL < yL; rem[remL++] = 0 ); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if ( yc[1] >= base / 2 ) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare( yc, rem, yL, remL ); + + // If divisor < remainder. + if ( cmp < 0 ) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 ); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor( rem0 / yc0 ); + + // Algorithm: + // 1. product = divisor * trial digit (n) + // 2. if product > remainder: product -= divisor, n-- + // 3. remainder -= product + // 4. if product was < remainder at 2: + // 5. compare new remainder and divisor + // 6. If remainder > divisor: remainder -= divisor, n++ + + if ( n > 1 ) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply( yc, n, base ); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder. + // Trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while ( compare( prod, rem, prodL, remL ) == 1 ) { + n--; + + // Subtract divisor from product. + subtract( prod, yL < prodL ? yz : yc, prodL, base ); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if ( n == 0 ) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if ( prodL < remL ) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract( rem, prod, remL, base ); + remL = rem.length; + + // If product was < remainder. + if ( cmp == -1 ) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while ( compare( yc, rem, yL, remL ) < 1 ) { + n++; + + // Subtract divisor from remainder. + subtract( rem, yL < remL ? yz : yc, remL, base ); + remL = rem.length; + } + } + } else if ( cmp === 0 ) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if ( rem[0] ) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [ xc[xi] ]; + remL = 1; + } + } while ( ( xi++ < xL || rem[0] != null ) && s-- ); + + more = rem[0] != null; + + // Leading zero? + if ( !qc[0] ) qc.splice(0, 1); + } + + if ( base == BASE ) { + + // To calculate q.e, first get the number of digits of qc[0]. + for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ ); + round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more ); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n is a BigNumber. + * i is the index of the last digit required (i.e. the digit that may be rounded up). + * rm is the rounding mode. + * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24. + */ + function format( n, i, rm, caller ) { + var c0, e, ne, len, str; + + rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode ) + ? rm | 0 : ROUNDING_MODE; + + if ( !n.c ) return n.toString(); + c0 = n.c[0]; + ne = n.e; + + if ( i == null ) { + str = coeffToString( n.c ); + str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG + ? toExponential( str, ne ) + : toFixedPoint( str, ne ); + } else { + n = round( new BigNumber(n), i, rm ); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString( n.c ); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) { + + // Append zeros? + for ( ; len < i; str += '0', len++ ); + str = toExponential( str, e ); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint( str, e ); + + // Append zeros? + if ( e + 1 > len ) { + if ( --i > 0 ) for ( str += '.'; i--; str += '0' ); + } else { + i += e - len; + if ( i > 0 ) { + if ( e + 1 == len ) str += '.'; + for ( ; i--; str += '0' ); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + function maxOrMin( args, method ) { + var m, n, + i = 0; + + if ( isArray( args[0] ) ) args = args[0]; + m = new BigNumber( args[0] ); + + for ( ; ++i < args.length; ) { + n = new BigNumber( args[i] ); + + // If any number is NaN, return NaN. + if ( !n.s ) { + m = n; + break; + } else if ( method.call( m, n ) ) { + m = n; + } + } + + return m; + } + + + /* + * Return true if n is an integer in range, otherwise throw. + * Use for argument validation when ERRORS is true. + */ + function intValidatorWithErrors( n, min, max, caller, name ) { + if ( n < min || n > max || n != truncate(n) ) { + raise( caller, ( name || 'decimal places' ) + + ( n < min || n > max ? ' out of range' : ' not an integer' ), n ); + } + + return true; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise( n, c, e ) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for ( ; !c[--j]; c.pop() ); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for ( j = c[0]; j >= 10; j /= 10, i++ ); + + // Overflow? + if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if ( e < MIN_EXP ) { + + // Zero. + n.c = [ n.e = 0 ]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function ( x, str, num, b ) { + var base, + s = num ? str : str.replace( whitespaceOrPlus, '' ); + + // No exception on ±Infinity or NaN. + if ( isInfinityOrNaN.test(s) ) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if ( !num ) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace( basePrefix, function ( m, p1, p2 ) { + base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' ); + } + + if ( str != s ) return new BigNumber( s, base ); + } + + // 'new BigNumber() not a number: {n}' + // 'new BigNumber() not a base {b} number: {n}' + if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str ); + x.s = null; + } + + x.c = x.e = null; + id = 0; + } + })(); + + + // Throw a BigNumber Error. + function raise( caller, msg, val ) { + var error = new Error( [ + 'new BigNumber', // 0 + 'cmp', // 1 + 'config', // 2 + 'div', // 3 + 'divToInt', // 4 + 'eq', // 5 + 'gt', // 6 + 'gte', // 7 + 'lt', // 8 + 'lte', // 9 + 'minus', // 10 + 'mod', // 11 + 'plus', // 12 + 'precision', // 13 + 'random', // 14 + 'round', // 15 + 'shift', // 16 + 'times', // 17 + 'toDigits', // 18 + 'toExponential', // 19 + 'toFixed', // 20 + 'toFormat', // 21 + 'toFraction', // 22 + 'pow', // 23 + 'toPrecision', // 24 + 'toString', // 25 + 'BigNumber' // 26 + ][caller] + '() ' + msg + ': ' + val ); + + error.name = 'BigNumber Error'; + id = 0; + throw error; + } + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round( x, sd, rm, r ) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ ); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if ( i < 0 ) { + i += LOG_BASE; + j = sd; + n = xc[ ni = 0 ]; + + // Get the rounding digit at index j of n. + rd = n / pows10[ d - j - 1 ] % 10 | 0; + } else { + ni = mathceil( ( i + 1 ) / LOG_BASE ); + + if ( ni >= xc.length ) { + + if (r) { + + // Needed by sqrt. + for ( ; xc.length <= ni; xc.push(0) ); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for ( d = 1; k >= 10; k /= 10, d++ ); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0; + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] ); + + r = rm < 4 + ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) + : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 || + rm == ( x.s < 0 ? 8 : 7 ) ); + + if ( sd < 1 || !xc[0] ) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if ( i == 0 ) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[ LOG_BASE - i ]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0; + } + + // Round up? + if (r) { + + for ( ; ; ) { + + // If the digit to be rounded up is in the first element of xc... + if ( ni == 0 ) { + + // i will be the length of xc[0] before k is added. + for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ ); + j = xc[0] += k; + for ( k = 1; j >= 10; j /= 10, k++ ); + + // if i != k the length has increased. + if ( i != k ) { + x.e++; + if ( xc[0] == BASE ) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if ( xc[ni] != BASE ) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for ( i = xc.length; xc[--i] === 0; xc.pop() ); + } + + // Overflow? Infinity. + if ( x.e > MAX_EXP ) { + x.c = x.e = null; + + // Underflow? Zero. + } else if ( x.e < MIN_EXP ) { + x.c = [ x.e = 0 ]; + } + } + + return x; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if ( x.s < 0 ) x.s = 1; + return x; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole + * number in the direction of Infinity. + */ + P.ceil = function () { + return round( new BigNumber(this), this.e + 1, 2 ); + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = P.cmp = function ( y, b ) { + id = 1; + return compare( this, new BigNumber( y, b ) ); + }; + + + /* + * Return the number of decimal places of the value of this BigNumber, or null if the value + * of this BigNumber is ±Infinity or NaN. + */ + P.decimalPlaces = P.dp = function () { + var n, v, + c = this.c; + + if ( !c ) return null; + n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); + if ( n < 0 ) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function ( y, b ) { + id = 3; + return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.divToInt = function ( y, b ) { + id = 4; + return div( this, new BigNumber( y, b ), 0, 1 ); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise returns false. + */ + P.equals = P.eq = function ( y, b ) { + id = 5; + return compare( this, new BigNumber( y, b ) ) === 0; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole + * number in the direction of -Infinity. + */ + P.floor = function () { + return round( new BigNumber(this), this.e + 1, 3 ); + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise returns false. + */ + P.greaterThan = P.gt = function ( y, b ) { + id = 6; + return compare( this, new BigNumber( y, b ) ) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise returns false. + */ + P.greaterThanOrEqualTo = P.gte = function ( y, b ) { + id = 7; + return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise returns false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = P.isInt = function () { + return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise returns false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise returns false. + */ + P.isNegative = P.isNeg = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise returns false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise returns false. + */ + P.lessThan = P.lt = function ( y, b ) { + id = 8; + return compare( this, new BigNumber( y, b ) ) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise returns false. + */ + P.lessThanOrEqualTo = P.lte = function ( y, b ) { + id = 9; + return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = P.sub = function ( y, b ) { + var i, j, t, xLTy, + x = this, + a = x.s; + + id = 10; + y = new BigNumber( y, b ); + b = y.s; + + // Either NaN? + if ( !a || !b ) return new BigNumber(NaN); + + // Signs differ? + if ( a != b ) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if ( !xe || !ye ) { + + // Either Infinity? + if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); + + // Either zero? + if ( !xc[0] || !yc[0] ) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0 ); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if ( a = xe - ye ) { + + if ( xLTy = a < 0 ) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for ( b = a; b--; t.push(0) ); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; + + for ( a = b = 0; b < j; b++ ) { + + if ( xc[b] != yc[b] ) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; + + b = ( j = yc.length ) - ( i = xc.length ); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if ( b > 0 ) for ( ; b--; xc[i++] = 0 ); + b = BASE - 1; + + // Subtract yc from xc. + for ( ; j > a; ) { + + if ( xc[--j] < yc[j] ) { + for ( i = j; i && !xc[--i]; xc[i] = b ); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for ( ; xc[0] == 0; xc.splice(0, 1), --ye ); + + // Zero? + if ( !xc[0] ) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [ y.e = 0 ]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise( y, xc, ye ); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function ( y, b ) { + var q, s, + x = this; + + id = 11; + y = new BigNumber( y, b ); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if ( !x.c || !y.s || y.c && !y.c[0] ) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if ( !y.c || x.c && !x.c[0] ) { + return new BigNumber(x); + } + + if ( MODULO_MODE == 9 ) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div( x, y, 0, 3 ); + y.s = s; + q.s *= s; + } else { + q = div( x, y, 0, MODULO_MODE ); + } + + return x.minus( q.times(y) ); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = P.neg = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = P.add = function ( y, b ) { + var t, + x = this, + a = x.s; + + id = 12; + y = new BigNumber( y, b ); + b = y.s; + + // Either NaN? + if ( !a || !b ) return new BigNumber(NaN); + + // Signs differ? + if ( a != b ) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if ( !xe || !ye ) { + + // Return ±Infinity if either ±Infinity. + if ( !xc || !yc ) return new BigNumber( a / 0 ); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 ); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if ( a = xe - ye ) { + if ( a > 0 ) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for ( ; a--; t.push(0) ); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a; + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for ( a = 0; b; ) { + a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise( y, xc, ye ); + }; + + + /* + * Return the number of significant digits of the value of this BigNumber. + * + * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + */ + P.precision = P.sd = function (z) { + var n, v, + x = this, + c = x.c; + + // 'precision() argument not a boolean or binary digit: {z}' + if ( z != null && z !== !!z && z !== 1 && z !== 0 ) { + if (ERRORS) raise( 13, 'argument' + notBool, z ); + if ( z != !!z ) z = null; + } + + if ( !c ) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if ( v = c[v] ) { + + // Subtract the number of trailing zeros of the last element. + for ( ; v % 10 == 0; v /= 10, n-- ); + + // Add the number of digits of the first element. + for ( v = c[0]; v >= 10; v /= 10, n++ ); + } + + if ( z && x.e + 1 > n ) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of + * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if + * omitted. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'round() decimal places out of range: {dp}' + * 'round() decimal places not an integer: {dp}' + * 'round() rounding mode not an integer: {rm}' + * 'round() rounding mode out of range: {rm}' + */ + P.round = function ( dp, rm ) { + var n = new BigNumber(this); + + if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) { + round( n, ~~dp + this.e + 1, rm == null || + !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 ); + } + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity + * otherwise. + * + * 'shift() argument not an integer: {k}' + * 'shift() argument out of range: {k}' + */ + P.shift = function (k) { + var n = this; + return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' ) + + // k < 1e+21, or truncate(k) will produce exponential notation. + ? n.times( '1e' + truncate(k) ) + : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER ) + ? n.s * ( k < 0 ? 0 : 1 / 0 ) + : n ); + }; + + + /* + * sqrt(-n) = N + * sqrt( N) = N + * sqrt(-I) = N + * sqrt( I) = I + * sqrt( 0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if ( s !== 1 || !c || !c[0] ) { + return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 ); + } + + // Initial estimate. + s = Math.sqrt( +x ); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if ( s == 0 || s == 1 / 0 ) { + n = coeffToString(c); + if ( ( n.length + e ) % 2 == 0 ) n += '0'; + s = Math.sqrt(n); + e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); + + if ( s == 1 / 0 ) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice( 0, n.indexOf('e') + 1 ) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber( s + '' ); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if ( r.c[0] ) { + e = r.e; + s = e + dp; + if ( s < 3 ) s = 0; + + // Newton-Raphson iteration. + for ( ; ; ) { + t = r; + r = half.times( t.plus( div( x, t, dp, 1 ) ) ); + + if ( coeffToString( t.c ).slice( 0, s ) === ( n = + coeffToString( r.c ) ).slice( 0, s ) ) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if ( r.e < e ) --s; + n = n.slice( s - 3, s + 1 ); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if ( n == '9999' || !rep && n == '4999' ) { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if ( !rep ) { + round( t, t.e + DECIMAL_PLACES + 2, 0 ); + + if ( t.times(t).eq(x) ) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) { + + // Truncate to the first rounding digit. + round( r, r.e + DECIMAL_PLACES + 2, 1 ); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber times the value of + * BigNumber(y, b). + */ + P.times = P.mul = function ( y, b ) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = ( id = 17, y = new BigNumber( y, b ) ).c; + + // Either NaN, ±Infinity or ±0? + if ( !xc || !yc || !xc[0] || !yc[0] ) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if ( !xc || !yc ) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; + + // Initialise the result array with zeros. + for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); + + base = BASE; + sqrtBase = SQRT_BASE; + + for ( i = ycL; --i >= 0; ) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for ( k = xcL, j = i + k; j > i; ) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c; + c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise( y, zc, e ); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of + * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toDigits() precision out of range: {sd}' + * 'toDigits() precision not an integer: {sd}' + * 'toDigits() rounding mode not an integer: {rm}' + * 'toDigits() rounding mode out of range: {rm}' + */ + P.toDigits = function ( sd, rm ) { + var n = new BigNumber(this); + sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0; + rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0; + return sd ? round( n, sd, rm ) : n; + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toExponential() decimal places not an integer: {dp}' + * 'toExponential() decimal places out of range: {dp}' + * 'toExponential() rounding mode not an integer: {rm}' + * 'toExponential() rounding mode out of range: {rm}' + */ + P.toExponential = function ( dp, rm ) { + return format( this, + dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 ); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toFixed() decimal places not an integer: {dp}' + * 'toFixed() decimal places out of range: {dp}' + * 'toFixed() rounding mode not an integer: {rm}' + * 'toFixed() rounding mode out of range: {rm}' + */ + P.toFixed = function ( dp, rm ) { + return format( this, dp != null && isValidInt( dp, 0, MAX, 20 ) + ? ~~dp + this.e + 1 : null, rm, 20 ); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the FORMAT object (see BigNumber.config). + * + * FORMAT = { + * decimalSeparator : '.', + * groupSeparator : ',', + * groupSize : 3, + * secondaryGroupSize : 0, + * fractionGroupSeparator : '\xA0', // non-breaking space + * fractionGroupSize : 0 + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toFormat() decimal places not an integer: {dp}' + * 'toFormat() decimal places out of range: {dp}' + * 'toFormat() rounding mode not an integer: {rm}' + * 'toFormat() rounding mode out of range: {rm}' + */ + P.toFormat = function ( dp, rm ) { + var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 ) + ? ~~dp + this.e + 1 : null, rm, 21 ); + + if ( this.c ) { + var i, + arr = str.split('.'), + g1 = +FORMAT.groupSize, + g2 = +FORMAT.secondaryGroupSize, + groupSeparator = FORMAT.groupSeparator, + intPart = arr[0], + fractionPart = arr[1], + isNeg = this.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) i = g1, g1 = g2, g2 = i, len -= i; + + if ( g1 > 0 && len > 0 ) { + i = len % g1 || g1; + intPart = intDigits.substr( 0, i ); + + for ( ; i < len; i += g1 ) { + intPart += groupSeparator + intDigits.substr( i, g1 ); + } + + if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize ) + ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ), + '$&' + FORMAT.fractionGroupSeparator ) + : fractionPart ) + : intPart; + } + + return str; + }; + + + /* + * Return a string array representing the value of this BigNumber as a simple fraction with + * an integer numerator and an integer denominator. The denominator will be a positive + * non-zero value less than or equal to the specified maximum denominator. If a maximum + * denominator is not specified, the denominator will be the lowest value necessary to + * represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator. + * + * 'toFraction() max denominator not an integer: {md}' + * 'toFraction() max denominator out of range: {md}' + */ + P.toFraction = function (md) { + var arr, d0, d2, e, exp, n, n0, q, s, + k = ERRORS, + x = this, + xc = x.c, + d = new BigNumber(ONE), + n1 = d0 = new BigNumber(ONE), + d1 = n0 = new BigNumber(ONE); + + if ( md != null ) { + ERRORS = false; + n = new BigNumber(md); + ERRORS = k; + + if ( !( k = n.isInt() ) || n.lt(ONE) ) { + + if (ERRORS) { + raise( 22, + 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md ); + } + + // ERRORS is false: + // If md is a finite non-integer >= 1, round it to an integer and use it. + md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null; + } + } + + if ( !xc ) return x.toString(); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ]; + md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for ( ; ; ) { + q = div( n, d, 0, 1 ); + d2 = d0.plus( q.times(d1) ); + if ( d2.cmp(md) == 1 ) break; + d0 = d1; + d1 = d2; + n1 = n0.plus( q.times( d2 = n1 ) ); + n0 = d2; + d = n.minus( q.times( d2 = d ) ); + n = d2; + } + + d2 = div( md.minus(d0), d1, 0, 1 ); + n0 = n0.plus( d2.times(n1) ); + d0 = d0.plus( d2.times(d1) ); + n0.s = n1.s = x.s; + e *= 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp( + div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1 + ? [ n1.toString(), d1.toString() ] + : [ n0.toString(), d0.toString() ]; + + MAX_EXP = exp; + return arr; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +this; + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber raised to the power n. + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using + * ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are positive integers, + * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0). + * + * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * [m] {number|string|BigNumber} The modulus. + * + * 'pow() exponent not an integer: {n}' + * 'pow() exponent out of range: {n}' + * + * Performs 54 loop iterations for n of 9007199254740991. + */ + P.toPower = P.pow = function ( n, m ) { + var k, y, z, + i = mathfloor( n < 0 ? -n : +n ), + x = this; + + if ( m != null ) { + id = 23; + m = new BigNumber(m); + } + + // Pass ±Infinity to Math.pow if exponent is out of range. + if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) && + ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) || + parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) { + k = Math.pow( +x, n ); + return new BigNumber( m ? k % m : k ); + } + + if (m) { + if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) { + x = x.mod(m); + } else { + z = m; + + // Nullify m so only a single mod operation is performed at the end. + m = null; + } + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + // (Using + 1.5 would give [9, 21] guard digits.) + k = mathceil( POW_PRECISION / LOG_BASE + 2 ); + } + + y = new BigNumber(ONE); + + for ( ; ; ) { + if ( i % 2 ) { + y = y.times(x); + if ( !y.c ) break; + if (k) { + if ( y.c.length > k ) y.c.length = k; + } else if (m) { + y = y.mod(m); + } + } + + i = mathfloor( i / 2 ); + if ( !i ) break; + x = x.times(x); + if (k) { + if ( x.c && x.c.length > k ) x.c.length = k; + } else if (m) { + x = x.mod(m); + } + } + + if (m) return y; + if ( n < 0 ) y = ONE.div(y); + + return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toPrecision() precision not an integer: {sd}' + * 'toPrecision() precision out of range: {sd}' + * 'toPrecision() rounding mode not an integer: {rm}' + * 'toPrecision() rounding mode out of range: {rm}' + */ + P.toPrecision = function ( sd, rm ) { + return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' ) + ? sd | 0 : null, rm, 24 ); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to 64 inclusive. + * + * 'toString() base not an integer: {b}' + * 'toString() base out of range: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if ( e === null ) { + + if (s) { + str = 'Infinity'; + if ( s < 0 ) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + str = coeffToString( n.c ); + + if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential( str, e ) + : toFixedPoint( str, e ); + } else { + str = convertBase( toFixedPoint( str, e ), b | 0, 10, s ); + } + + if ( s < 0 && n.c[0] ) str = '-' + str; + } + + return str; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole + * number. + */ + P.truncated = P.trunc = function () { + return round( new BigNumber(this), this.e + 1, 1 ); + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + var str, + n = this, + e = n.e; + + if ( e === null ) return n.toString(); + + str = coeffToString( n.c ); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential( str, e ) + : toFixedPoint( str, e ); + + return n.s < 0 ? '-' + str : str; + }; + + + P.isBigNumber = true; + + if ( config != null ) BigNumber.config(config); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for ( ; i < j; ) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for ( ; z--; s = '0' + s ); + r += s; + } + + // Determine trailing zeros. + for ( j = r.length; r.charCodeAt(--j) === 48; ); + return r.slice( 0, j + 1 || 1 ); + } + + + // Compare the value of BigNumbers x and y. + function compare( x, y ) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if ( !i || !j ) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if ( a || b ) return a ? b ? 0 : -j : i; + + // Signs differ? + if ( i != j ) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if ( !b ) return k > l ^ a ? 1 : -1; + + j = ( k = xc.length ) < ( l = yc.length ) ? k : l; + + // Compare digit by digit. + for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Return true if n is a valid number in range, otherwise false. + * Use for argument validation when ERRORS is false. + * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10. + */ + function intValidatorNoErrors( n, min, max ) { + return ( n = truncate(n) ) >= min && n <= max; + } + + + function isArray(obj) { + return Object.prototype.toString.call(obj) == '[object Array]'; + } + + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. convertBase('255', 10, 16) returns [15, 15]. + * Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut( str, baseIn, baseOut ) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for ( ; i < len; ) { + for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn ); + arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) ); + + for ( ; j < arr.length; j++ ) { + + if ( arr[j] > baseOut - 1 ) { + if ( arr[j + 1] == null ) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + + function toExponential( str, e ) { + return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) + + ( e < 0 ? 'e' : 'e+' ) + e; + } + + + function toFixedPoint( str, e ) { + var len, z; + + // Negative exponent? + if ( e < 0 ) { + + // Prepend zeros. + for ( z = '0.'; ++e; z += '0' ); + str = z + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if ( ++e > len ) { + for ( z = '0', e -= len; --e; z += '0' ); + str += z; + } else if ( e < len ) { + str = str.slice( 0, e ) + '.' + str.slice(e); + } + } + + return str; + } + + + function truncate(n) { + n = parseFloat(n); + return n < 0 ? mathceil(n) : mathfloor(n); + } + + + // EXPORT + + + BigNumber = constructorFactory(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + + // AMD. + if ( typeof define == 'function' && define.amd ) { + define( function () { return BigNumber; } ); + + // Node.js and other environments that support module.exports. + } else if ( typeof module != 'undefined' && module.exports ) { + module.exports = BigNumber; + + // Browser. + } else { + if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')(); + globalObj.BigNumber = BigNumber; + } +})(this); diff --git a/node_modules/bignumber.js/bignumber.js.map b/node_modules/bignumber.js/bignumber.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c993524a3b34339c0ac003ed77146813bdd54fe1 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bignumber.min.js","sources":["bignumber.js"],"names":["globalObj","constructorFactory","config","BigNumber","n","b","c","e","i","num","len","str","x","this","ERRORS","raise","isValidInt","id","round","DECIMAL_PLACES","ROUNDING_MODE","RegExp","ALPHABET","slice","test","parseNumeric","s","replace","length","tooManyDigits","charCodeAt","convertBase","isNumeric","indexOf","search","substring","MAX_SAFE_INTEGER","mathfloor","MAX_EXP","MIN_EXP","LOG_BASE","push","baseOut","baseIn","sign","d","k","r","xc","y","dp","rm","toLowerCase","POW_PRECISION","pow","toBaseOut","toFixedPoint","coeffToString","pop","div","concat","charAt","format","caller","c0","ne","roundingMode","toString","TO_EXP_NEG","toExponential","maxOrMin","args","method","m","isArray","call","intValidatorWithErrors","min","max","name","truncate","normalise","j","msg","val","error","Error","sd","ni","rd","pows10","POWS_TEN","out","mathceil","BASE","P","prototype","ONE","TO_EXP_POS","CRYPTO","MODULO_MODE","FORMAT","decimalSeparator","groupSeparator","groupSize","secondaryGroupSize","fractionGroupSeparator","fractionGroupSize","another","ROUND_UP","ROUND_DOWN","ROUND_CEIL","ROUND_FLOOR","ROUND_HALF_UP","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_HALF_CEIL","ROUND_HALF_FLOOR","EUCLID","set","v","p","a","arguments","o","has","hasOwnProperty","MAX","intValidatorNoErrors","notBool","crypto","getRandomValues","randomBytes","lt","gt","random","pow2_53","random53bitInt","Math","rand","Uint32Array","copy","splice","multiply","base","temp","xlo","xhi","carry","klo","SQRT_BASE","khi","compare","aL","bL","cmp","subtract","more","prod","prodL","q","qc","rem","remL","rem0","xi","xL","yc0","yL","yz","yc","NaN","bitFloor","basePrefix","dotAfter","dotBefore","isInfinityOrNaN","whitespaceOrPlus","isNaN","p1","p2","absoluteValue","abs","ceil","comparedTo","decimalPlaces","dividedBy","dividedToIntegerBy","divToInt","equals","eq","floor","greaterThan","greaterThanOrEqualTo","gte","isFinite","isInteger","isInt","isNegative","isNeg","isZero","lessThan","lessThanOrEqualTo","lte","minus","sub","t","xLTy","plus","xe","ye","reverse","modulo","mod","times","negated","neg","add","precision","z","shift","squareRoot","sqrt","rep","half","mul","xcL","ycL","ylo","yhi","zc","sqrtBase","toDigits","toFixed","toFormat","arr","split","g1","g2","intPart","fractionPart","intDigits","substr","toFraction","md","d0","d2","exp","n0","n1","d1","toNumber","toPower","parseFloat","toPrecision","truncated","trunc","valueOf","toJSON","isBigNumber","l","obj","Object","arrL","define","amd","module","exports","self","Function"],"mappings":";CAEC,SAAWA,GACR,YAqCA,SAASC,GAAmBC,GAiHxB,QAASC,GAAWC,EAAGC,GACnB,GAAIC,GAAGC,EAAGC,EAAGC,EAAKC,EAAKC,EACnBC,EAAIC,IAGR,MAAQD,YAAaT,IAIjB,MADIW,IAAQC,EAAO,GAAI,+BAAgCX,GAChD,GAAID,GAAWC,EAAGC,EAK7B,IAAU,MAALA,GAAcW,EAAYX,EAAG,EAAG,GAAIY,EAAI,QA4BtC,CAMH,GALAZ,EAAQ,EAAJA,EACJM,EAAMP,EAAI,GAIA,IAALC,EAED,MADAO,GAAI,GAAIT,GAAWC,YAAaD,GAAYC,EAAIO,GACzCO,EAAON,EAAGO,EAAiBP,EAAEL,EAAI,EAAGa,EAK/C,KAAOX,EAAkB,gBAALL,KAAuB,EAAJA,GAAS,IAC7C,GAAMiB,QAAQ,OAAUf,EAAI,IAAMgB,EAASC,MAAO,EAAGlB,GAAM,MAC1D,SAAWC,EAAI,MAAU,GAAJD,EAAS,IAAM,IAAOmB,KAAKb,GAChD,MAAOc,GAAcb,EAAGD,EAAKF,EAAKJ,EAGlCI,IACAG,EAAEc,EAAY,EAAR,EAAItB,GAAUO,EAAMA,EAAIY,MAAM,GAAI,IAAO,EAE1CT,GAAUH,EAAIgB,QAAS,YAAa,IAAKC,OAAS,IAGnDb,EAAOE,EAAIY,EAAezB,GAI9BK,GAAM,GAENG,EAAEc,EAA0B,KAAtBf,EAAImB,WAAW,IAAcnB,EAAMA,EAAIY,MAAM,GAAI,IAAO,EAGlEZ,EAAMoB,EAAapB,EAAK,GAAIN,EAAGO,EAAEc,OA9DmB,CAGpD,GAAKtB,YAAaD,GAKd,MAJAS,GAAEc,EAAItB,EAAEsB,EACRd,EAAEL,EAAIH,EAAEG,EACRK,EAAEN,GAAMF,EAAIA,EAAEE,GAAMF,EAAEmB,QAAUnB,OAChCa,EAAK,EAIT,KAAOR,EAAkB,gBAALL,KAAuB,EAAJA,GAAS,EAAI,CAIhD,GAHAQ,EAAEc,EAAY,EAAR,EAAItB,GAAUA,GAAKA,EAAG,IAAO,EAG9BA,MAAQA,EAAI,CACb,IAAMG,EAAI,EAAGC,EAAIJ,EAAGI,GAAK,GAAIA,GAAK,GAAID,KAItC,MAHAK,GAAEL,EAAIA,EACNK,EAAEN,GAAKF,QACPa,EAAK,GAITN,EAAMP,EAAI,OACP,CACH,IAAM4B,EAAUR,KAAMb,EAAMP,EAAI,IAAO,MAAOqB,GAAcb,EAAGD,EAAKF,EACpEG,GAAEc,EAA0B,KAAtBf,EAAImB,WAAW,IAAcnB,EAAMA,EAAIY,MAAM,GAAI,IAAO,GAwDtE,KAhBOhB,EAAII,EAAIsB,QAAQ,MAAS,KAAKtB,EAAMA,EAAIgB,QAAS,IAAK,MAGtDnB,EAAIG,EAAIuB,OAAQ,OAAW,GAGrB,EAAJ3B,IAAQA,EAAIC,GACjBD,IAAMI,EAAIY,MAAOf,EAAI,GACrBG,EAAMA,EAAIwB,UAAW,EAAG3B,IACZ,EAAJD,IAGRA,EAAII,EAAIiB,QAINpB,EAAI,EAAyB,KAAtBG,EAAImB,WAAWtB,GAAWA,KAGvC,IAAME,EAAMC,EAAIiB,OAAkC,KAA1BjB,EAAImB,aAAapB,KAGzC,GAFAC,EAAMA,EAAIY,MAAOf,EAAGE,EAAM,GActB,GAXAA,EAAMC,EAAIiB,OAILnB,GAAOK,GAAUJ,EAAM,KAAQN,EAAIgC,GAAoBhC,IAAMiC,EAAUjC,KACxEW,EAAOE,EAAIY,EAAejB,EAAEc,EAAItB,GAGpCG,EAAIA,EAAIC,EAAI,EAGPD,EAAI+B,EAGL1B,EAAEN,EAAIM,EAAEL,EAAI,SAGT,IAASgC,EAAJhC,EAGRK,EAAEN,GAAMM,EAAEL,EAAI,OACX,CAWH,GAVAK,EAAEL,EAAIA,EACNK,EAAEN,KAMFE,GAAMD,EAAI,GAAMiC,EACP,EAAJjC,IAAQC,GAAKgC,GAET9B,EAAJF,EAAU,CAGX,IAFIA,GAAGI,EAAEN,EAAEmC,MAAO9B,EAAIY,MAAO,EAAGf,IAE1BE,GAAO8B,EAAc9B,EAAJF,GACnBI,EAAEN,EAAEmC,MAAO9B,EAAIY,MAAOf,EAAGA,GAAKgC,GAGlC7B,GAAMA,EAAIY,MAAMf,GAChBA,EAAIgC,EAAW7B,EAAIiB,WAEnBpB,IAAKE,CAGT,MAAQF,IAAKG,GAAO,KACpBC,EAAEN,EAAEmC,MAAO9B,OAKfC,GAAEN,GAAMM,EAAEL,EAAI,EAGlBU,GAAK,EA2VT,QAASc,GAAapB,EAAK+B,EAASC,EAAQC,GACxC,GAAIC,GAAGtC,EAAGuC,EAAGC,EAAGnC,EAAGoC,EAAIC,EACnBzC,EAAIG,EAAIsB,QAAS,KACjBiB,EAAK/B,EACLgC,EAAK/B,CA0BT,KAxBc,GAATuB,IAAchC,EAAMA,EAAIyC,eAGxB5C,GAAK,IACNsC,EAAIO,EAGJA,EAAgB,EAChB1C,EAAMA,EAAIgB,QAAS,IAAK,IACxBsB,EAAI,GAAI9C,GAAUwC,GAClB/B,EAAIqC,EAAEK,IAAK3C,EAAIiB,OAASpB,GACxB6C,EAAgBP,EAIhBG,EAAE3C,EAAIiD,EAAWC,EAAcC,EAAe7C,EAAEN,GAAKM,EAAEL,GAAK,GAAImC,GAChEO,EAAE1C,EAAI0C,EAAE3C,EAAEsB,QAIdoB,EAAKO,EAAW5C,EAAKgC,EAAQD,GAC7BnC,EAAIuC,EAAIE,EAAGpB,OAGQ,GAAXoB,IAAKF,GAASE,EAAGU,OACzB,IAAMV,EAAG,GAAK,MAAO,GA2BrB,IAzBS,EAAJxC,IACCD,GAEFK,EAAEN,EAAI0C,EACNpC,EAAEL,EAAIA,EAGNK,EAAEc,EAAIkB,EACNhC,EAAI+C,EAAK/C,EAAGqC,EAAGC,EAAIC,EAAIT,GACvBM,EAAKpC,EAAEN,EACPyC,EAAInC,EAAEmC,EACNxC,EAAIK,EAAEL,GAGVsC,EAAItC,EAAI2C,EAAK,EAGb1C,EAAIwC,EAAGH,GACPC,EAAIJ,EAAU,EACdK,EAAIA,GAAS,EAAJF,GAAsB,MAAbG,EAAGH,EAAI,GAEzBE,EAAS,EAALI,GAAgB,MAAL3C,GAAauC,KAAe,GAANI,GAAWA,IAAQvC,EAAEc,EAAI,EAAI,EAAI,IACzDlB,EAAIsC,GAAKtC,GAAKsC,IAAY,GAANK,GAAWJ,GAAW,GAANI,GAAuB,EAAZH,EAAGH,EAAI,IACtDM,IAAQvC,EAAEc,EAAI,EAAI,EAAI,IAE1B,EAAJmB,IAAUG,EAAG,GAGdrC,EAAMoC,EAAIS,EAAc,KAAMN,GAAO,QAClC,CAGH,GAFAF,EAAGpB,OAASiB,EAERE,EAGA,MAAQL,IAAWM,IAAKH,GAAKH,GACzBM,EAAGH,GAAK,EAEFA,MACAtC,EACFyC,GAAM,GAAGY,OAAOZ,GAM5B,KAAMF,EAAIE,EAAGpB,QAASoB,IAAKF,KAG3B,IAAMtC,EAAI,EAAGG,EAAM,GAASmC,GAALtC,EAAQG,GAAOW,EAASuC,OAAQb,EAAGxC,OAC1DG,EAAM6C,EAAc7C,EAAKJ,GAI7B,MAAOI,GA4QX,QAASmD,GAAQ1D,EAAGI,EAAG2C,EAAIY,GACvB,GAAIC,GAAIzD,EAAG0D,EAAIvD,EAAKC,CAKpB,IAHAwC,EAAW,MAANA,GAAcnC,EAAYmC,EAAI,EAAG,EAAGY,EAAQG,GACxC,EAALf,EAAS/B,GAEPhB,EAAEE,EAAI,MAAOF,GAAE+D,UAIrB,IAHAH,EAAK5D,EAAEE,EAAE,GACT2D,EAAK7D,EAAEG,EAEG,MAALC,EACDG,EAAM8C,EAAerD,EAAEE,GACvBK,EAAgB,IAAVoD,GAA0B,IAAVA,GAAsBK,GAANH,EAClCI,EAAe1D,EAAKsD,GACpBT,EAAc7C,EAAKsD,OAevB,IAbA7D,EAAIc,EAAO,GAAIf,GAAUC,GAAII,EAAG2C,GAGhC5C,EAAIH,EAAEG,EAENI,EAAM8C,EAAerD,EAAEE,GACvBI,EAAMC,EAAIiB,OAOK,IAAVmC,GAA0B,IAAVA,IAAuBxD,GAALC,GAAe4D,GAAL7D,GAAoB,CAGjE,KAAcC,EAANE,EAASC,GAAO,IAAKD,KAC7BC,EAAM0D,EAAe1D,EAAKJ,OAQ1B,IAJAC,GAAKyD,EACLtD,EAAM6C,EAAc7C,EAAKJ,GAGpBA,EAAI,EAAIG,GACT,KAAOF,EAAI,EAAI,IAAMG,GAAO,IAAKH,IAAKG,GAAO,UAG7C,IADAH,GAAKD,EAAIG,EACJF,EAAI,EAEL,IADKD,EAAI,GAAKG,IAAMC,GAAO,KACnBH,IAAKG,GAAO,KAMpC,MAAOP,GAAEsB,EAAI,GAAKsC,EAAK,IAAMrD,EAAMA,EAKvC,QAAS2D,GAAUC,EAAMC,GACrB,GAAIC,GAAGrE,EACHI,EAAI,CAKR,KAHKkE,EAASH,EAAK,MAAOA,EAAOA,EAAK,IACtCE,EAAI,GAAItE,GAAWoE,EAAK,MAEd/D,EAAI+D,EAAK3C,QAAU,CAIzB,GAHAxB,EAAI,GAAID,GAAWoE,EAAK/D,KAGlBJ,EAAEsB,EAAI,CACR+C,EAAIrE,CACJ,OACQoE,EAAOG,KAAMF,EAAGrE,KACxBqE,EAAIrE,GAIZ,MAAOqE,GAQX,QAASG,GAAwBxE,EAAGyE,EAAKC,EAAKf,EAAQgB,GAMlD,OALSF,EAAJzE,GAAWA,EAAI0E,GAAO1E,GAAK4E,EAAS5E,KACrCW,EAAOgD,GAAUgB,GAAQ,mBACjBF,EAAJzE,GAAWA,EAAI0E,EAAM,gBAAkB,mBAAqB1E,IAG7D,EAQX,QAAS6E,GAAW7E,EAAGE,EAAGC,GAKtB,IAJA,GAAIC,GAAI,EACJ0E,EAAI5E,EAAEsB,QAGDtB,IAAI4E,GAAI5E,EAAEoD,OAGnB,IAAMwB,EAAI5E,EAAE,GAAI4E,GAAK,GAAIA,GAAK,GAAI1E,KAkBlC,OAfOD,EAAIC,EAAID,EAAIiC,EAAW,GAAMF,EAGhClC,EAAEE,EAAIF,EAAEG,EAAI,KAGAgC,EAAJhC,EAGRH,EAAEE,GAAMF,EAAEG,EAAI,IAEdH,EAAEG,EAAIA,EACNH,EAAEE,EAAIA,GAGHF,EAmDX,QAASW,GAAOgD,EAAQoB,EAAKC,GACzB,GAAIC,GAAQ,GAAIC,QACZ,gBACA,MACA,SACA,MACA,WACA,KACA,KACA,MACA,KACA,MACA,QACA,MACA,OACA,YACA,SACA,QACA,QACA,QACA,WACA,gBACA,UACA,WACA,aACA,MACA,cACA,WACA,aACFvB,GAAU,MAAQoB,EAAM,KAAOC,EAIjC,MAFAC,GAAMN,KAAO,kBACb9D,EAAK,EACCoE,EAQV,QAASnE,GAAON,EAAG2E,EAAIpC,EAAIJ,GACvB,GAAIF,GAAGrC,EAAG0E,EAAGpC,EAAG1C,EAAGoF,EAAIC,EACnBzC,EAAKpC,EAAEN,EACPoF,EAASC,CAGb,IAAI3C,EAAI,CAQJ4C,EAAK,CAGD,IAAM/C,EAAI,EAAGC,EAAIE,EAAG,GAAIF,GAAK,GAAIA,GAAK,GAAID,KAI1C,GAHArC,EAAI+E,EAAK1C,EAGA,EAAJrC,EACDA,GAAKgC,EACL0C,EAAIK,EACJnF,EAAI4C,EAAIwC,EAAK,GAGbC,EAAKrF,EAAIsF,EAAQ7C,EAAIqC,EAAI,GAAM,GAAK,MAIpC,IAFAM,EAAKK,GAAYrF,EAAI,GAAMgC,GAEtBgD,GAAMxC,EAAGpB,OAAS,CAEnB,IAAImB,EASA,KAAM6C,EANN,MAAQ5C,EAAGpB,QAAU4D,EAAIxC,EAAGP,KAAK,IACjCrC,EAAIqF,EAAK,EACT5C,EAAI,EACJrC,GAAKgC,EACL0C,EAAI1E,EAAIgC,EAAW,MAIpB,CAIH,IAHApC,EAAI0C,EAAIE,EAAGwC,GAGL3C,EAAI,EAAGC,GAAK,GAAIA,GAAK,GAAID,KAG/BrC,GAAKgC,EAIL0C,EAAI1E,EAAIgC,EAAWK,EAGnB4C,EAAS,EAAJP,EAAQ,EAAI9E,EAAIsF,EAAQ7C,EAAIqC,EAAI,GAAM,GAAK,EAmBxD,GAfAnC,EAAIA,GAAU,EAALwC,GAKO,MAAdvC,EAAGwC,EAAK,KAAoB,EAAJN,EAAQ9E,EAAIA,EAAIsF,EAAQ7C,EAAIqC,EAAI,IAE1DnC,EAAS,EAALI,GACEsC,GAAM1C,KAAe,GAANI,GAAWA,IAAQvC,EAAEc,EAAI,EAAI,EAAI,IAClD+D,EAAK,GAAW,GAANA,IAAmB,GAANtC,GAAWJ,GAAW,GAANI,IAGnC3C,EAAI,EAAI0E,EAAI,EAAI9E,EAAIsF,EAAQ7C,EAAIqC,GAAM,EAAIlC,EAAGwC,EAAK,IAAO,GAAO,GAClErC,IAAQvC,EAAEc,EAAI,EAAI,EAAI,IAElB,EAAL6D,IAAWvC,EAAG,GAiBf,MAhBAA,GAAGpB,OAAS,EAERmB,GAGAwC,GAAM3E,EAAEL,EAAI,EAGZyC,EAAG,GAAK0C,GAAUlD,EAAW+C,EAAK/C,GAAaA,GAC/C5B,EAAEL,GAAKgF,GAAM,GAIbvC,EAAG,GAAKpC,EAAEL,EAAI,EAGXK,CAkBX,IAdU,GAALJ,GACDwC,EAAGpB,OAAS4D,EACZ1C,EAAI,EACJ0C,MAEAxC,EAAGpB,OAAS4D,EAAK,EACjB1C,EAAI4C,EAAQlD,EAAWhC,GAIvBwC,EAAGwC,GAAMN,EAAI,EAAI7C,EAAWjC,EAAIsF,EAAQ7C,EAAIqC,GAAMQ,EAAOR,IAAOpC,EAAI,GAIpEC,EAEA,OAAY,CAGR,GAAW,GAANyC,EAAU,CAGX,IAAMhF,EAAI,EAAG0E,EAAIlC,EAAG,GAAIkC,GAAK,GAAIA,GAAK,GAAI1E,KAE1C,IADA0E,EAAIlC,EAAG,IAAMF,EACPA,EAAI,EAAGoC,GAAK,GAAIA,GAAK,GAAIpC,KAG1BtC,GAAKsC,IACNlC,EAAEL,IACGyC,EAAG,IAAM8C,IAAO9C,EAAG,GAAK,GAGjC,OAGA,GADAA,EAAGwC,IAAO1C,EACLE,EAAGwC,IAAOM,EAAO,KACtB9C,GAAGwC,KAAQ,EACX1C,EAAI,EAMhB,IAAMtC,EAAIwC,EAAGpB,OAAoB,IAAZoB,IAAKxC,GAAUwC,EAAGU,QAItC9C,EAAEL,EAAI+B,EACP1B,EAAEN,EAAIM,EAAEL,EAAI,KAGJK,EAAEL,EAAIgC,IACd3B,EAAEN,GAAMM,EAAEL,EAAI,IAItB,MAAOK,GA9zCX,GAAI+C,GAAKlC,EAGLR,EAAK,EACL8E,EAAI5F,EAAU6F,UACdC,EAAM,GAAI9F,GAAU,GAYpBgB,EAAiB,GAejBC,EAAgB,EAMhBgD,EAAa,GAIb8B,EAAa,GAMb3D,EAAU,KAKVD,EAAU,IAGVxB,GAAS,EAGTE,EAAa4D,EAGbuB,GAAS,EAoBTC,EAAc,EAId/C,EAAgB,EAGhBgD,GACIC,iBAAkB,IAClBC,eAAgB,IAChBC,UAAW,EACXC,mBAAoB,EACpBC,uBAAwB,IACxBC,kBAAmB,EAm3E3B,OA9rEAxG,GAAUyG,QAAU3G,EAEpBE,EAAU0G,SAAW,EACrB1G,EAAU2G,WAAa,EACvB3G,EAAU4G,WAAa,EACvB5G,EAAU6G,YAAc,EACxB7G,EAAU8G,cAAgB,EAC1B9G,EAAU+G,gBAAkB,EAC5B/G,EAAUgH,gBAAkB,EAC5BhH,EAAUiH,gBAAkB,EAC5BjH,EAAUkH,iBAAmB,EAC7BlH,EAAUmH,OAAS,EAoCnBnH,EAAUD,OAASC,EAAUoH,IAAM,WAC/B,GAAIC,GAAGC,EACHjH,EAAI,EACJuC,KACA2E,EAAIC,UACJC,EAAIF,EAAE,GACNG,EAAMD,GAAiB,gBAALA,GACd,WAAc,MAAKA,GAAEE,eAAeL,GAA4B,OAAdD,EAAII,EAAEH,IAA1C,QACd,WAAc,MAAKC,GAAE9F,OAASpB,EAA6B,OAAhBgH,EAAIE,EAAElH,MAAnC,OAuHtB,OAlHKqH,GAAKJ,EAAI,mBAAsBzG,EAAYwG,EAAG,EAAGO,EAAK,EAAGN,KAC1DtG,EAAqB,EAAJqG,GAErBzE,EAAE0E,GAAKtG,EAKF0G,EAAKJ,EAAI,kBAAqBzG,EAAYwG,EAAG,EAAG,EAAG,EAAGC,KACvDrG,EAAoB,EAAJoG,GAEpBzE,EAAE0E,GAAKrG,EAMFyG,EAAKJ,EAAI,oBAEL/C,EAAQ8C,GACJxG,EAAYwG,EAAE,IAAKO,EAAK,EAAG,EAAGN,IAAOzG,EAAYwG,EAAE,GAAI,EAAGO,EAAK,EAAGN,KACnErD,EAAoB,EAAPoD,EAAE,GACftB,EAAoB,EAAPsB,EAAE,IAEXxG,EAAYwG,GAAIO,EAAKA,EAAK,EAAGN,KACrCrD,IAAgB8B,EAAkC,GAAf,EAAJsB,GAASA,EAAIA,MAGpDzE,EAAE0E,IAAOrD,EAAY8B,GAOhB2B,EAAKJ,EAAI,WAEL/C,EAAQ8C,GACJxG,EAAYwG,EAAE,IAAKO,EAAK,GAAI,EAAGN,IAAOzG,EAAYwG,EAAE,GAAI,EAAGO,EAAK,EAAGN,KACpElF,EAAiB,EAAPiF,EAAE,GACZlF,EAAiB,EAAPkF,EAAE,IAERxG,EAAYwG,GAAIO,EAAKA,EAAK,EAAGN,KAC5B,EAAJD,EAAQjF,IAAaD,EAA+B,GAAf,EAAJkF,GAASA,EAAIA,IAC1C1G,GAAQC,EAAO,EAAG0G,EAAI,kBAAmBD,KAG1DzE,EAAE0E,IAAOlF,EAASD,GAIbuF,EAAKJ,EAAI,YAELD,MAAQA,GAAW,IAANA,GAAiB,IAANA,GACzBvG,EAAK,EACLD,GAAeF,IAAW0G,GAAM5C,EAAyBoD,GAClDlH,GACPC,EAAO,EAAG0G,EAAIQ,EAAST,IAG/BzE,EAAE0E,GAAK3G,EAKF+G,EAAKJ,EAAI,YAELD,KAAM,GAAQA,KAAM,GAAe,IAANA,GAAiB,IAANA,EACrCA,GACAA,EAAqB,mBAAVU,SACLV,GAAKU,SAAWA,OAAOC,iBAAmBD,OAAOE,aACnDjC,GAAS,EACFrF,EACPC,EAAO,EAAG,qBAAsByG,EAAI,OAASU,QAE7C/B,GAAS,GAGbA,GAAS,EAENrF,GACPC,EAAO,EAAG0G,EAAIQ,EAAST,IAG/BzE,EAAE0E,GAAKtB,EAKF0B,EAAKJ,EAAI,gBAAmBzG,EAAYwG,EAAG,EAAG,EAAG,EAAGC,KACrDrB,EAAkB,EAAJoB,GAElBzE,EAAE0E,GAAKrB,EAKFyB,EAAKJ,EAAI,kBAAqBzG,EAAYwG,EAAG,EAAGO,EAAK,EAAGN,KACzDpE,EAAoB,EAAJmE,GAEpBzE,EAAE0E,GAAKpE,EAIFwE,EAAKJ,EAAI,YAEO,gBAALD,GACRnB,EAASmB,EACF1G,GACPC,EAAO,EAAG0G,EAAI,iBAAkBD,IAGxCzE,EAAE0E,GAAKpB,EAEAtD,GASX5C,EAAU2E,IAAM,WAAc,MAAOR,GAAUqD,UAAW5B,EAAEsC,KAQ5DlI,EAAU0E,IAAM,WAAc,MAAOP,GAAUqD,UAAW5B,EAAEuC,KAc5DnI,EAAUoI,OAAS,WACf,GAAIC,GAAU,iBAMVC,EAAkBC,KAAKH,SAAWC,EAAW,QAC7C,WAAc,MAAOnG,GAAWqG,KAAKH,SAAWC,IAChD,WAAc,MAA2C,UAAlB,WAAhBE,KAAKH,SAAwB,IACjC,QAAhBG,KAAKH,SAAsB,GAElC,OAAO,UAAUrF,GACb,GAAIwE,GAAGrH,EAAGE,EAAGuC,EAAG0E,EACZhH,EAAI,EACJF,KACAqI,EAAO,GAAIxI,GAAU8F,EAKzB,IAHA/C,EAAW,MAANA,GAAelC,EAAYkC,EAAI,EAAG6E,EAAK,IAA6B,EAAL7E,EAAjB/B,EACnD2B,EAAI+C,EAAU3C,EAAKV,GAEf2D,EAGA,GAAI+B,OAAOC,gBAAiB,CAIxB,IAFAT,EAAIQ,OAAOC,gBAAiB,GAAIS,aAAa9F,GAAK,IAEtCA,EAAJtC,GAQJgH,EAAW,OAAPE,EAAElH,IAAgBkH,EAAElH,EAAI,KAAO,IAM9BgH,GAAK,MACNnH,EAAI6H,OAAOC,gBAAiB,GAAIS,aAAY,IAC5ClB,EAAElH,GAAKH,EAAE,GACTqH,EAAElH,EAAI,GAAKH,EAAE,KAKbC,EAAEmC,KAAM+E,EAAI,MACZhH,GAAK,EAGbA,GAAIsC,EAAI,MAGL,IAAIoF,OAAOE,YAAa,CAK3B,IAFAV,EAAIQ,OAAOE,YAAatF,GAAK,GAEjBA,EAAJtC,GAMJgH,EAAsB,iBAAP,GAAPE,EAAElH,IAA6C,cAAXkH,EAAElH,EAAI,GAC/B,WAAXkH,EAAElH,EAAI,GAAkC,SAAXkH,EAAElH,EAAI,IACnCkH,EAAElH,EAAI,IAAM,KAASkH,EAAElH,EAAI,IAAM,GAAMkH,EAAElH,EAAI,GAEhDgH,GAAK,KACNU,OAAOE,YAAY,GAAGS,KAAMnB,EAAGlH,IAI/BF,EAAEmC,KAAM+E,EAAI,MACZhH,GAAK,EAGbA,GAAIsC,EAAI,MAERqD,IAAS,EACLrF,GAAQC,EAAO,GAAI,qBAAsBmH,OAKrD,KAAK/B,EAED,KAAYrD,EAAJtC,GACJgH,EAAIiB,IACK,KAAJjB,IAAWlH,EAAEE,KAAOgH,EAAI,KAcrC,KAVA1E,EAAIxC,IAAIE,GACR0C,GAAMV,EAGDM,GAAKI,IACNsE,EAAI7B,EAASnD,EAAWU,GACxB5C,EAAEE,GAAK6B,EAAWS,EAAI0E,GAAMA,GAIf,IAATlH,EAAEE,GAAUF,EAAEoD,MAAOlD,KAG7B,GAAS,EAAJA,EACDF,GAAMC,EAAI,OACP,CAGH,IAAMA,EAAI,GAAc,IAATD,EAAE,GAAUA,EAAEwI,OAAO,EAAG,GAAIvI,GAAKiC,GAGhD,IAAMhC,EAAI,EAAGgH,EAAIlH,EAAE,GAAIkH,GAAK,GAAIA,GAAK,GAAIhH,KAGhCgC,EAAJhC,IAAeD,GAAKiC,EAAWhC,GAKxC,MAFAmI,GAAKpI,EAAIA,EACToI,EAAKrI,EAAIA,EACFqI,MAqGfhF,EAAM,WAGF,QAASoF,GAAUnI,EAAGkC,EAAGkG,GACrB,GAAIvE,GAAGwE,EAAMC,EAAKC,EACdC,EAAQ,EACR5I,EAAII,EAAEgB,OACNyH,EAAMvG,EAAIwG,EACVC,EAAMzG,EAAIwG,EAAY,CAE1B,KAAM1I,EAAIA,EAAEW,QAASf,KACjB0I,EAAMtI,EAAEJ,GAAK8I,EACbH,EAAMvI,EAAEJ,GAAK8I,EAAY,EACzB7E,EAAI8E,EAAML,EAAMC,EAAME,EACtBJ,EAAOI,EAAMH,EAAUzE,EAAI6E,EAAcA,EAAcF,EACvDA,GAAUH,EAAOD,EAAO,IAAQvE,EAAI6E,EAAY,GAAMC,EAAMJ,EAC5DvI,EAAEJ,GAAKyI,EAAOD,CAKlB,OAFII,KAAOxI,GAAKwI,GAAOxF,OAAOhD,IAEvBA,EAGX,QAAS4I,GAAS9B,EAAGrH,EAAGoJ,EAAIC,GACxB,GAAIlJ,GAAGmJ,CAEP,IAAKF,GAAMC,EACPC,EAAMF,EAAKC,EAAK,EAAI,OAGpB,KAAMlJ,EAAImJ,EAAM,EAAOF,EAAJjJ,EAAQA,IAEvB,GAAKkH,EAAElH,IAAMH,EAAEG,GAAK,CAChBmJ,EAAMjC,EAAElH,GAAKH,EAAEG,GAAK,EAAI,EACxB,OAIZ,MAAOmJ,GAGX,QAASC,GAAUlC,EAAGrH,EAAGoJ,EAAIT,GAIzB,IAHA,GAAIxI,GAAI,EAGAiJ,KACJ/B,EAAE+B,IAAOjJ,EACTA,EAAIkH,EAAE+B,GAAMpJ,EAAEoJ,GAAM,EAAI,EACxB/B,EAAE+B,GAAMjJ,EAAIwI,EAAOtB,EAAE+B,GAAMpJ,EAAEoJ,EAIjC,OAAS/B,EAAE,IAAMA,EAAE9F,OAAS,EAAG8F,EAAEoB,OAAO,EAAG,KAI/C,MAAO,UAAWlI,EAAGqC,EAAGC,EAAIC,EAAI6F,GAC5B,GAAIW,GAAKpJ,EAAGC,EAAGqJ,EAAMzJ,EAAG0J,EAAMC,EAAOC,EAAGC,EAAIC,EAAKC,EAAMC,EAAMC,EAAIC,EAAIC,EACjEC,EAAIC,EACJ/I,EAAId,EAAEc,GAAKuB,EAAEvB,EAAI,EAAI,GACrBsB,EAAKpC,EAAEN,EACPoK,EAAKzH,EAAE3C,CAGX,MAAM0C,GAAOA,EAAG,IAAO0H,GAAOA,EAAG,IAE7B,MAAO,IAAIvK,GAGRS,EAAEc,GAAMuB,EAAEvB,IAAOsB,GAAK0H,GAAM1H,EAAG,IAAM0H,EAAG,GAAMA,GAG7C1H,GAAe,GAATA,EAAG,KAAY0H,EAAS,EAAJhJ,EAAQA,EAAI,EAHciJ,IAoB5D,KAbAX,EAAI,GAAI7J,GAAUuB,GAClBuI,EAAKD,EAAE1J,KACPC,EAAIK,EAAEL,EAAI0C,EAAE1C,EACZmB,EAAIwB,EAAK3C,EAAI,EAEPyI,IACFA,EAAOlD,EACPvF,EAAIqK,EAAUhK,EAAEL,EAAIiC,GAAaoI,EAAU3H,EAAE1C,EAAIiC,GACjDd,EAAIA,EAAIc,EAAW,GAKjBhC,EAAI,EAAGkK,EAAGlK,KAAQwC,EAAGxC,IAAM,GAAKA,KAGtC,GAFKkK,EAAGlK,IAAOwC,EAAGxC,IAAM,IAAMD,IAErB,EAAJmB,EACDuI,EAAGxH,KAAK,GACRoH,GAAO,MACJ,CAwBH,IAvBAS,EAAKtH,EAAGpB,OACR4I,EAAKE,EAAG9I,OACRpB,EAAI,EACJkB,GAAK,EAILtB,EAAIiC,EAAW2G,GAAS0B,EAAG,GAAK,IAI3BtK,EAAI,IACLsK,EAAK3B,EAAU2B,EAAItK,EAAG4I,GACtBhG,EAAK+F,EAAU/F,EAAI5C,EAAG4I,GACtBwB,EAAKE,EAAG9I,OACR0I,EAAKtH,EAAGpB,QAGZyI,EAAKG,EACLN,EAAMlH,EAAGzB,MAAO,EAAGiJ,GACnBL,EAAOD,EAAItI,OAGI4I,EAAPL,EAAWD,EAAIC,KAAU,GACjCM,EAAKC,EAAGnJ,QACRkJ,GAAM,GAAG7G,OAAO6G,GAChBF,EAAMG,EAAG,GACJA,EAAG,IAAM1B,EAAO,GAAIuB,GAIzB,GAAG,CAOC,GANAnK,EAAI,EAGJuJ,EAAMH,EAASkB,EAAIR,EAAKM,EAAIL,GAGjB,EAANR,EAAU,CAkBX,GAdAS,EAAOF,EAAI,GACNM,GAAML,IAAOC,EAAOA,EAAOpB,GAASkB,EAAI,IAAM,IAGnD9J,EAAIiC,EAAW+H,EAAOG,GAUjBnK,EAAI,EAeL,IAZIA,GAAK4I,IAAM5I,EAAI4I,EAAO,GAG1Bc,EAAOf,EAAU2B,EAAItK,EAAG4I,GACxBe,EAAQD,EAAKlI,OACbuI,EAAOD,EAAItI,OAOkC,GAArC4H,EAASM,EAAMI,EAAKH,EAAOI,IAC/B/J,IAGAwJ,EAAUE,EAAWC,EAALS,EAAaC,EAAKC,EAAIX,EAAOf,GAC7Ce,EAAQD,EAAKlI,OACb+H,EAAM,MAQA,IAALvJ,IAGDuJ,EAAMvJ,EAAI,GAId0J,EAAOY,EAAGnJ,QACVwI,EAAQD,EAAKlI,MAUjB,IAPauI,EAARJ,IAAeD,GAAQ,GAAGlG,OAAOkG,IAGtCF,EAAUM,EAAKJ,EAAMK,EAAMnB,GAC3BmB,EAAOD,EAAItI,OAGC,IAAP+H,EAMD,KAAQH,EAASkB,EAAIR,EAAKM,EAAIL,GAAS,GACnC/J,IAGAwJ,EAAUM,EAAUC,EAALK,EAAYC,EAAKC,EAAIP,EAAMnB,GAC1CmB,EAAOD,EAAItI,WAGH,KAAR+H,IACRvJ,IACA8J,GAAO,GAIXD,GAAGzJ,KAAOJ,EAGL8J,EAAI,GACLA,EAAIC,KAAUnH,EAAGqH,IAAO,GAExBH,GAAQlH,EAAGqH,IACXF,EAAO,UAEHE,IAAOC,GAAgB,MAAVJ,EAAI,KAAgBxI,IAE7CmI,GAAiB,MAAVK,EAAI,GAGLD,EAAG,IAAKA,EAAGnB,OAAO,EAAG,GAG/B,GAAKE,GAAQlD,EAAO,CAGhB,IAAMtF,EAAI,EAAGkB,EAAIuI,EAAG,GAAIvI,GAAK,GAAIA,GAAK,GAAIlB,KAC1CU,EAAO8I,EAAG9G,GAAO8G,EAAEzJ,EAAIC,EAAID,EAAIiC,EAAW,GAAM,EAAGW,EAAI0G,OAIvDG,GAAEzJ,EAAIA,EACNyJ,EAAEjH,GAAK8G,CAGX,OAAOG,OAgJfvI,EAAe,WACX,GAAIoJ,GAAa,8BACbC,EAAW,cACXC,EAAY,cACZC,EAAkB,qBAClBC,EAAmB,4BAEvB,OAAO,UAAWrK,EAAGD,EAAKF,EAAKJ,GAC3B,GAAI2I,GACAtH,EAAIjB,EAAME,EAAMA,EAAIgB,QAASsJ,EAAkB,GAGnD,IAAKD,EAAgBxJ,KAAKE,GACtBd,EAAEc,EAAIwJ,MAAMxJ,GAAK,KAAW,EAAJA,EAAQ,GAAK,MAClC,CACH,IAAMjB,IAGFiB,EAAIA,EAAEC,QAASkJ,EAAY,SAAWpG,EAAG0G,EAAIC,GAEzC,MADApC,GAAoC,MAA3BoC,EAAKA,EAAGhI,eAAyB,GAAW,KAANgI,EAAY,EAAI,EACvD/K,GAAKA,GAAK2I,EAAYvE,EAAL0G,IAGzB9K,IACA2I,EAAO3I,EAGPqB,EAAIA,EAAEC,QAASmJ,EAAU,MAAOnJ,QAASoJ,EAAW,SAGnDpK,GAAOe,GAAI,MAAO,IAAIvB,GAAWuB,EAAGsH,EAKzClI,IAAQC,EAAOE,EAAI,SAAYZ,EAAI,SAAWA,EAAI,IAAO,UAAWM,GACxEC,EAAEc,EAAI,KAGVd,EAAEN,EAAIM,EAAEL,EAAI,KACZU,EAAK,MAmNb8E,EAAEsF,cAAgBtF,EAAEuF,IAAM,WACtB,GAAI1K,GAAI,GAAIT,GAAUU,KAEtB,OADKD,GAAEc,EAAI,IAAId,EAAEc,EAAI,GACdd,GAQXmF,EAAEwF,KAAO,WACL,MAAOrK,GAAO,GAAIf,GAAUU,MAAOA,KAAKN,EAAI,EAAG,IAWnDwF,EAAEyF,WAAazF,EAAE4D,IAAM,SAAW1G,EAAG5C,GAEjC,MADAY,GAAK,EACEuI,EAAS3I,KAAM,GAAIV,GAAW8C,EAAG5C,KAQ5C0F,EAAE0F,cAAgB1F,EAAE7C,GAAK,WACrB,GAAI9C,GAAGoH,EACHlH,EAAIO,KAAKP,CAEb,KAAMA,EAAI,MAAO,KAIjB,IAHAF,IAAQoH,EAAIlH,EAAEsB,OAAS,GAAMgJ,EAAU/J,KAAKN,EAAIiC,IAAeA,EAG1DgF,EAAIlH,EAAEkH,GAAK,KAAQA,EAAI,IAAM,EAAGA,GAAK,GAAIpH,KAG9C,MAFS,GAAJA,IAAQA,EAAI,GAEVA,GAwBX2F,EAAE2F,UAAY3F,EAAEpC,IAAM,SAAWV,EAAG5C,GAEhC,MADAY,GAAK,EACE0C,EAAK9C,KAAM,GAAIV,GAAW8C,EAAG5C,GAAKc,EAAgBC,IAQ7D2E,EAAE4F,mBAAqB5F,EAAE6F,SAAW,SAAW3I,EAAG5C,GAE9C,MADAY,GAAK,EACE0C,EAAK9C,KAAM,GAAIV,GAAW8C,EAAG5C,GAAK,EAAG,IAQhD0F,EAAE8F,OAAS9F,EAAE+F,GAAK,SAAW7I,EAAG5C,GAE5B,MADAY,GAAK,EAC6C,IAA3CuI,EAAS3I,KAAM,GAAIV,GAAW8C,EAAG5C,KAQ5C0F,EAAEgG,MAAQ,WACN,MAAO7K,GAAO,GAAIf,GAAUU,MAAOA,KAAKN,EAAI,EAAG,IAQnDwF,EAAEiG,YAAcjG,EAAEuC,GAAK,SAAWrF,EAAG5C,GAEjC,MADAY,GAAK,EACEuI,EAAS3I,KAAM,GAAIV,GAAW8C,EAAG5C,IAAQ,GAQpD0F,EAAEkG,qBAAuBlG,EAAEmG,IAAM,SAAWjJ,EAAG5C,GAE3C,MADAY,GAAK,EACqD,KAAjDZ,EAAImJ,EAAS3I,KAAM,GAAIV,GAAW8C,EAAG5C,MAAuB,IAANA,GAQnE0F,EAAEoG,SAAW,WACT,QAAStL,KAAKP,GAOlByF,EAAEqG,UAAYrG,EAAEsG,MAAQ,WACpB,QAASxL,KAAKP,GAAKsK,EAAU/J,KAAKN,EAAIiC,GAAa3B,KAAKP,EAAEsB,OAAS,GAOvEmE,EAAEmF,MAAQ,WACN,OAAQrK,KAAKa,GAOjBqE,EAAEuG,WAAavG,EAAEwG,MAAQ,WACrB,MAAO1L,MAAKa,EAAI,GAOpBqE,EAAEyG,OAAS,WACP,QAAS3L,KAAKP,GAAkB,GAAbO,KAAKP,EAAE,IAQ9ByF,EAAE0G,SAAW1G,EAAEsC,GAAK,SAAWpF,EAAG5C,GAE9B,MADAY,GAAK,EACEuI,EAAS3I,KAAM,GAAIV,GAAW8C,EAAG5C,IAAQ,GAQpD0F,EAAE2G,kBAAoB3G,EAAE4G,IAAM,SAAW1J,EAAG5C,GAExC,MADAY,GAAK,EACqD,MAAjDZ,EAAImJ,EAAS3I,KAAM,GAAIV,GAAW8C,EAAG5C,MAAwB,IAANA,GAwBpE0F,EAAE6G,MAAQ7G,EAAE8G,IAAM,SAAW5J,EAAG5C,GAC5B,GAAIG,GAAG0E,EAAG4H,EAAGC,EACTnM,EAAIC,KACJ6G,EAAI9G,EAAEc,CAOV,IALAT,EAAK,GACLgC,EAAI,GAAI9C,GAAW8C,EAAG5C,GACtBA,EAAI4C,EAAEvB,GAGAgG,IAAMrH,EAAI,MAAO,IAAIF,GAAUwK,IAGrC,IAAKjD,GAAKrH,EAEN,MADA4C,GAAEvB,GAAKrB,EACAO,EAAEoM,KAAK/J,EAGlB,IAAIgK,GAAKrM,EAAEL,EAAIiC,EACX0K,EAAKjK,EAAE1C,EAAIiC,EACXQ,EAAKpC,EAAEN,EACPoK,EAAKzH,EAAE3C,CAEX,KAAM2M,IAAOC,EAAK,CAGd,IAAMlK,IAAO0H,EAAK,MAAO1H,IAAOC,EAAEvB,GAAKrB,EAAG4C,GAAM,GAAI9C,GAAWuK,EAAK9J,EAAI+J,IAGxE,KAAM3H,EAAG,KAAO0H,EAAG,GAGf,MAAOA,GAAG,IAAOzH,EAAEvB,GAAKrB,EAAG4C,GAAM,GAAI9C,GAAW6C,EAAG,GAAKpC,EAGrC,GAAjBQ,GAAsB,EAAI,GASpC,GALA6L,EAAKrC,EAASqC,GACdC,EAAKtC,EAASsC,GACdlK,EAAKA,EAAGzB,QAGHmG,EAAIuF,EAAKC,EAAK,CAaf,KAXKH,EAAW,EAAJrF,IACRA,GAAKA,EACLoF,EAAI9J,IAEJkK,EAAKD,EACLH,EAAIpC,GAGRoC,EAAEK,UAGI9M,EAAIqH,EAAGrH,IAAKyM,EAAErK,KAAK,IACzBqK,EAAEK,cAMF,KAFAjI,GAAM6H,GAASrF,EAAI1E,EAAGpB,SAAavB,EAAIqK,EAAG9I,SAAa8F,EAAIrH,EAErDqH,EAAIrH,EAAI,EAAO6E,EAAJ7E,EAAOA,IAEpB,GAAK2C,EAAG3C,IAAMqK,EAAGrK,GAAK,CAClB0M,EAAO/J,EAAG3C,GAAKqK,EAAGrK,EAClB,OAYZ,GANI0M,IAAMD,EAAI9J,EAAIA,EAAK0H,EAAIA,EAAKoC,EAAG7J,EAAEvB,GAAKuB,EAAEvB,GAE5CrB,GAAM6E,EAAIwF,EAAG9I,SAAapB,EAAIwC,EAAGpB,QAI5BvB,EAAI,EAAI,KAAQA,IAAK2C,EAAGxC,KAAO,GAIpC,IAHAH,EAAIyF,EAAO,EAGHZ,EAAIwC,GAAK,CAEb,GAAK1E,IAAKkC,GAAKwF,EAAGxF,GAAK,CACnB,IAAM1E,EAAI0E,EAAG1E,IAAMwC,IAAKxC,GAAIwC,EAAGxC,GAAKH,KAClC2C,EAAGxC,GACLwC,EAAGkC,IAAMY,EAGb9C,EAAGkC,IAAMwF,EAAGxF,GAIhB,KAAiB,GAATlC,EAAG,GAASA,EAAG8F,OAAO,EAAG,KAAMoE,GAGvC,MAAMlK,GAAG,GAWFiC,EAAWhC,EAAGD,EAAIkK,IAPrBjK,EAAEvB,EAAqB,GAAjBN,EAAqB,GAAK,EAChC6B,EAAE3C,GAAM2C,EAAE1C,EAAI,GACP0C,IA8Bf8C,EAAEqH,OAASrH,EAAEsH,IAAM,SAAWpK,EAAG5C,GAC7B,GAAI2J,GAAGtI,EACHd,EAAIC,IAMR,OAJAI,GAAK,GACLgC,EAAI,GAAI9C,GAAW8C,EAAG5C,IAGhBO,EAAEN,IAAM2C,EAAEvB,GAAKuB,EAAE3C,IAAM2C,EAAE3C,EAAE,GACtB,GAAIH,GAAUwK,MAGZ1H,EAAE3C,GAAKM,EAAEN,IAAMM,EAAEN,EAAE,GACrB,GAAIH,GAAUS,IAGL,GAAfwF,GAID1E,EAAIuB,EAAEvB,EACNuB,EAAEvB,EAAI,EACNsI,EAAIrG,EAAK/C,EAAGqC,EAAG,EAAG,GAClBA,EAAEvB,EAAIA,EACNsI,EAAEtI,GAAKA,GAEPsI,EAAIrG,EAAK/C,EAAGqC,EAAG,EAAGmD,GAGfxF,EAAEgM,MAAO5C,EAAEsD,MAAMrK,MAQ5B8C,EAAEwH,QAAUxH,EAAEyH,IAAM,WAChB,GAAI5M,GAAI,GAAIT,GAAUU,KAEtB,OADAD,GAAEc,GAAKd,EAAEc,GAAK,KACPd,GAwBXmF,EAAEiH,KAAOjH,EAAE0H,IAAM,SAAWxK,EAAG5C,GAC3B,GAAIyM,GACAlM,EAAIC,KACJ6G,EAAI9G,EAAEc,CAOV,IALAT,EAAK,GACLgC,EAAI,GAAI9C,GAAW8C,EAAG5C,GACtBA,EAAI4C,EAAEvB,GAGAgG,IAAMrH,EAAI,MAAO,IAAIF,GAAUwK,IAGpC,IAAKjD,GAAKrH,EAEP,MADA4C,GAAEvB,GAAKrB,EACAO,EAAEgM,MAAM3J,EAGnB,IAAIgK,GAAKrM,EAAEL,EAAIiC,EACX0K,EAAKjK,EAAE1C,EAAIiC,EACXQ,EAAKpC,EAAEN,EACPoK,EAAKzH,EAAE3C,CAEX,KAAM2M,IAAOC,EAAK,CAGd,IAAMlK,IAAO0H,EAAK,MAAO,IAAIvK,GAAWuH,EAAI,EAI5C,KAAM1E,EAAG,KAAO0H,EAAG,GAAK,MAAOA,GAAG,GAAKzH,EAAI,GAAI9C,GAAW6C,EAAG,GAAKpC,EAAQ,EAAJ8G,GAQ1E,GALAuF,EAAKrC,EAASqC,GACdC,EAAKtC,EAASsC,GACdlK,EAAKA,EAAGzB,QAGHmG,EAAIuF,EAAKC,EAAK,CAUf,IATKxF,EAAI,GACLwF,EAAKD,EACLH,EAAIpC,IAEJhD,GAAKA,EACLoF,EAAI9J,GAGR8J,EAAEK,UACMzF,IAAKoF,EAAErK,KAAK,IACpBqK,EAAEK,UAUN,IAPAzF,EAAI1E,EAAGpB,OACPvB,EAAIqK,EAAG9I,OAGM,EAAR8F,EAAIrH,IAAQyM,EAAIpC,EAAIA,EAAK1H,EAAIA,EAAK8J,EAAGzM,EAAIqH,GAGxCA,EAAI,EAAGrH,GACTqH,GAAM1E,IAAK3C,GAAK2C,EAAG3C,GAAKqK,EAAGrK,GAAKqH,GAAM5B,EAAO,EAC7C9C,EAAG3C,GAAKyF,IAAS9C,EAAG3C,GAAK,EAAI2C,EAAG3C,GAAKyF,CAUzC,OAPI4B,KACA1E,GAAM0E,GAAG9D,OAAOZ,KACdkK,GAKCjI,EAAWhC,EAAGD,EAAIkK,IAS7BnH,EAAE2H,UAAY3H,EAAER,GAAK,SAAUoI,GAC3B,GAAIvN,GAAGoH,EACH5G,EAAIC,KACJP,EAAIM,EAAEN,CAQV,IALU,MAALqN,GAAaA,MAAQA,GAAW,IAANA,GAAiB,IAANA,IAClC7M,GAAQC,EAAO,GAAI,WAAakH,EAAS0F,GACxCA,KAAOA,IAAIA,EAAI,QAGlBrN,EAAI,MAAO,KAIjB,IAHAkH,EAAIlH,EAAEsB,OAAS,EACfxB,EAAIoH,EAAIhF,EAAW,EAEdgF,EAAIlH,EAAEkH,GAAK,CAGZ,KAAQA,EAAI,IAAM,EAAGA,GAAK,GAAIpH,KAG9B,IAAMoH,EAAIlH,EAAE,GAAIkH,GAAK,GAAIA,GAAK,GAAIpH,MAKtC,MAFKuN,IAAK/M,EAAEL,EAAI,EAAIH,IAAIA,EAAIQ,EAAEL,EAAI,GAE3BH,GAiBX2F,EAAE7E,MAAQ,SAAWgC,EAAIC,GACrB,GAAI/C,GAAI,GAAID,GAAUU,KAOtB,QALW,MAANqC,GAAclC,EAAYkC,EAAI,EAAG6E,EAAK,MACvC7G,EAAOd,IAAK8C,EAAKrC,KAAKN,EAAI,EAAS,MAAN4C,GAC1BnC,EAAYmC,EAAI,EAAG,EAAG,GAAIe,GAAsC,EAALf,EAAhB/B,GAG3ChB,GAgBX2F,EAAE6H,MAAQ,SAAU9K,GAChB,GAAI1C,GAAIS,IACR,OAAOG,GAAY8B,GAAIV,EAAkBA,EAAkB,GAAI,YAG3DhC,EAAEkN,MAAO,KAAOtI,EAASlC,IACzB,GAAI3C,GAAWC,EAAEE,GAAKF,EAAEE,EAAE,MAAa8B,EAALU,GAAyBA,EAAIV,GAC7DhC,EAAEsB,GAAU,EAAJoB,EAAQ,EAAI,EAAI,GACxB1C,IAeV2F,EAAE8H,WAAa9H,EAAE+H,KAAO,WACpB,GAAIrJ,GAAGrE,EAAG2C,EAAGgL,EAAKjB,EACdlM,EAAIC,KACJP,EAAIM,EAAEN,EACNoB,EAAId,EAAEc,EACNnB,EAAIK,EAAEL,EACN2C,EAAK/B,EAAiB,EACtB6M,EAAO,GAAI7N,GAAU,MAGzB,IAAW,IAANuB,IAAYpB,IAAMA,EAAE,GACrB,MAAO,IAAIH,IAAYuB,GAAS,EAAJA,KAAYpB,GAAKA,EAAE,IAAOqK,IAAMrK,EAAIM,EAAI,EAAI,EA8B5E,IA1BAc,EAAIgH,KAAKoF,MAAOlN,GAIN,GAALc,GAAUA,GAAK,EAAI,GACpBtB,EAAIqD,EAAcnD,IACXF,EAAEwB,OAASrB,GAAM,GAAK,IAAIH,GAAK,KACtCsB,EAAIgH,KAAKoF,KAAK1N,GACdG,EAAIqK,GAAYrK,EAAI,GAAM,IAAY,EAAJA,GAASA,EAAI,GAE1CmB,GAAK,EAAI,EACVtB,EAAI,KAAOG,GAEXH,EAAIsB,EAAE2C,gBACNjE,EAAIA,EAAEmB,MAAO,EAAGnB,EAAE6B,QAAQ,KAAO,GAAM1B,GAG3CwC,EAAI,GAAI5C,GAAUC,IAElB2C,EAAI,GAAI5C,GAAWuB,EAAI,IAOtBqB,EAAEzC,EAAE,GAML,IALAC,EAAIwC,EAAExC,EACNmB,EAAInB,EAAI2C,EACC,EAAJxB,IAAQA,EAAI,KAOb,GAHAoL,EAAI/J,EACJA,EAAIiL,EAAKV,MAAOR,EAAEE,KAAMrJ,EAAK/C,EAAGkM,EAAG5J,EAAI,KAElCO,EAAeqJ,EAAExM,GAAMiB,MAAO,EAAGG,MAAUtB,EAC3CqD,EAAeV,EAAEzC,IAAMiB,MAAO,EAAGG,GAAM,CAWxC,GANKqB,EAAExC,EAAIA,KAAMmB,EACjBtB,EAAIA,EAAEmB,MAAOG,EAAI,EAAGA,EAAI,GAKd,QAALtB,IAAgB2N,GAAY,QAAL3N,GAgBrB,IAIIA,KAAOA,EAAEmB,MAAM,IAAqB,KAAfnB,EAAEyD,OAAO,MAGjC3C,EAAO6B,EAAGA,EAAExC,EAAIY,EAAiB,EAAG,GACpCsD,GAAK1B,EAAEuK,MAAMvK,GAAG+I,GAAGlL,GAGvB,OAvBA,IAAMmN,IACF7M,EAAO4L,EAAGA,EAAEvM,EAAIY,EAAiB,EAAG,GAE/B2L,EAAEQ,MAAMR,GAAGhB,GAAGlL,IAAK,CACpBmC,EAAI+J,CACJ,OAIR5J,GAAM,EACNxB,GAAK,EACLqM,EAAM,EAkBtB,MAAO7M,GAAO6B,EAAGA,EAAExC,EAAIY,EAAiB,EAAGC,EAAeqD,IAwB9DsB,EAAEuH,MAAQvH,EAAEkI,IAAM,SAAWhL,EAAG5C,GAC5B,GAAIC,GAAGC,EAAGC,EAAG0E,EAAGpC,EAAG2B,EAAGyJ,EAAKhF,EAAKC,EAAKgF,EAAKC,EAAKC,EAAKC,EAChDtF,EAAMuF,EACN3N,EAAIC,KACJmC,EAAKpC,EAAEN,EACPoK,GAAOzJ,EAAK,GAAIgC,EAAI,GAAI9C,GAAW8C,EAAG5C,IAAMC,CAGhD,MAAM0C,GAAO0H,GAAO1H,EAAG,IAAO0H,EAAG,IAmB7B,OAhBM9J,EAAEc,IAAMuB,EAAEvB,GAAKsB,IAAOA,EAAG,KAAO0H,GAAMA,IAAOA,EAAG,KAAO1H,EACzDC,EAAE3C,EAAI2C,EAAE1C,EAAI0C,EAAEvB,EAAI,MAElBuB,EAAEvB,GAAKd,EAAEc,EAGHsB,GAAO0H,GAKTzH,EAAE3C,GAAK,GACP2C,EAAE1C,EAAI,GALN0C,EAAE3C,EAAI2C,EAAE1C,EAAI,MASb0C,CAYX,KATA1C,EAAIqK,EAAUhK,EAAEL,EAAIiC,GAAaoI,EAAU3H,EAAE1C,EAAIiC,GACjDS,EAAEvB,GAAKd,EAAEc,EACTwM,EAAMlL,EAAGpB,OACTuM,EAAMzD,EAAG9I,OAGEuM,EAAND,IAAYI,EAAKtL,EAAIA,EAAK0H,EAAIA,EAAK4D,EAAI9N,EAAI0N,EAAKA,EAAMC,EAAKA,EAAM3N,GAGhEA,EAAI0N,EAAMC,EAAKG,KAAS9N,IAAK8N,EAAG7L,KAAK,IAK3C,IAHAuG,EAAOlD,EACPyI,EAAWjF,EAEL9I,EAAI2N,IAAO3N,GAAK,GAAK,CAKvB,IAJAF,EAAI,EACJ8N,EAAM1D,EAAGlK,GAAK+N,EACdF,EAAM3D,EAAGlK,GAAK+N,EAAW,EAEnBzL,EAAIoL,EAAKhJ,EAAI1E,EAAIsC,EAAGoC,EAAI1E,GAC1B0I,EAAMlG,IAAKF,GAAKyL,EAChBpF,EAAMnG,EAAGF,GAAKyL,EAAW,EACzB9J,EAAI4J,EAAMnF,EAAMC,EAAMiF,EACtBlF,EAAMkF,EAAMlF,EAAUzE,EAAI8J,EAAaA,EAAaD,EAAGpJ,GAAK5E,EAC5DA,GAAM4I,EAAMF,EAAO,IAAQvE,EAAI8J,EAAW,GAAMF,EAAMlF,EACtDmF,EAAGpJ,KAAOgE,EAAMF,CAGpBsF,GAAGpJ,GAAK5E,EASZ,MANIA,KACEC,EAEF+N,EAAGxF,OAAO,EAAG,GAGV7D,EAAWhC,EAAGqL,EAAI/N,IAgB7BwF,EAAEyI,SAAW,SAAWjJ,EAAIpC,GACxB,GAAI/C,GAAI,GAAID,GAAUU,KAGtB,OAFA0E,GAAW,MAANA,GAAevE,EAAYuE,EAAI,EAAGwC,EAAK,GAAI,aAA4B,EAALxC,EAAP,KAChEpC,EAAW,MAANA,GAAenC,EAAYmC,EAAI,EAAG,EAAG,GAAIe,GAAsC,EAALf,EAAhB/B,EACxDmE,EAAKrE,EAAOd,EAAGmF,EAAIpC,GAAO/C,GAgBrC2F,EAAE1B,cAAgB,SAAWnB,EAAIC,GAC7B,MAAOW,GAAQjD,KACP,MAANqC,GAAclC,EAAYkC,EAAI,EAAG6E,EAAK,MAAS7E,EAAK,EAAI,KAAMC,EAAI,KAmBxE4C,EAAE0I,QAAU,SAAWvL,EAAIC,GACvB,MAAOW,GAAQjD,KAAY,MAANqC,GAAclC,EAAYkC,EAAI,EAAG6E,EAAK,MACrD7E,EAAKrC,KAAKN,EAAI,EAAI,KAAM4C,EAAI,KA0BtC4C,EAAE2I,SAAW,SAAWxL,EAAIC,GACxB,GAAIxC,GAAMmD,EAAQjD,KAAY,MAANqC,GAAclC,EAAYkC,EAAI,EAAG6E,EAAK,MACxD7E,EAAKrC,KAAKN,EAAI,EAAI,KAAM4C,EAAI,GAElC,IAAKtC,KAAKP,EAAI,CACV,GAAIE,GACAmO,EAAMhO,EAAIiO,MAAM,KAChBC,GAAMxI,EAAOG,UACbsI,GAAMzI,EAAOI,mBACbF,EAAiBF,EAAOE,eACxBwI,EAAUJ,EAAI,GACdK,EAAeL,EAAI,GACnBpC,EAAQ1L,KAAKa,EAAI,EACjBuN,EAAY1C,EAAQwC,EAAQxN,MAAM,GAAKwN,EACvCrO,EAAMuO,EAAUrN,MAIpB,IAFIkN,IAAItO,EAAIqO,EAAIA,EAAKC,EAAIA,EAAKtO,EAAGE,GAAOF,GAEnCqO,EAAK,GAAKnO,EAAM,EAAI,CAIrB,IAHAF,EAAIE,EAAMmO,GAAMA,EAChBE,EAAUE,EAAUC,OAAQ,EAAG1O,GAEnBE,EAAJF,EAASA,GAAKqO,EAClBE,GAAWxI,EAAiB0I,EAAUC,OAAQ1O,EAAGqO,EAGhDC,GAAK,IAAIC,GAAWxI,EAAiB0I,EAAU1N,MAAMf,IACtD+L,IAAOwC,EAAU,IAAMA,GAG/BpO,EAAMqO,EACFD,EAAU1I,EAAOC,mBAAuBwI,GAAMzI,EAAOM,mBACnDqI,EAAarN,QAAS,GAAIN,QAAQ,OAASyN,EAAK,OAAQ,KACxD,KAAOzI,EAAOK,wBACdsI,GACFD,EAGR,MAAOpO,IAgBXoF,EAAEoJ,WAAa,SAAUC,GACrB,GAAIT,GAAKU,EAAIC,EAAI/O,EAAGgP,EAAKnP,EAAGoP,EAAIxF,EAAGtI,EAC/BoB,EAAIhC,EACJF,EAAIC,KACJmC,EAAKpC,EAAEN,EACPuC,EAAI,GAAI1C,GAAU8F,GAClBwJ,EAAKJ,EAAK,GAAIlP,GAAU8F,GACxByJ,EAAKF,EAAK,GAAIrP,GAAU8F,EAoB5B,IAlBW,MAANmJ,IACDtO,GAAS,EACTV,EAAI,GAAID,GAAUiP,GAClBtO,EAASgC,KAEDA,EAAI1C,EAAEiM,UAAajM,EAAEiI,GAAGpC,MAExBnF,GACAC,EAAO,GACL,oBAAuB+B,EAAI,eAAiB,kBAAoBsM,GAKtEA,GAAMtM,GAAK1C,EAAEE,GAAKY,EAAOd,EAAGA,EAAEG,EAAI,EAAG,GAAI2L,IAAIjG,GAAO7F,EAAI,QAI1D4C,EAAK,MAAOpC,GAAEuD,UAgBpB,KAfAzC,EAAI+B,EAAcT,GAIlBzC,EAAIsC,EAAEtC,EAAImB,EAAEE,OAAShB,EAAEL,EAAI,EAC3BsC,EAAEvC,EAAE,GAAKqF,GAAY4J,EAAMhP,EAAIiC,GAAa,EAAIA,EAAW+M,EAAMA,GACjEH,GAAMA,GAAMhP,EAAEuJ,IAAI9G,GAAK,EAAMtC,EAAI,EAAIsC,EAAI4M,EAAOrP,EAEhDmP,EAAMjN,EACNA,EAAU,EAAI,EACdlC,EAAI,GAAID,GAAUuB,GAGlB8N,EAAGlP,EAAE,GAAK,EAGN0J,EAAIrG,EAAKvD,EAAGyC,EAAG,EAAG,GAClByM,EAAKD,EAAGrC,KAAMhD,EAAEsD,MAAMoC,IACH,GAAdJ,EAAG3F,IAAIyF,IACZC,EAAKK,EACLA,EAAKJ,EACLG,EAAKD,EAAGxC,KAAMhD,EAAEsD,MAAOgC,EAAKG,IAC5BD,EAAKF,EACLzM,EAAIzC,EAAEwM,MAAO5C,EAAEsD,MAAOgC,EAAKzM,IAC3BzC,EAAIkP,CAgBR,OAbAA,GAAK3L,EAAKyL,EAAGxC,MAAMyC,GAAKK,EAAI,EAAG,GAC/BF,EAAKA,EAAGxC,KAAMsC,EAAGhC,MAAMmC,IACvBJ,EAAKA,EAAGrC,KAAMsC,EAAGhC,MAAMoC,IACvBF,EAAG9N,EAAI+N,EAAG/N,EAAId,EAAEc,EAChBnB,GAAK,EAGLoO,EAAMhL,EAAK8L,EAAIC,EAAInP,EAAGa,GAAgBwL,MAAMhM,GAAG0K,MAAM3B,IAC/ChG,EAAK6L,EAAIH,EAAI9O,EAAGa,GAAgBwL,MAAMhM,GAAG0K,OAAU,GAC7CmE,EAAGtL,WAAYuL,EAAGvL,aAClBqL,EAAGrL,WAAYkL,EAAGlL,YAE9B7B,EAAUiN,EACHZ,GAOX5I,EAAE4J,SAAW,WACT,OAAQ9O,MAsBZkF,EAAE6J,QAAU7J,EAAEzC,IAAM,SAAWlD,EAAGqE,GAC9B,GAAI3B,GAAGG,EAAG0K,EACNnN,EAAI6B,EAAe,EAAJjC,GAASA,GAAKA,GAC7BQ,EAAIC,IAQR,IANU,MAAL4D,IACDxD,EAAK,GACLwD,EAAI,GAAItE,GAAUsE,KAIhBzD,EAAYZ,GAAIgC,EAAkBA,EAAkB,GAAI,eACzD+J,SAAS/L,IAAMI,EAAI4B,IAAsBhC,GAAK,IAC/CyP,WAAWzP,IAAMA,KAAQA,EAAIuK,OAAgB,GAALvK,EAExC,MADA0C,GAAI4F,KAAKpF,KAAM1C,EAAGR,GACX,GAAID,GAAWsE,EAAI3B,EAAI2B,EAAI3B,EAuBtC,KApBI2B,EACKrE,EAAI,GAAKQ,EAAE0H,GAAGrC,IAAQrF,EAAEyL,SAAW5H,EAAE6D,GAAGrC,IAAQxB,EAAE4H,QACnDzL,EAAIA,EAAEyM,IAAI5I,IAEVkJ,EAAIlJ,EAGJA,EAAI,MAEDpB,IAMPP,EAAI+C,EAAUxC,EAAgBb,EAAW,IAG7CS,EAAI,GAAI9C,GAAU8F,KAEN,CACR,GAAKzF,EAAI,EAAI,CAET,GADAyC,EAAIA,EAAEqK,MAAM1M,IACNqC,EAAE3C,EAAI,KACRwC,GACKG,EAAE3C,EAAEsB,OAASkB,IAAIG,EAAE3C,EAAEsB,OAASkB,GAC5B2B,IACPxB,EAAIA,EAAEoK,IAAI5I,IAKlB,GADAjE,EAAI6B,EAAW7B,EAAI,IACbA,EAAI,KACVI,GAAIA,EAAE0M,MAAM1M,GACRkC,EACKlC,EAAEN,GAAKM,EAAEN,EAAEsB,OAASkB,IAAIlC,EAAEN,EAAEsB,OAASkB,GACnC2B,IACP7D,EAAIA,EAAEyM,IAAI5I,IAIlB,MAAIA,GAAUxB,GACL,EAAJ7C,IAAQ6C,EAAIgD,EAAItC,IAAIV,IAElB0K,EAAI1K,EAAEoK,IAAIM,GAAK7K,EAAI5B,EAAO+B,EAAGI,EAAejC,GAAkB6B,IAkBzE8C,EAAE+J,YAAc,SAAWvK,EAAIpC,GAC3B,MAAOW,GAAQjD,KAAY,MAAN0E,GAAcvE,EAAYuE,EAAI,EAAGwC,EAAK,GAAI,aACtD,EAALxC,EAAS,KAAMpC,EAAI,KAgB3B4C,EAAE5B,SAAW,SAAU9D,GACnB,GAAIM,GACAP,EAAIS,KACJa,EAAItB,EAAEsB,EACNnB,EAAIH,EAAEG,CAyBV,OAtBW,QAANA,EAEGmB,GACAf,EAAM,WACG,EAAJe,IAAQf,EAAM,IAAMA,IAEzBA,EAAM,OAGVA,EAAM8C,EAAerD,EAAEE,GAOnBK,EALM,MAALN,GAAcW,EAAYX,EAAG,EAAG,GAAI,GAAI,QAKnC0B,EAAayB,EAAc7C,EAAKJ,GAAS,EAAJF,EAAO,GAAIqB,GAJ3C0C,GAAL7D,GAAmBA,GAAK2F,EAC1B7B,EAAe1D,EAAKJ,GACpBiD,EAAc7C,EAAKJ,GAKlB,EAAJmB,GAAStB,EAAEE,EAAE,KAAKK,EAAM,IAAMA,IAGhCA,GAQXoF,EAAEgK,UAAYhK,EAAEiK,MAAQ,WACpB,MAAO9O,GAAO,GAAIf,GAAUU,MAAOA,KAAKN,EAAI,EAAG,IAQnDwF,EAAEkK,QAAUlK,EAAEmK,OAAS,WACnB,GAAIvP,GACAP,EAAIS,KACJN,EAAIH,EAAEG,CAEV,OAAW,QAANA,EAAoBH,EAAE+D,YAE3BxD,EAAM8C,EAAerD,EAAEE,GAEvBK,EAAWyD,GAAL7D,GAAmBA,GAAK2F,EACxB7B,EAAe1D,EAAKJ,GACpBiD,EAAc7C,EAAKJ,GAElBH,EAAEsB,EAAI,EAAI,IAAMf,EAAMA,IAIjCoF,EAAEoK,aAAc,EAED,MAAVjQ,GAAiBC,EAAUD,OAAOA,GAEhCC,EAOX,QAASyK,GAASxK,GACd,GAAII,GAAQ,EAAJJ,CACR,OAAOA,GAAI,GAAKA,IAAMI,EAAIA,EAAIA,EAAI,EAKtC,QAASiD,GAAciE,GAMnB,IALA,GAAIhG,GAAGiM,EACHnN,EAAI,EACJ0E,EAAIwC,EAAE9F,OACNmB,EAAI2E,EAAE,GAAK,GAEHxC,EAAJ1E,GAAS,CAGb,IAFAkB,EAAIgG,EAAElH,KAAO,GACbmN,EAAInL,EAAWd,EAAEE,OACT+L,IAAKjM,EAAI,IAAMA,GACvBqB,GAAKrB,EAIT,IAAMwD,EAAInC,EAAEnB,OAA8B,KAAtBmB,EAAEjB,aAAaoD,KACnC,MAAOnC,GAAExB,MAAO,EAAG2D,EAAI,GAAK,GAKhC,QAASsE,GAAS5I,EAAGqC,GACjB,GAAIyE,GAAGrH,EACH2C,EAAKpC,EAAEN,EACPoK,EAAKzH,EAAE3C,EACPE,EAAII,EAAEc,EACNwD,EAAIjC,EAAEvB,EACNoB,EAAIlC,EAAEL,EACN6P,EAAInN,EAAE1C,CAGV,KAAMC,IAAM0E,EAAI,MAAO,KAMvB,IAJAwC,EAAI1E,IAAOA,EAAG,GACd3C,EAAIqK,IAAOA,EAAG,GAGThD,GAAKrH,EAAI,MAAOqH,GAAIrH,EAAI,GAAK6E,EAAI1E,CAGtC,IAAKA,GAAK0E,EAAI,MAAO1E,EAMrB,IAJAkH,EAAQ,EAAJlH,EACJH,EAAIyC,GAAKsN,GAGHpN,IAAO0H,EAAK,MAAOrK,GAAI,GAAK2C,EAAK0E,EAAI,EAAI,EAG/C,KAAMrH,EAAI,MAAOyC,GAAIsN,EAAI1I,EAAI,EAAI,EAKjC,KAHAxC,GAAMpC,EAAIE,EAAGpB,SAAawO,EAAI1F,EAAG9I,QAAWkB,EAAIsN,EAG1C5P,EAAI,EAAO0E,EAAJ1E,EAAOA,IAAM,GAAKwC,EAAGxC,IAAMkK,EAAGlK,GAAK,MAAOwC,GAAGxC,GAAKkK,EAAGlK,GAAKkH,EAAI,EAAI,EAG/E,OAAO5E,IAAKsN,EAAI,EAAItN,EAAIsN,EAAI1I,EAAI,EAAI,GASxC,QAASM,GAAsB5H,EAAGyE,EAAKC,GACnC,OAAS1E,EAAI4E,EAAS5E,KAAQyE,GAAYC,GAAL1E,EAIzC,QAASsE,GAAQ2L,GACb,MAA8C,kBAAvCC,OAAOtK,UAAU7B,SAASQ,KAAK0L,GAS1C,QAAS9M,GAAW5C,EAAKgC,EAAQD,GAO7B,IANA,GAAIwC,GAEAqL,EADA5B,GAAO,GAEPnO,EAAI,EACJE,EAAMC,EAAIiB,OAEFlB,EAAJF,GAAW,CACf,IAAM+P,EAAO5B,EAAI/M,OAAQ2O,IAAQ5B,EAAI4B,IAAS5N,GAG9C,IAFAgM,EAAKzJ,EAAI,IAAO5D,EAASW,QAAStB,EAAIkD,OAAQrD,MAEtC0E,EAAIyJ,EAAI/M,OAAQsD,IAEfyJ,EAAIzJ,GAAKxC,EAAU,IACD,MAAdiM,EAAIzJ,EAAI,KAAayJ,EAAIzJ,EAAI,GAAK,GACvCyJ,EAAIzJ,EAAI,IAAMyJ,EAAIzJ,GAAKxC,EAAU,EACjCiM,EAAIzJ,IAAMxC,GAKtB,MAAOiM,GAAIxB,UAIf,QAAS9I,GAAe1D,EAAKJ,GACzB,OAASI,EAAIiB,OAAS,EAAIjB,EAAIkD,OAAO,GAAK,IAAMlD,EAAIY,MAAM,GAAKZ,IACvD,EAAJJ,EAAQ,IAAM,MAASA,EAI/B,QAASiD,GAAc7C,EAAKJ,GACxB,GAAIG,GAAKiN,CAGT,IAAS,EAAJpN,EAAQ,CAGT,IAAMoN,EAAI,OAAQpN,EAAGoN,GAAK,KAC1BhN,EAAMgN,EAAIhN,MAOV,IAHAD,EAAMC,EAAIiB,SAGHrB,EAAIG,EAAM,CACb,IAAMiN,EAAI,IAAKpN,GAAKG,IAAOH,EAAGoN,GAAK,KACnChN,GAAOgN,MACKjN,GAAJH,IACRI,EAAMA,EAAIY,MAAO,EAAGhB,GAAM,IAAMI,EAAIY,MAAMhB,GAIlD,OAAOI,GAIX,QAASqE,GAAS5E,GAEd,MADAA,GAAIyP,WAAWzP,GACJ,EAAJA,EAAQyF,EAASzF,GAAKiC,EAAUjC,GAvoF3C,GAAID,GACA6B,EAAY,uCACZ6D,EAAW6C,KAAK6C,KAChBlJ,EAAYqG,KAAKqD,MACjB9D,EAAU,iCACV/D,EAAe,gBACfrC,EAAgB,kDAChBP,EAAW,mEACXwE,EAAO,KACPtD,EAAW,GACXJ,EAAmB,iBAEnBuD,GAAY,EAAG,GAAI,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,KAAM,KAAM,KAAM,MAC7E2D,EAAY,IAOZvB,EAAM,GA0nFV5H,GAAYF,IACZE,EAAU,WAAaA,EAAUA,UAAYA,EAIvB,kBAAVqQ,SAAwBA,OAAOC,IACvCD,OAAQ,WAAc,MAAOrQ,KAGJ,mBAAVuQ,SAAyBA,OAAOC,QAC/CD,OAAOC,QAAUxQ,GAIXH,IAAYA,EAA2B,mBAAR4Q,MAAsBA,KAAOC,SAAS,kBAC3E7Q,EAAUG,UAAYA,IAE3BU"} \ No newline at end of file diff --git a/node_modules/bignumber.js/bignumber.min.js b/node_modules/bignumber.js/bignumber.min.js new file mode 100644 index 0000000000000000000000000000000000000000..5b0f7ad211d197bc5bc7c49304e6e48426c4cadc --- /dev/null +++ b/node_modules/bignumber.js/bignumber.min.js @@ -0,0 +1,3 @@ +/* bignumber.js v4.1.0 https://github.com/MikeMcl/bignumber.js/LICENCE */ +!function(e){"use strict";function n(e){function a(e,n){var t,r,i,o,u,s,l=this;if(!(l instanceof a))return z&&x(26,"constructor call without new",e),new a(e,n);if(null!=n&&V(n,2,64,C,"base")){if(n=0|n,s=e+"",10==n)return l=new a(e instanceof a?e:s),I(l,B+l.e+1,P);if((o="number"==typeof e)&&0*e!=0||!new RegExp("^-?"+(t="["+v.slice(0,n)+"]+")+"(?:\\."+t+")?$",37>n?"i":"").test(s))return U(l,s,o,n);o?(l.s=0>1/e?(s=s.slice(1),-1):1,z&&s.replace(/^0\.0*|\./,"").length>15&&x(C,w,e),o=!1):l.s=45===s.charCodeAt(0)?(s=s.slice(1),-1):1,s=A(s,10,n,l.s)}else{if(e instanceof a)return l.s=e.s,l.e=e.e,l.c=(e=e.c)?e.slice():e,void(C=0);if((o="number"==typeof e)&&0*e==0){if(l.s=0>1/e?(e=-e,-1):1,e===~~e){for(r=0,i=e;i>=10;i/=10,r++);return l.e=r,l.c=[e],void(C=0)}s=e+""}else{if(!h.test(s=e+""))return U(l,s,o);l.s=45===s.charCodeAt(0)?(s=s.slice(1),-1):1}}for((r=s.indexOf("."))>-1&&(s=s.replace(".","")),(i=s.search(/e/i))>0?(0>r&&(r=i),r+=+s.slice(i+1),s=s.substring(0,i)):0>r&&(r=s.length),i=0;48===s.charCodeAt(i);i++);for(u=s.length;48===s.charCodeAt(--u););if(s=s.slice(i,u+1))if(u=s.length,o&&z&&u>15&&(e>y||e!==p(e))&&x(C,w,l.s*e),r=r-i-1,r>G)l.c=l.e=null;else if($>r)l.c=[l.e=0];else{if(l.e=r,l.c=[],i=(r+1)%b,0>r&&(i+=b),u>i){for(i&&l.c.push(+s.slice(0,i)),u-=b;u>i;)l.c.push(+s.slice(i,i+=b));s=s.slice(i),i=b-s.length}else i-=u;for(;i--;s+="0");l.c.push(+s)}else l.c=[l.e=0];C=0}function A(e,n,t,i){var o,u,l,f,h,g,p,d=e.indexOf("."),m=B,w=P;for(37>t&&(e=e.toLowerCase()),d>=0&&(l=W,W=0,e=e.replace(".",""),p=new a(t),h=p.pow(e.length-d),W=l,p.c=s(c(r(h.c),h.e),10,n),p.e=p.c.length),g=s(e,t,n),u=l=g.length;0==g[--l];g.pop());if(!g[0])return"0";if(0>d?--u:(h.c=g,h.e=u,h.s=i,h=L(h,p,m,w,n),g=h.c,f=h.r,u=h.e),o=u+m+1,d=g[o],l=n/2,f=f||0>o||null!=g[o+1],f=4>w?(null!=d||f)&&(0==w||w==(h.s<0?3:2)):d>l||d==l&&(4==w||f||6==w&&1&g[o-1]||w==(h.s<0?8:7)),1>o||!g[0])e=f?c("1",-m):"0";else{if(g.length=o,f)for(--n;++g[--o]>n;)g[o]=0,o||(++u,g=[1].concat(g));for(l=g.length;!g[--l];);for(d=0,e="";l>=d;e+=v.charAt(g[d++]));e=c(e,u)}return e}function E(e,n,t,i){var o,u,s,f,h;if(t=null!=t&&V(t,0,8,i,m)?0|t:P,!e.c)return e.toString();if(o=e.c[0],s=e.e,null==n)h=r(e.c),h=19==i||24==i&&q>=s?l(h,s):c(h,s);else if(e=I(new a(e),n,t),u=e.e,h=r(e.c),f=h.length,19==i||24==i&&(u>=n||q>=u)){for(;n>f;h+="0",f++);h=l(h,u)}else if(n-=s,h=c(h,u),u+1>f){if(--n>0)for(h+=".";n--;h+="0");}else if(n+=u-f,n>0)for(u+1==f&&(h+=".");n--;h+="0");return e.s<0&&o?"-"+h:h}function D(e,n){var t,r,i=0;for(u(e[0])&&(e=e[0]),t=new a(e[0]);++i<e.length;){if(r=new a(e[i]),!r.s){t=r;break}n.call(t,r)&&(t=r)}return t}function F(e,n,t,r,i){return(n>e||e>t||e!=f(e))&&x(r,(i||"decimal places")+(n>e||e>t?" out of range":" not an integer"),e),!0}function _(e,n,t){for(var r=1,i=n.length;!n[--i];n.pop());for(i=n[0];i>=10;i/=10,r++);return(t=r+t*b-1)>G?e.c=e.e=null:$>t?e.c=[e.e=0]:(e.e=t,e.c=n),e}function x(e,n,t){var r=new Error(["new BigNumber","cmp","config","div","divToInt","eq","gt","gte","lt","lte","minus","mod","plus","precision","random","round","shift","times","toDigits","toExponential","toFixed","toFormat","toFraction","pow","toPrecision","toString","BigNumber"][e]+"() "+n+": "+t);throw r.name="BigNumber Error",C=0,r}function I(e,n,t,r){var i,o,u,s,l,c,f,a=e.c,h=O;if(a){e:{for(i=1,s=a[0];s>=10;s/=10,i++);if(o=n-i,0>o)o+=b,u=n,l=a[c=0],f=l/h[i-u-1]%10|0;else if(c=g((o+1)/b),c>=a.length){if(!r)break e;for(;a.length<=c;a.push(0));l=f=0,i=1,o%=b,u=o-b+1}else{for(l=s=a[c],i=1;s>=10;s/=10,i++);o%=b,u=o-b+i,f=0>u?0:l/h[i-u-1]%10|0}if(r=r||0>n||null!=a[c+1]||(0>u?l:l%h[i-u-1]),r=4>t?(f||r)&&(0==t||t==(e.s<0?3:2)):f>5||5==f&&(4==t||r||6==t&&(o>0?u>0?l/h[i-u]:0:a[c-1])%10&1||t==(e.s<0?8:7)),1>n||!a[0])return a.length=0,r?(n-=e.e+1,a[0]=h[(b-n%b)%b],e.e=-n||0):a[0]=e.e=0,e;if(0==o?(a.length=c,s=1,c--):(a.length=c+1,s=h[b-o],a[c]=u>0?p(l/h[i-u]%h[u])*s:0),r)for(;;){if(0==c){for(o=1,u=a[0];u>=10;u/=10,o++);for(u=a[0]+=s,s=1;u>=10;u/=10,s++);o!=s&&(e.e++,a[0]==N&&(a[0]=1));break}if(a[c]+=s,a[c]!=N)break;a[c--]=0,s=1}for(o=a.length;0===a[--o];a.pop());}e.e>G?e.c=e.e=null:e.e<$&&(e.c=[e.e=0])}return e}var L,U,C=0,M=a.prototype,T=new a(1),B=20,P=4,q=-7,k=21,$=-1e7,G=1e7,z=!0,V=F,j=!1,H=1,W=0,J={decimalSeparator:".",groupSeparator:",",groupSize:3,secondaryGroupSize:0,fractionGroupSeparator:" ",fractionGroupSize:0};return a.another=n,a.ROUND_UP=0,a.ROUND_DOWN=1,a.ROUND_CEIL=2,a.ROUND_FLOOR=3,a.ROUND_HALF_UP=4,a.ROUND_HALF_DOWN=5,a.ROUND_HALF_EVEN=6,a.ROUND_HALF_CEIL=7,a.ROUND_HALF_FLOOR=8,a.EUCLID=9,a.config=a.set=function(){var e,n,t=0,r={},i=arguments,s=i[0],l=s&&"object"==typeof s?function(){return s.hasOwnProperty(n)?null!=(e=s[n]):void 0}:function(){return i.length>t?null!=(e=i[t++]):void 0};return l(n="DECIMAL_PLACES")&&V(e,0,S,2,n)&&(B=0|e),r[n]=B,l(n="ROUNDING_MODE")&&V(e,0,8,2,n)&&(P=0|e),r[n]=P,l(n="EXPONENTIAL_AT")&&(u(e)?V(e[0],-S,0,2,n)&&V(e[1],0,S,2,n)&&(q=0|e[0],k=0|e[1]):V(e,-S,S,2,n)&&(q=-(k=0|(0>e?-e:e)))),r[n]=[q,k],l(n="RANGE")&&(u(e)?V(e[0],-S,-1,2,n)&&V(e[1],1,S,2,n)&&($=0|e[0],G=0|e[1]):V(e,-S,S,2,n)&&(0|e?$=-(G=0|(0>e?-e:e)):z&&x(2,n+" cannot be zero",e))),r[n]=[$,G],l(n="ERRORS")&&(e===!!e||1===e||0===e?(C=0,V=(z=!!e)?F:o):z&&x(2,n+d,e)),r[n]=z,l(n="CRYPTO")&&(e===!0||e===!1||1===e||0===e?e?(e="undefined"==typeof crypto,!e&&crypto&&(crypto.getRandomValues||crypto.randomBytes)?j=!0:z?x(2,"crypto unavailable",e?void 0:crypto):j=!1):j=!1:z&&x(2,n+d,e)),r[n]=j,l(n="MODULO_MODE")&&V(e,0,9,2,n)&&(H=0|e),r[n]=H,l(n="POW_PRECISION")&&V(e,0,S,2,n)&&(W=0|e),r[n]=W,l(n="FORMAT")&&("object"==typeof e?J=e:z&&x(2,n+" not an object",e)),r[n]=J,r},a.max=function(){return D(arguments,M.lt)},a.min=function(){return D(arguments,M.gt)},a.random=function(){var e=9007199254740992,n=Math.random()*e&2097151?function(){return p(Math.random()*e)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(e){var t,r,i,o,u,s=0,l=[],c=new a(T);if(e=null!=e&&V(e,0,S,14)?0|e:B,o=g(e/b),j)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(o*=2));o>s;)u=131072*t[s]+(t[s+1]>>>11),u>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(l.push(u%1e14),s+=2);s=o/2}else if(crypto.randomBytes){for(t=crypto.randomBytes(o*=7);o>s;)u=281474976710656*(31&t[s])+1099511627776*t[s+1]+4294967296*t[s+2]+16777216*t[s+3]+(t[s+4]<<16)+(t[s+5]<<8)+t[s+6],u>=9e15?crypto.randomBytes(7).copy(t,s):(l.push(u%1e14),s+=7);s=o/7}else j=!1,z&&x(14,"crypto unavailable",crypto);if(!j)for(;o>s;)u=n(),9e15>u&&(l[s++]=u%1e14);for(o=l[--s],e%=b,o&&e&&(u=O[b-e],l[s]=p(o/u)*u);0===l[s];l.pop(),s--);if(0>s)l=[i=0];else{for(i=-1;0===l[0];l.splice(0,1),i-=b);for(s=1,u=l[0];u>=10;u/=10,s++);b>s&&(i-=b-s)}return c.e=i,c.c=l,c}}(),L=function(){function e(e,n,t){var r,i,o,u,s=0,l=e.length,c=n%R,f=n/R|0;for(e=e.slice();l--;)o=e[l]%R,u=e[l]/R|0,r=f*o+u*c,i=c*o+r%R*R+s,s=(i/t|0)+(r/R|0)+f*u,e[l]=i%t;return s&&(e=[s].concat(e)),e}function n(e,n,t,r){var i,o;if(t!=r)o=t>r?1:-1;else for(i=o=0;t>i;i++)if(e[i]!=n[i]){o=e[i]>n[i]?1:-1;break}return o}function r(e,n,t,r){for(var i=0;t--;)e[t]-=i,i=e[t]<n[t]?1:0,e[t]=i*r+e[t]-n[t];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(i,o,u,s,l){var c,f,h,g,d,m,w,v,y,O,R,S,A,E,D,F,_,x=i.s==o.s?1:-1,L=i.c,U=o.c;if(!(L&&L[0]&&U&&U[0]))return new a(i.s&&o.s&&(L?!U||L[0]!=U[0]:U)?L&&0==L[0]||!U?0*x:x/0:NaN);for(v=new a(x),y=v.c=[],f=i.e-o.e,x=u+f+1,l||(l=N,f=t(i.e/b)-t(o.e/b),x=x/b|0),h=0;U[h]==(L[h]||0);h++);if(U[h]>(L[h]||0)&&f--,0>x)y.push(1),g=!0;else{for(E=L.length,F=U.length,h=0,x+=2,d=p(l/(U[0]+1)),d>1&&(U=e(U,d,l),L=e(L,d,l),F=U.length,E=L.length),A=F,O=L.slice(0,F),R=O.length;F>R;O[R++]=0);_=U.slice(),_=[0].concat(_),D=U[0],U[1]>=l/2&&D++;do{if(d=0,c=n(U,O,F,R),0>c){if(S=O[0],F!=R&&(S=S*l+(O[1]||0)),d=p(S/D),d>1)for(d>=l&&(d=l-1),m=e(U,d,l),w=m.length,R=O.length;1==n(m,O,w,R);)d--,r(m,w>F?_:U,w,l),w=m.length,c=1;else 0==d&&(c=d=1),m=U.slice(),w=m.length;if(R>w&&(m=[0].concat(m)),r(O,m,R,l),R=O.length,-1==c)for(;n(U,O,F,R)<1;)d++,r(O,R>F?_:U,R,l),R=O.length}else 0===c&&(d++,O=[0]);y[h++]=d,O[0]?O[R++]=L[A]||0:(O=[L[A]],R=1)}while((A++<E||null!=O[0])&&x--);g=null!=O[0],y[0]||y.splice(0,1)}if(l==N){for(h=1,x=y[0];x>=10;x/=10,h++);I(v,u+(v.e=h+f*b-1)+1,s,g)}else v.e=f,v.r=+g;return v}}(),U=function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,n=/^([^.]+)\.$/,t=/^\.([^.]+)$/,r=/^-?(Infinity|NaN)$/,i=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(o,u,s,l){var c,f=s?u:u.replace(i,"");if(r.test(f))o.s=isNaN(f)?null:0>f?-1:1;else{if(!s&&(f=f.replace(e,function(e,n,t){return c="x"==(t=t.toLowerCase())?16:"b"==t?2:8,l&&l!=c?e:n}),l&&(c=l,f=f.replace(n,"$1").replace(t,"0.$1")),u!=f))return new a(f,c);z&&x(C,"not a"+(l?" base "+l:"")+" number",u),o.s=null}o.c=o.e=null,C=0}}(),M.absoluteValue=M.abs=function(){var e=new a(this);return e.s<0&&(e.s=1),e},M.ceil=function(){return I(new a(this),this.e+1,2)},M.comparedTo=M.cmp=function(e,n){return C=1,i(this,new a(e,n))},M.decimalPlaces=M.dp=function(){var e,n,r=this.c;if(!r)return null;if(e=((n=r.length-1)-t(this.e/b))*b,n=r[n])for(;n%10==0;n/=10,e--);return 0>e&&(e=0),e},M.dividedBy=M.div=function(e,n){return C=3,L(this,new a(e,n),B,P)},M.dividedToIntegerBy=M.divToInt=function(e,n){return C=4,L(this,new a(e,n),0,1)},M.equals=M.eq=function(e,n){return C=5,0===i(this,new a(e,n))},M.floor=function(){return I(new a(this),this.e+1,3)},M.greaterThan=M.gt=function(e,n){return C=6,i(this,new a(e,n))>0},M.greaterThanOrEqualTo=M.gte=function(e,n){return C=7,1===(n=i(this,new a(e,n)))||0===n},M.isFinite=function(){return!!this.c},M.isInteger=M.isInt=function(){return!!this.c&&t(this.e/b)>this.c.length-2},M.isNaN=function(){return!this.s},M.isNegative=M.isNeg=function(){return this.s<0},M.isZero=function(){return!!this.c&&0==this.c[0]},M.lessThan=M.lt=function(e,n){return C=8,i(this,new a(e,n))<0},M.lessThanOrEqualTo=M.lte=function(e,n){return C=9,-1===(n=i(this,new a(e,n)))||0===n},M.minus=M.sub=function(e,n){var r,i,o,u,s=this,l=s.s;if(C=10,e=new a(e,n),n=e.s,!l||!n)return new a(NaN);if(l!=n)return e.s=-n,s.plus(e);var c=s.e/b,f=e.e/b,h=s.c,g=e.c;if(!c||!f){if(!h||!g)return h?(e.s=-n,e):new a(g?s:NaN);if(!h[0]||!g[0])return g[0]?(e.s=-n,e):new a(h[0]?s:3==P?-0:0)}if(c=t(c),f=t(f),h=h.slice(),l=c-f){for((u=0>l)?(l=-l,o=h):(f=c,o=g),o.reverse(),n=l;n--;o.push(0));o.reverse()}else for(i=(u=(l=h.length)<(n=g.length))?l:n,l=n=0;i>n;n++)if(h[n]!=g[n]){u=h[n]<g[n];break}if(u&&(o=h,h=g,g=o,e.s=-e.s),n=(i=g.length)-(r=h.length),n>0)for(;n--;h[r++]=0);for(n=N-1;i>l;){if(h[--i]<g[i]){for(r=i;r&&!h[--r];h[r]=n);--h[r],h[i]+=N}h[i]-=g[i]}for(;0==h[0];h.splice(0,1),--f);return h[0]?_(e,h,f):(e.s=3==P?-1:1,e.c=[e.e=0],e)},M.modulo=M.mod=function(e,n){var t,r,i=this;return C=11,e=new a(e,n),!i.c||!e.s||e.c&&!e.c[0]?new a(NaN):!e.c||i.c&&!i.c[0]?new a(i):(9==H?(r=e.s,e.s=1,t=L(i,e,0,3),e.s=r,t.s*=r):t=L(i,e,0,H),i.minus(t.times(e)))},M.negated=M.neg=function(){var e=new a(this);return e.s=-e.s||null,e},M.plus=M.add=function(e,n){var r,i=this,o=i.s;if(C=12,e=new a(e,n),n=e.s,!o||!n)return new a(NaN);if(o!=n)return e.s=-n,i.minus(e);var u=i.e/b,s=e.e/b,l=i.c,c=e.c;if(!u||!s){if(!l||!c)return new a(o/0);if(!l[0]||!c[0])return c[0]?e:new a(l[0]?i:0*o)}if(u=t(u),s=t(s),l=l.slice(),o=u-s){for(o>0?(s=u,r=c):(o=-o,r=l),r.reverse();o--;r.push(0));r.reverse()}for(o=l.length,n=c.length,0>o-n&&(r=c,c=l,l=r,n=o),o=0;n;)o=(l[--n]=l[n]+c[n]+o)/N|0,l[n]=N===l[n]?0:l[n]%N;return o&&(l=[o].concat(l),++s),_(e,l,s)},M.precision=M.sd=function(e){var n,t,r=this,i=r.c;if(null!=e&&e!==!!e&&1!==e&&0!==e&&(z&&x(13,"argument"+d,e),e!=!!e&&(e=null)),!i)return null;if(t=i.length-1,n=t*b+1,t=i[t]){for(;t%10==0;t/=10,n--);for(t=i[0];t>=10;t/=10,n++);}return e&&r.e+1>n&&(n=r.e+1),n},M.round=function(e,n){var t=new a(this);return(null==e||V(e,0,S,15))&&I(t,~~e+this.e+1,null!=n&&V(n,0,8,15,m)?0|n:P),t},M.shift=function(e){var n=this;return V(e,-y,y,16,"argument")?n.times("1e"+f(e)):new a(n.c&&n.c[0]&&(-y>e||e>y)?n.s*(0>e?0:1/0):n)},M.squareRoot=M.sqrt=function(){var e,n,i,o,u,s=this,l=s.c,c=s.s,f=s.e,h=B+4,g=new a("0.5");if(1!==c||!l||!l[0])return new a(!c||0>c&&(!l||l[0])?NaN:l?s:1/0);if(c=Math.sqrt(+s),0==c||c==1/0?(n=r(l),(n.length+f)%2==0&&(n+="0"),c=Math.sqrt(n),f=t((f+1)/2)-(0>f||f%2),c==1/0?n="1e"+f:(n=c.toExponential(),n=n.slice(0,n.indexOf("e")+1)+f),i=new a(n)):i=new a(c+""),i.c[0])for(f=i.e,c=f+h,3>c&&(c=0);;)if(u=i,i=g.times(u.plus(L(s,u,h,1))),r(u.c).slice(0,c)===(n=r(i.c)).slice(0,c)){if(i.e<f&&--c,n=n.slice(c-3,c+1),"9999"!=n&&(o||"4999"!=n)){(!+n||!+n.slice(1)&&"5"==n.charAt(0))&&(I(i,i.e+B+2,1),e=!i.times(i).eq(s));break}if(!o&&(I(u,u.e+B+2,0),u.times(u).eq(s))){i=u;break}h+=4,c+=4,o=1}return I(i,i.e+B+1,P,e)},M.times=M.mul=function(e,n){var r,i,o,u,s,l,c,f,h,g,p,d,m,w,v,y=this,O=y.c,S=(C=17,e=new a(e,n)).c;if(!(O&&S&&O[0]&&S[0]))return!y.s||!e.s||O&&!O[0]&&!S||S&&!S[0]&&!O?e.c=e.e=e.s=null:(e.s*=y.s,O&&S?(e.c=[0],e.e=0):e.c=e.e=null),e;for(i=t(y.e/b)+t(e.e/b),e.s*=y.s,c=O.length,g=S.length,g>c&&(m=O,O=S,S=m,o=c,c=g,g=o),o=c+g,m=[];o--;m.push(0));for(w=N,v=R,o=g;--o>=0;){for(r=0,p=S[o]%v,d=S[o]/v|0,s=c,u=o+s;u>o;)f=O[--s]%v,h=O[s]/v|0,l=d*f+h*p,f=p*f+l%v*v+m[u]+r,r=(f/w|0)+(l/v|0)+d*h,m[u--]=f%w;m[u]=r}return r?++i:m.splice(0,1),_(e,m,i)},M.toDigits=function(e,n){var t=new a(this);return e=null!=e&&V(e,1,S,18,"precision")?0|e:null,n=null!=n&&V(n,0,8,18,m)?0|n:P,e?I(t,e,n):t},M.toExponential=function(e,n){return E(this,null!=e&&V(e,0,S,19)?~~e+1:null,n,19)},M.toFixed=function(e,n){return E(this,null!=e&&V(e,0,S,20)?~~e+this.e+1:null,n,20)},M.toFormat=function(e,n){var t=E(this,null!=e&&V(e,0,S,21)?~~e+this.e+1:null,n,21);if(this.c){var r,i=t.split("."),o=+J.groupSize,u=+J.secondaryGroupSize,s=J.groupSeparator,l=i[0],c=i[1],f=this.s<0,a=f?l.slice(1):l,h=a.length;if(u&&(r=o,o=u,u=r,h-=r),o>0&&h>0){for(r=h%o||o,l=a.substr(0,r);h>r;r+=o)l+=s+a.substr(r,o);u>0&&(l+=s+a.slice(r)),f&&(l="-"+l)}t=c?l+J.decimalSeparator+((u=+J.fractionGroupSize)?c.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+J.fractionGroupSeparator):c):l}return t},M.toFraction=function(e){var n,t,i,o,u,s,l,c,f,h=z,g=this,p=g.c,d=new a(T),m=t=new a(T),w=l=new a(T);if(null!=e&&(z=!1,s=new a(e),z=h,(!(h=s.isInt())||s.lt(T))&&(z&&x(22,"max denominator "+(h?"out of range":"not an integer"),e),e=!h&&s.c&&I(s,s.e+1,1).gte(T)?s:null)),!p)return g.toString();for(f=r(p),o=d.e=f.length-g.e-1,d.c[0]=O[(u=o%b)<0?b+u:u],e=!e||s.cmp(d)>0?o>0?d:m:s,u=G,G=1/0,s=new a(f),l.c[0]=0;c=L(s,d,0,1),i=t.plus(c.times(w)),1!=i.cmp(e);)t=w,w=i,m=l.plus(c.times(i=m)),l=i,d=s.minus(c.times(i=d)),s=i;return i=L(e.minus(t),w,0,1),l=l.plus(i.times(m)),t=t.plus(i.times(w)),l.s=m.s=g.s,o*=2,n=L(m,w,o,P).minus(g).abs().cmp(L(l,t,o,P).minus(g).abs())<1?[m.toString(),w.toString()]:[l.toString(),t.toString()],G=u,n},M.toNumber=function(){return+this},M.toPower=M.pow=function(e,n){var t,r,i,o=p(0>e?-e:+e),u=this;if(null!=n&&(C=23,n=new a(n)),!V(e,-y,y,23,"exponent")&&(!isFinite(e)||o>y&&(e/=0)||parseFloat(e)!=e&&!(e=NaN))||0==e)return t=Math.pow(+u,e),new a(n?t%n:t);for(n?e>1&&u.gt(T)&&u.isInt()&&n.gt(T)&&n.isInt()?u=u.mod(n):(i=n,n=null):W&&(t=g(W/b+2)),r=new a(T);;){if(o%2){if(r=r.times(u),!r.c)break;t?r.c.length>t&&(r.c.length=t):n&&(r=r.mod(n))}if(o=p(o/2),!o)break;u=u.times(u),t?u.c&&u.c.length>t&&(u.c.length=t):n&&(u=u.mod(n))}return n?r:(0>e&&(r=T.div(r)),i?r.mod(i):t?I(r,W,P):r)},M.toPrecision=function(e,n){return E(this,null!=e&&V(e,1,S,24,"precision")?0|e:null,n,24)},M.toString=function(e){var n,t=this,i=t.s,o=t.e;return null===o?i?(n="Infinity",0>i&&(n="-"+n)):n="NaN":(n=r(t.c),n=null!=e&&V(e,2,64,25,"base")?A(c(n,o),0|e,10,i):q>=o||o>=k?l(n,o):c(n,o),0>i&&t.c[0]&&(n="-"+n)),n},M.truncated=M.trunc=function(){return I(new a(this),this.e+1,1)},M.valueOf=M.toJSON=function(){var e,n=this,t=n.e;return null===t?n.toString():(e=r(n.c),e=q>=t||t>=k?l(e,t):c(e,t),n.s<0?"-"+e:e)},M.isBigNumber=!0,null!=e&&a.config(e),a}function t(e){var n=0|e;return e>0||e===n?n:n-1}function r(e){for(var n,t,r=1,i=e.length,o=e[0]+"";i>r;){for(n=e[r++]+"",t=b-n.length;t--;n="0"+n);o+=n}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function i(e,n){var t,r,i=e.c,o=n.c,u=e.s,s=n.s,l=e.e,c=n.e;if(!u||!s)return null;if(t=i&&!i[0],r=o&&!o[0],t||r)return t?r?0:-s:u;if(u!=s)return u;if(t=0>u,r=l==c,!i||!o)return r?0:!i^t?1:-1;if(!r)return l>c^t?1:-1;for(s=(l=i.length)<(c=o.length)?l:c,u=0;s>u;u++)if(i[u]!=o[u])return i[u]>o[u]^t?1:-1;return l==c?0:l>c^t?1:-1}function o(e,n,t){return(e=f(e))>=n&&t>=e}function u(e){return"[object Array]"==Object.prototype.toString.call(e)}function s(e,n,t){for(var r,i,o=[0],u=0,s=e.length;s>u;){for(i=o.length;i--;o[i]*=n);for(o[r=0]+=v.indexOf(e.charAt(u++));r<o.length;r++)o[r]>t-1&&(null==o[r+1]&&(o[r+1]=0),o[r+1]+=o[r]/t|0,o[r]%=t)}return o.reverse()}function l(e,n){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(0>n?"e":"e+")+n}function c(e,n){var t,r;if(0>n){for(r="0.";++n;r+="0");e=r+e}else if(t=e.length,++n>t){for(r="0",n-=t;--n;r+="0");e+=r}else t>n&&(e=e.slice(0,n)+"."+e.slice(n));return e}function f(e){return e=parseFloat(e),0>e?g(e):p(e)}var a,h=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,g=Math.ceil,p=Math.floor,d=" not a boolean or binary digit",m="rounding mode",w="number type has more than 15 significant digits",v="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",N=1e14,b=14,y=9007199254740991,O=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],R=1e7,S=1e9;a=n(),a["default"]=a.BigNumber=a,"function"==typeof define&&define.amd?define(function(){return a}):"undefined"!=typeof module&&module.exports?module.exports=a:(e||(e="undefined"!=typeof self?self:Function("return this")()),e.BigNumber=a)}(this); +//# sourceMappingURL=bignumber.js.map \ No newline at end of file diff --git a/node_modules/bignumber.js/bignumber.mjs b/node_modules/bignumber.js/bignumber.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f9537c28bf34c3815c656c98d6dbad3f3b812305 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.mjs @@ -0,0 +1,2717 @@ +/* + * + * bignumber.js v4.1.0 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com> + * MIT Expat Licence + * + */ + + +var BigNumber, + isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, + mathceil = Math.ceil, + mathfloor = Math.floor, + notBool = ' not a boolean or binary digit', + roundingMode = 'rounding mode', + tooManyDigits = 'number type has more than 15 significant digits', + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_', + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + /* + * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an + * exception is thrown (if ERRORS is true). + */ + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function constructorFactory(config) { + var div, parseNumeric, + + // id tracks the caller function, so its name can be included in error messages. + id = 0, + P = BigNumber.prototype, + ONE = new BigNumber(1), + + +/*************************************** EDITABLE DEFAULTS ****************************************/ + + + /* + * The default values below must be integers within the inclusive ranges stated. + * The values can also be changed at run-time using BigNumber.config. + */ + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + /* + * The rounding mode used when rounding to the above decimal places, and when using + * toExponential, toFixed, toFormat and toPrecision, and round (default value). + * UP 0 Away from zero. + * DOWN 1 Towards zero. + * CEIL 2 Towards +Infinity. + * FLOOR 3 Towards -Infinity. + * HALF_UP 4 Towards nearest neighbour. If equidistant, up. + * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + */ + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether BigNumber Errors are ever thrown. + ERRORS = true, // true or false + + // Change to intValidatorNoErrors if ERRORS is false. + isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + /* + * The modulo mode used when calculating the modulus: a mod n. + * The quotient (q = a / n) is calculated according to the corresponding rounding mode. + * The remainder (r) is calculated as: r = a - n * q. + * + * UP 0 The remainder is positive if the dividend is negative, else is negative. + * DOWN 1 The remainder has the same sign as the dividend. + * This modulo mode is commonly known as 'truncated division' and is + * equivalent to (a % n) in JavaScript. + * FLOOR 3 The remainder has the same sign as the divisor (Python %). + * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + * The remainder is always positive. + * + * The truncated division, floored division, Euclidian division and IEEE 754 remainder + * modes are commonly used for the modulus operation. + * Although the other rounding modes can also be used, they may not give useful results. + */ + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the toPower operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + decimalSeparator: '.', + groupSeparator: ',', + groupSize: 3, + secondaryGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + fractionGroupSize: 0 + }; + + +/**************************************************************************************************/ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * n {number|string|BigNumber} A numeric value. + * [b] {number} The base of n. Integer, 2 to 64 inclusive. + */ + function BigNumber( n, b ) { + var c, e, i, num, len, str, + x = this; + + // Enable constructor usage without new. + if ( !( x instanceof BigNumber ) ) { + + // 'BigNumber() constructor call without new: {n}' + if (ERRORS) raise( 26, 'constructor call without new', n ); + return new BigNumber( n, b ); + } + + // 'new BigNumber() base not an integer: {b}' + // 'new BigNumber() base out of range: {b}' + if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { + + // Duplicate. + if ( n instanceof BigNumber ) { + x.s = n.s; + x.e = n.e; + x.c = ( n = n.c ) ? n.slice() : n; + id = 0; + return; + } + + if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { + x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; + + // Fast path for integers. + if ( n === ~~n ) { + for ( e = 0, i = n; i >= 10; i /= 10, e++ ); + x.e = e; + x.c = [n]; + id = 0; + return; + } + + str = n + ''; + } else { + if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); + x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; + } + } else { + b = b | 0; + str = n + ''; + + // Ensure return value is rounded to DECIMAL_PLACES as with other bases. + // Allow exponential notation to be used with base 10 argument. + if ( b == 10 ) { + x = new BigNumber( n instanceof BigNumber ? n : str ); + return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); + } + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + // Any number in exponential form will fail due to the [Ee][+-]. + if ( ( num = typeof n == 'number' ) && n * 0 != 0 || + !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + + '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { + return parseNumeric( x, str, num, b ); + } + + if (num) { + x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; + + if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { + + // 'new BigNumber() number type has more than 15 significant digits: {n}' + raise( id, tooManyDigits, n ); + } + + // Prevent later check for length on converted number. + num = false; + } else { + x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; + } + + str = convertBase( str, 10, b, x.s ); + } + + // Decimal point? + if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); + + // Exponential form? + if ( ( i = str.search( /e/i ) ) > 0 ) { + + // Determine exponent. + if ( e < 0 ) e = i; + e += +str.slice( i + 1 ); + str = str.substring( 0, i ); + } else if ( e < 0 ) { + + // Integer. + e = str.length; + } + + // Determine leading zeros. + for ( i = 0; str.charCodeAt(i) === 48; i++ ); + + // Determine trailing zeros. + for ( len = str.length; str.charCodeAt(--len) === 48; ); + str = str.slice( i, len + 1 ); + + if (str) { + len = str.length; + + // Disallow numbers with over 15 significant digits if number type. + // 'new BigNumber() number type has more than 15 significant digits: {n}' + if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) { + raise( id, tooManyDigits, x.s * n ); + } + + e = e - i - 1; + + // Overflow? + if ( e > MAX_EXP ) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if ( e < MIN_EXP ) { + + // Zero. + x.c = [ x.e = 0 ]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = ( e + 1 ) % LOG_BASE; + if ( e < 0 ) i += LOG_BASE; + + if ( i < len ) { + if (i) x.c.push( +str.slice( 0, i ) ); + + for ( len -= LOG_BASE; i < len; ) { + x.c.push( +str.slice( i, i += LOG_BASE ) ); + } + + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } + + for ( ; i--; str += '0' ); + x.c.push( +str ); + } + } else { + + // Zero. + x.c = [ x.e = 0 ]; + } + + id = 0; + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.another = constructorFactory; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object or an argument list, with one or many of the following properties or + * parameters respectively: + * + * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive + * ROUNDING_MODE {number} Integer, 0 to 8 inclusive + * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or + * [integer -MAX to 0 incl., 0 to MAX incl.] + * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + * [integer -MAX to -1 incl., integer 1 to MAX incl.] + * ERRORS {boolean|number} true, false, 1 or 0 + * CRYPTO {boolean|number} true, false, 1 or 0 + * MODULO_MODE {number} 0 to 9 inclusive + * POW_PRECISION {number} 0 to MAX inclusive + * FORMAT {object} See BigNumber.prototype.toFormat + * decimalSeparator {string} + * groupSeparator {string} + * groupSize {number} + * secondaryGroupSize {number} + * fractionGroupSeparator {string} + * fractionGroupSize {number} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config(20, 4) is equivalent to + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined. + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function () { + var v, p, + i = 0, + r = {}, + a = arguments, + o = a[0], + has = o && typeof o == 'object' + ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; } + : function () { if ( a.length > i ) return ( v = a[i++] ) != null; }; + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // 'config() DECIMAL_PLACES not an integer: {v}' + // 'config() DECIMAL_PLACES out of range: {v}' + if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) { + DECIMAL_PLACES = v | 0; + } + r[p] = DECIMAL_PLACES; + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // 'config() ROUNDING_MODE not an integer: {v}' + // 'config() ROUNDING_MODE out of range: {v}' + if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) { + ROUNDING_MODE = v | 0; + } + r[p] = ROUNDING_MODE; + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // 'config() EXPONENTIAL_AT not an integer: {v}' + // 'config() EXPONENTIAL_AT out of range: {v}' + if ( has( p = 'EXPONENTIAL_AT' ) ) { + + if ( isArray(v) ) { + if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) { + TO_EXP_NEG = v[0] | 0; + TO_EXP_POS = v[1] | 0; + } + } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { + TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 ); + } + } + r[p] = [ TO_EXP_NEG, TO_EXP_POS ]; + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // 'config() RANGE not an integer: {v}' + // 'config() RANGE cannot be zero: {v}' + // 'config() RANGE out of range: {v}' + if ( has( p = 'RANGE' ) ) { + + if ( isArray(v) ) { + if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) { + MIN_EXP = v[0] | 0; + MAX_EXP = v[1] | 0; + } + } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { + if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 ); + else if (ERRORS) raise( 2, p + ' cannot be zero', v ); + } + } + r[p] = [ MIN_EXP, MAX_EXP ]; + + // ERRORS {boolean|number} true, false, 1 or 0. + // 'config() ERRORS not a boolean or binary digit: {v}' + if ( has( p = 'ERRORS' ) ) { + + if ( v === !!v || v === 1 || v === 0 ) { + id = 0; + isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors; + } else if (ERRORS) { + raise( 2, p + notBool, v ); + } + } + r[p] = ERRORS; + + // CRYPTO {boolean|number} true, false, 1 or 0. + // 'config() CRYPTO not a boolean or binary digit: {v}' + // 'config() crypto unavailable: {crypto}' + if ( has( p = 'CRYPTO' ) ) { + + if ( v === true || v === false || v === 1 || v === 0 ) { + if (v) { + v = typeof crypto == 'undefined'; + if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = true; + } else if (ERRORS) { + raise( 2, 'crypto unavailable', v ? void 0 : crypto ); + } else { + CRYPTO = false; + } + } else { + CRYPTO = false; + } + } else if (ERRORS) { + raise( 2, p + notBool, v ); + } + } + r[p] = CRYPTO; + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // 'config() MODULO_MODE not an integer: {v}' + // 'config() MODULO_MODE out of range: {v}' + if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) { + MODULO_MODE = v | 0; + } + r[p] = MODULO_MODE; + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // 'config() POW_PRECISION not an integer: {v}' + // 'config() POW_PRECISION out of range: {v}' + if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) { + POW_PRECISION = v | 0; + } + r[p] = POW_PRECISION; + + // FORMAT {object} + // 'config() FORMAT not an object: {v}' + if ( has( p = 'FORMAT' ) ) { + + if ( typeof v == 'object' ) { + FORMAT = v; + } else if (ERRORS) { + raise( 2, p + ' not an object', v ); + } + } + r[p] = FORMAT; + + return r; + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.max = function () { return maxOrMin( arguments, P.lt ); }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.min = function () { return maxOrMin( arguments, P.gt ); }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * 'random() decimal places not an integer: {dp}' + * 'random() decimal places out of range: {dp}' + * 'random() crypto unavailable: {crypto}' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor( Math.random() * pow2_53 ); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0; + k = mathceil( dp / LOG_BASE ); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues( new Uint32Array( k *= 2 ) ); + + for ( ; i < k; ) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if ( v >= 9e15 ) { + b = crypto.getRandomValues( new Uint32Array(2) ); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push( v % 1e14 ); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes( k *= 7 ); + + for ( ; i < k; ) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) + + ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) + + ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6]; + + if ( v >= 9e15 ) { + crypto.randomBytes(7).copy( a, i ); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push( v % 1e14 ); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + if (ERRORS) raise( 14, 'crypto unavailable', crypto ); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for ( ; i < k; ) { + v = random53bitInt(); + if ( v < 9e15 ) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if ( k && dp ) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor( k / v ) * v; + } + + // Remove trailing elements which are zero. + for ( ; c[i] === 0; c.pop(), i-- ); + + // Zero? + if ( i < 0 ) { + c = [ e = 0 ]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for ( i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if ( i < LOG_BASE ) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + // PRIVATE FUNCTIONS + + + // Convert a numeric string of baseIn to a numeric string of baseOut. + function convertBase( str, baseOut, baseIn, sign ) { + var d, e, k, r, x, xc, y, + i = str.indexOf( '.' ), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + if ( baseIn < 37 ) str = str.toLowerCase(); + + // Non-integer. + if ( i >= 0 ) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace( '.', '' ); + y = new BigNumber(baseIn); + x = y.pow( str.length - i ); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut ); + y.e = y.c.length; + } + + // Convert the number as integer. + xc = toBaseOut( str, baseIn, baseOut ); + e = k = xc.length; + + // Remove trailing zeros. + for ( ; xc[--k] == 0; xc.pop() ); + if ( !xc[0] ) return '0'; + + if ( i < 0 ) { + --e; + } else { + x.c = xc; + x.e = e; + + // sign is needed for correct rounding. + x.s = sign; + x = div( x, y, dp, rm, baseOut ); + xc = x.c; + r = x.r; + e = x.e; + } + + d = e + dp + 1; + + // The rounding digit, i.e. the digit to the right of the digit that may be rounded up. + i = xc[d]; + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) + : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == ( x.s < 0 ? 8 : 7 ) ); + + if ( d < 1 || !xc[0] ) { + + // 1^-dp or 0. + str = r ? toFixedPoint( '1', -dp ) : '0'; + } else { + xc.length = d; + + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for ( --baseOut; ++xc[--d] > baseOut; ) { + xc[d] = 0; + + if ( !d ) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for ( k = xc.length; !xc[--k]; ); + + // E.g. [4, 11, 15] becomes 4bf. + for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) ); + str = toFixedPoint( str, e ); + } + + // The caller will add the sign. + return str; + } + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply( x, k, base ) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for ( x = x.slice(); i--; ) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry; + carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare( a, b, aL, bL ) { + var i, cmp; + + if ( aL != bL ) { + cmp = aL > bL ? 1 : -1; + } else { + + for ( i = cmp = 0; i < aL; i++ ) { + + if ( a[i] != b[i] ) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + return cmp; + } + + function subtract( a, b, aL, base ) { + var i = 0; + + // Subtract b from a. + for ( ; aL--; ) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for ( ; !a[0] && a.length > 1; a.splice(0, 1) ); + } + + // x: dividend, y: divisor. + return function ( x, y, dp, rm, base ) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if ( !xc || !xc[0] || !yc || !yc[0] ) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if ( !base ) { + base = BASE; + e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE ); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ ); + if ( yc[i] > ( xc[i] || 0 ) ) e--; + + if ( s < 0 ) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor( base / ( yc[0] + 1 ) ); + + // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1. + // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) { + if ( n > 1 ) { + yc = multiply( yc, n, base ); + xc = multiply( xc, n, base ); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice( 0, yL ); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for ( ; remL < yL; rem[remL++] = 0 ); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if ( yc[1] >= base / 2 ) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare( yc, rem, yL, remL ); + + // If divisor < remainder. + if ( cmp < 0 ) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 ); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor( rem0 / yc0 ); + + // Algorithm: + // 1. product = divisor * trial digit (n) + // 2. if product > remainder: product -= divisor, n-- + // 3. remainder -= product + // 4. if product was < remainder at 2: + // 5. compare new remainder and divisor + // 6. If remainder > divisor: remainder -= divisor, n++ + + if ( n > 1 ) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply( yc, n, base ); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder. + // Trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while ( compare( prod, rem, prodL, remL ) == 1 ) { + n--; + + // Subtract divisor from product. + subtract( prod, yL < prodL ? yz : yc, prodL, base ); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if ( n == 0 ) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if ( prodL < remL ) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract( rem, prod, remL, base ); + remL = rem.length; + + // If product was < remainder. + if ( cmp == -1 ) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while ( compare( yc, rem, yL, remL ) < 1 ) { + n++; + + // Subtract divisor from remainder. + subtract( rem, yL < remL ? yz : yc, remL, base ); + remL = rem.length; + } + } + } else if ( cmp === 0 ) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if ( rem[0] ) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [ xc[xi] ]; + remL = 1; + } + } while ( ( xi++ < xL || rem[0] != null ) && s-- ); + + more = rem[0] != null; + + // Leading zero? + if ( !qc[0] ) qc.splice(0, 1); + } + + if ( base == BASE ) { + + // To calculate q.e, first get the number of digits of qc[0]. + for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ ); + round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more ); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n is a BigNumber. + * i is the index of the last digit required (i.e. the digit that may be rounded up). + * rm is the rounding mode. + * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24. + */ + function format( n, i, rm, caller ) { + var c0, e, ne, len, str; + + rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode ) + ? rm | 0 : ROUNDING_MODE; + + if ( !n.c ) return n.toString(); + c0 = n.c[0]; + ne = n.e; + + if ( i == null ) { + str = coeffToString( n.c ); + str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG + ? toExponential( str, ne ) + : toFixedPoint( str, ne ); + } else { + n = round( new BigNumber(n), i, rm ); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString( n.c ); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) { + + // Append zeros? + for ( ; len < i; str += '0', len++ ); + str = toExponential( str, e ); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint( str, e ); + + // Append zeros? + if ( e + 1 > len ) { + if ( --i > 0 ) for ( str += '.'; i--; str += '0' ); + } else { + i += e - len; + if ( i > 0 ) { + if ( e + 1 == len ) str += '.'; + for ( ; i--; str += '0' ); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + function maxOrMin( args, method ) { + var m, n, + i = 0; + + if ( isArray( args[0] ) ) args = args[0]; + m = new BigNumber( args[0] ); + + for ( ; ++i < args.length; ) { + n = new BigNumber( args[i] ); + + // If any number is NaN, return NaN. + if ( !n.s ) { + m = n; + break; + } else if ( method.call( m, n ) ) { + m = n; + } + } + + return m; + } + + + /* + * Return true if n is an integer in range, otherwise throw. + * Use for argument validation when ERRORS is true. + */ + function intValidatorWithErrors( n, min, max, caller, name ) { + if ( n < min || n > max || n != truncate(n) ) { + raise( caller, ( name || 'decimal places' ) + + ( n < min || n > max ? ' out of range' : ' not an integer' ), n ); + } + + return true; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise( n, c, e ) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for ( ; !c[--j]; c.pop() ); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for ( j = c[0]; j >= 10; j /= 10, i++ ); + + // Overflow? + if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if ( e < MIN_EXP ) { + + // Zero. + n.c = [ n.e = 0 ]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function ( x, str, num, b ) { + var base, + s = num ? str : str.replace( whitespaceOrPlus, '' ); + + // No exception on ±Infinity or NaN. + if ( isInfinityOrNaN.test(s) ) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if ( !num ) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace( basePrefix, function ( m, p1, p2 ) { + base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' ); + } + + if ( str != s ) return new BigNumber( s, base ); + } + + // 'new BigNumber() not a number: {n}' + // 'new BigNumber() not a base {b} number: {n}' + if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str ); + x.s = null; + } + + x.c = x.e = null; + id = 0; + } + })(); + + + // Throw a BigNumber Error. + function raise( caller, msg, val ) { + var error = new Error( [ + 'new BigNumber', // 0 + 'cmp', // 1 + 'config', // 2 + 'div', // 3 + 'divToInt', // 4 + 'eq', // 5 + 'gt', // 6 + 'gte', // 7 + 'lt', // 8 + 'lte', // 9 + 'minus', // 10 + 'mod', // 11 + 'plus', // 12 + 'precision', // 13 + 'random', // 14 + 'round', // 15 + 'shift', // 16 + 'times', // 17 + 'toDigits', // 18 + 'toExponential', // 19 + 'toFixed', // 20 + 'toFormat', // 21 + 'toFraction', // 22 + 'pow', // 23 + 'toPrecision', // 24 + 'toString', // 25 + 'BigNumber' // 26 + ][caller] + '() ' + msg + ': ' + val ); + + error.name = 'BigNumber Error'; + id = 0; + throw error; + } + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round( x, sd, rm, r ) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ ); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if ( i < 0 ) { + i += LOG_BASE; + j = sd; + n = xc[ ni = 0 ]; + + // Get the rounding digit at index j of n. + rd = n / pows10[ d - j - 1 ] % 10 | 0; + } else { + ni = mathceil( ( i + 1 ) / LOG_BASE ); + + if ( ni >= xc.length ) { + + if (r) { + + // Needed by sqrt. + for ( ; xc.length <= ni; xc.push(0) ); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for ( d = 1; k >= 10; k /= 10, d++ ); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0; + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] ); + + r = rm < 4 + ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) + : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 || + rm == ( x.s < 0 ? 8 : 7 ) ); + + if ( sd < 1 || !xc[0] ) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if ( i == 0 ) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[ LOG_BASE - i ]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0; + } + + // Round up? + if (r) { + + for ( ; ; ) { + + // If the digit to be rounded up is in the first element of xc... + if ( ni == 0 ) { + + // i will be the length of xc[0] before k is added. + for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ ); + j = xc[0] += k; + for ( k = 1; j >= 10; j /= 10, k++ ); + + // if i != k the length has increased. + if ( i != k ) { + x.e++; + if ( xc[0] == BASE ) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if ( xc[ni] != BASE ) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for ( i = xc.length; xc[--i] === 0; xc.pop() ); + } + + // Overflow? Infinity. + if ( x.e > MAX_EXP ) { + x.c = x.e = null; + + // Underflow? Zero. + } else if ( x.e < MIN_EXP ) { + x.c = [ x.e = 0 ]; + } + } + + return x; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if ( x.s < 0 ) x.s = 1; + return x; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole + * number in the direction of Infinity. + */ + P.ceil = function () { + return round( new BigNumber(this), this.e + 1, 2 ); + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = P.cmp = function ( y, b ) { + id = 1; + return compare( this, new BigNumber( y, b ) ); + }; + + + /* + * Return the number of decimal places of the value of this BigNumber, or null if the value + * of this BigNumber is ±Infinity or NaN. + */ + P.decimalPlaces = P.dp = function () { + var n, v, + c = this.c; + + if ( !c ) return null; + n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); + if ( n < 0 ) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function ( y, b ) { + id = 3; + return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.divToInt = function ( y, b ) { + id = 4; + return div( this, new BigNumber( y, b ), 0, 1 ); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise returns false. + */ + P.equals = P.eq = function ( y, b ) { + id = 5; + return compare( this, new BigNumber( y, b ) ) === 0; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole + * number in the direction of -Infinity. + */ + P.floor = function () { + return round( new BigNumber(this), this.e + 1, 3 ); + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise returns false. + */ + P.greaterThan = P.gt = function ( y, b ) { + id = 6; + return compare( this, new BigNumber( y, b ) ) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise returns false. + */ + P.greaterThanOrEqualTo = P.gte = function ( y, b ) { + id = 7; + return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise returns false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = P.isInt = function () { + return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise returns false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise returns false. + */ + P.isNegative = P.isNeg = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise returns false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise returns false. + */ + P.lessThan = P.lt = function ( y, b ) { + id = 8; + return compare( this, new BigNumber( y, b ) ) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise returns false. + */ + P.lessThanOrEqualTo = P.lte = function ( y, b ) { + id = 9; + return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = P.sub = function ( y, b ) { + var i, j, t, xLTy, + x = this, + a = x.s; + + id = 10; + y = new BigNumber( y, b ); + b = y.s; + + // Either NaN? + if ( !a || !b ) return new BigNumber(NaN); + + // Signs differ? + if ( a != b ) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if ( !xe || !ye ) { + + // Either Infinity? + if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); + + // Either zero? + if ( !xc[0] || !yc[0] ) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0 ); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if ( a = xe - ye ) { + + if ( xLTy = a < 0 ) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for ( b = a; b--; t.push(0) ); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; + + for ( a = b = 0; b < j; b++ ) { + + if ( xc[b] != yc[b] ) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; + + b = ( j = yc.length ) - ( i = xc.length ); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if ( b > 0 ) for ( ; b--; xc[i++] = 0 ); + b = BASE - 1; + + // Subtract yc from xc. + for ( ; j > a; ) { + + if ( xc[--j] < yc[j] ) { + for ( i = j; i && !xc[--i]; xc[i] = b ); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for ( ; xc[0] == 0; xc.splice(0, 1), --ye ); + + // Zero? + if ( !xc[0] ) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [ y.e = 0 ]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise( y, xc, ye ); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function ( y, b ) { + var q, s, + x = this; + + id = 11; + y = new BigNumber( y, b ); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if ( !x.c || !y.s || y.c && !y.c[0] ) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if ( !y.c || x.c && !x.c[0] ) { + return new BigNumber(x); + } + + if ( MODULO_MODE == 9 ) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div( x, y, 0, 3 ); + y.s = s; + q.s *= s; + } else { + q = div( x, y, 0, MODULO_MODE ); + } + + return x.minus( q.times(y) ); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = P.neg = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = P.add = function ( y, b ) { + var t, + x = this, + a = x.s; + + id = 12; + y = new BigNumber( y, b ); + b = y.s; + + // Either NaN? + if ( !a || !b ) return new BigNumber(NaN); + + // Signs differ? + if ( a != b ) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if ( !xe || !ye ) { + + // Return ±Infinity if either ±Infinity. + if ( !xc || !yc ) return new BigNumber( a / 0 ); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 ); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if ( a = xe - ye ) { + if ( a > 0 ) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for ( ; a--; t.push(0) ); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a; + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for ( a = 0; b; ) { + a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise( y, xc, ye ); + }; + + + /* + * Return the number of significant digits of the value of this BigNumber. + * + * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. + */ + P.precision = P.sd = function (z) { + var n, v, + x = this, + c = x.c; + + // 'precision() argument not a boolean or binary digit: {z}' + if ( z != null && z !== !!z && z !== 1 && z !== 0 ) { + if (ERRORS) raise( 13, 'argument' + notBool, z ); + if ( z != !!z ) z = null; + } + + if ( !c ) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if ( v = c[v] ) { + + // Subtract the number of trailing zeros of the last element. + for ( ; v % 10 == 0; v /= 10, n-- ); + + // Add the number of digits of the first element. + for ( v = c[0]; v >= 10; v /= 10, n++ ); + } + + if ( z && x.e + 1 > n ) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of + * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if + * omitted. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'round() decimal places out of range: {dp}' + * 'round() decimal places not an integer: {dp}' + * 'round() rounding mode not an integer: {rm}' + * 'round() rounding mode out of range: {rm}' + */ + P.round = function ( dp, rm ) { + var n = new BigNumber(this); + + if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) { + round( n, ~~dp + this.e + 1, rm == null || + !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 ); + } + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity + * otherwise. + * + * 'shift() argument not an integer: {k}' + * 'shift() argument out of range: {k}' + */ + P.shift = function (k) { + var n = this; + return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' ) + + // k < 1e+21, or truncate(k) will produce exponential notation. + ? n.times( '1e' + truncate(k) ) + : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER ) + ? n.s * ( k < 0 ? 0 : 1 / 0 ) + : n ); + }; + + + /* + * sqrt(-n) = N + * sqrt( N) = N + * sqrt(-I) = N + * sqrt( I) = I + * sqrt( 0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if ( s !== 1 || !c || !c[0] ) { + return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 ); + } + + // Initial estimate. + s = Math.sqrt( +x ); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if ( s == 0 || s == 1 / 0 ) { + n = coeffToString(c); + if ( ( n.length + e ) % 2 == 0 ) n += '0'; + s = Math.sqrt(n); + e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); + + if ( s == 1 / 0 ) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice( 0, n.indexOf('e') + 1 ) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber( s + '' ); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if ( r.c[0] ) { + e = r.e; + s = e + dp; + if ( s < 3 ) s = 0; + + // Newton-Raphson iteration. + for ( ; ; ) { + t = r; + r = half.times( t.plus( div( x, t, dp, 1 ) ) ); + + if ( coeffToString( t.c ).slice( 0, s ) === ( n = + coeffToString( r.c ) ).slice( 0, s ) ) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if ( r.e < e ) --s; + n = n.slice( s - 3, s + 1 ); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if ( n == '9999' || !rep && n == '4999' ) { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if ( !rep ) { + round( t, t.e + DECIMAL_PLACES + 2, 0 ); + + if ( t.times(t).eq(x) ) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) { + + // Truncate to the first rounding digit. + round( r, r.e + DECIMAL_PLACES + 2, 1 ); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber times the value of + * BigNumber(y, b). + */ + P.times = P.mul = function ( y, b ) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = ( id = 17, y = new BigNumber( y, b ) ).c; + + // Either NaN, ±Infinity or ±0? + if ( !xc || !yc || !xc[0] || !yc[0] ) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if ( !xc || !yc ) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; + + // Initialise the result array with zeros. + for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); + + base = BASE; + sqrtBase = SQRT_BASE; + + for ( i = ycL; --i >= 0; ) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for ( k = xcL, j = i + k; j > i; ) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c; + c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise( y, zc, e ); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of + * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toDigits() precision out of range: {sd}' + * 'toDigits() precision not an integer: {sd}' + * 'toDigits() rounding mode not an integer: {rm}' + * 'toDigits() rounding mode out of range: {rm}' + */ + P.toDigits = function ( sd, rm ) { + var n = new BigNumber(this); + sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0; + rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0; + return sd ? round( n, sd, rm ) : n; + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toExponential() decimal places not an integer: {dp}' + * 'toExponential() decimal places out of range: {dp}' + * 'toExponential() rounding mode not an integer: {rm}' + * 'toExponential() rounding mode out of range: {rm}' + */ + P.toExponential = function ( dp, rm ) { + return format( this, + dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 ); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toFixed() decimal places not an integer: {dp}' + * 'toFixed() decimal places out of range: {dp}' + * 'toFixed() rounding mode not an integer: {rm}' + * 'toFixed() rounding mode out of range: {rm}' + */ + P.toFixed = function ( dp, rm ) { + return format( this, dp != null && isValidInt( dp, 0, MAX, 20 ) + ? ~~dp + this.e + 1 : null, rm, 20 ); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the FORMAT object (see BigNumber.config). + * + * FORMAT = { + * decimalSeparator : '.', + * groupSeparator : ',', + * groupSize : 3, + * secondaryGroupSize : 0, + * fractionGroupSeparator : '\xA0', // non-breaking space + * fractionGroupSize : 0 + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toFormat() decimal places not an integer: {dp}' + * 'toFormat() decimal places out of range: {dp}' + * 'toFormat() rounding mode not an integer: {rm}' + * 'toFormat() rounding mode out of range: {rm}' + */ + P.toFormat = function ( dp, rm ) { + var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 ) + ? ~~dp + this.e + 1 : null, rm, 21 ); + + if ( this.c ) { + var i, + arr = str.split('.'), + g1 = +FORMAT.groupSize, + g2 = +FORMAT.secondaryGroupSize, + groupSeparator = FORMAT.groupSeparator, + intPart = arr[0], + fractionPart = arr[1], + isNeg = this.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) i = g1, g1 = g2, g2 = i, len -= i; + + if ( g1 > 0 && len > 0 ) { + i = len % g1 || g1; + intPart = intDigits.substr( 0, i ); + + for ( ; i < len; i += g1 ) { + intPart += groupSeparator + intDigits.substr( i, g1 ); + } + + if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize ) + ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ), + '$&' + FORMAT.fractionGroupSeparator ) + : fractionPart ) + : intPart; + } + + return str; + }; + + + /* + * Return a string array representing the value of this BigNumber as a simple fraction with + * an integer numerator and an integer denominator. The denominator will be a positive + * non-zero value less than or equal to the specified maximum denominator. If a maximum + * denominator is not specified, the denominator will be the lowest value necessary to + * represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator. + * + * 'toFraction() max denominator not an integer: {md}' + * 'toFraction() max denominator out of range: {md}' + */ + P.toFraction = function (md) { + var arr, d0, d2, e, exp, n, n0, q, s, + k = ERRORS, + x = this, + xc = x.c, + d = new BigNumber(ONE), + n1 = d0 = new BigNumber(ONE), + d1 = n0 = new BigNumber(ONE); + + if ( md != null ) { + ERRORS = false; + n = new BigNumber(md); + ERRORS = k; + + if ( !( k = n.isInt() ) || n.lt(ONE) ) { + + if (ERRORS) { + raise( 22, + 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md ); + } + + // ERRORS is false: + // If md is a finite non-integer >= 1, round it to an integer and use it. + md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null; + } + } + + if ( !xc ) return x.toString(); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ]; + md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for ( ; ; ) { + q = div( n, d, 0, 1 ); + d2 = d0.plus( q.times(d1) ); + if ( d2.cmp(md) == 1 ) break; + d0 = d1; + d1 = d2; + n1 = n0.plus( q.times( d2 = n1 ) ); + n0 = d2; + d = n.minus( q.times( d2 = d ) ); + n = d2; + } + + d2 = div( md.minus(d0), d1, 0, 1 ); + n0 = n0.plus( d2.times(n1) ); + d0 = d0.plus( d2.times(d1) ); + n0.s = n1.s = x.s; + e *= 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp( + div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1 + ? [ n1.toString(), d1.toString() ] + : [ n0.toString(), d0.toString() ]; + + MAX_EXP = exp; + return arr; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +this; + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber raised to the power n. + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using + * ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are positive integers, + * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0). + * + * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * [m] {number|string|BigNumber} The modulus. + * + * 'pow() exponent not an integer: {n}' + * 'pow() exponent out of range: {n}' + * + * Performs 54 loop iterations for n of 9007199254740991. + */ + P.toPower = P.pow = function ( n, m ) { + var k, y, z, + i = mathfloor( n < 0 ? -n : +n ), + x = this; + + if ( m != null ) { + id = 23; + m = new BigNumber(m); + } + + // Pass ±Infinity to Math.pow if exponent is out of range. + if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) && + ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) || + parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) { + k = Math.pow( +x, n ); + return new BigNumber( m ? k % m : k ); + } + + if (m) { + if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) { + x = x.mod(m); + } else { + z = m; + + // Nullify m so only a single mod operation is performed at the end. + m = null; + } + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + // (Using + 1.5 would give [9, 21] guard digits.) + k = mathceil( POW_PRECISION / LOG_BASE + 2 ); + } + + y = new BigNumber(ONE); + + for ( ; ; ) { + if ( i % 2 ) { + y = y.times(x); + if ( !y.c ) break; + if (k) { + if ( y.c.length > k ) y.c.length = k; + } else if (m) { + y = y.mod(m); + } + } + + i = mathfloor( i / 2 ); + if ( !i ) break; + x = x.times(x); + if (k) { + if ( x.c && x.c.length > k ) x.c.length = k; + } else if (m) { + x = x.mod(m); + } + } + + if (m) return y; + if ( n < 0 ) y = ONE.div(y); + + return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * 'toPrecision() precision not an integer: {sd}' + * 'toPrecision() precision out of range: {sd}' + * 'toPrecision() rounding mode not an integer: {rm}' + * 'toPrecision() rounding mode out of range: {rm}' + */ + P.toPrecision = function ( sd, rm ) { + return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' ) + ? sd | 0 : null, rm, 24 ); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to 64 inclusive. + * + * 'toString() base not an integer: {b}' + * 'toString() base out of range: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if ( e === null ) { + + if (s) { + str = 'Infinity'; + if ( s < 0 ) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + str = coeffToString( n.c ); + + if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential( str, e ) + : toFixedPoint( str, e ); + } else { + str = convertBase( toFixedPoint( str, e ), b | 0, 10, s ); + } + + if ( s < 0 && n.c[0] ) str = '-' + str; + } + + return str; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole + * number. + */ + P.truncated = P.trunc = function () { + return round( new BigNumber(this), this.e + 1, 1 ); + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + var str, + n = this, + e = n.e; + + if ( e === null ) return n.toString(); + + str = coeffToString( n.c ); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential( str, e ) + : toFixedPoint( str, e ); + + return n.s < 0 ? '-' + str : str; + }; + + + P.isBigNumber = true; + + if ( config != null ) BigNumber.config(config); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for ( ; i < j; ) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for ( ; z--; s = '0' + s ); + r += s; + } + + // Determine trailing zeros. + for ( j = r.length; r.charCodeAt(--j) === 48; ); + return r.slice( 0, j + 1 || 1 ); +} + + +// Compare the value of BigNumbers x and y. +function compare( x, y ) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if ( !i || !j ) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if ( a || b ) return a ? b ? 0 : -j : i; + + // Signs differ? + if ( i != j ) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if ( !b ) return k > l ^ a ? 1 : -1; + + j = ( k = xc.length ) < ( l = yc.length ) ? k : l; + + // Compare digit by digit. + for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Return true if n is a valid number in range, otherwise false. + * Use for argument validation when ERRORS is false. + * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10. + */ +function intValidatorNoErrors( n, min, max ) { + return ( n = truncate(n) ) >= min && n <= max; +} + + +function isArray(obj) { + return Object.prototype.toString.call(obj) == '[object Array]'; +} + + +/* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. convertBase('255', 10, 16) returns [15, 15]. + * Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. + */ +function toBaseOut( str, baseIn, baseOut ) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for ( ; i < len; ) { + for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn ); + arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) ); + + for ( ; j < arr.length; j++ ) { + + if ( arr[j] > baseOut - 1 ) { + if ( arr[j + 1] == null ) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); +} + + +function toExponential( str, e ) { + return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) + + ( e < 0 ? 'e' : 'e+' ) + e; +} + + +function toFixedPoint( str, e ) { + var len, z; + + // Negative exponent? + if ( e < 0 ) { + + // Prepend zeros. + for ( z = '0.'; ++e; z += '0' ); + str = z + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if ( ++e > len ) { + for ( z = '0', e -= len; --e; z += '0' ); + str += z; + } else if ( e < len ) { + str = str.slice( 0, e ) + '.' + str.slice(e); + } + } + + return str; +} + + +function truncate(n) { + n = parseFloat(n); + return n < 0 ? mathceil(n) : mathfloor(n); +} + + +// EXPORT + + +BigNumber = constructorFactory(); +BigNumber['default'] = BigNumber.BigNumber = BigNumber; + +export default BigNumber; diff --git a/node_modules/bignumber.js/bower.json b/node_modules/bignumber.js/bower.json new file mode 100644 index 0000000000000000000000000000000000000000..3144f5c3fc4c4bb7add34dc4cc630672007c2019 --- /dev/null +++ b/node_modules/bignumber.js/bower.json @@ -0,0 +1,36 @@ +{ + "name": "bignumber.js", + "main": "bignumber.js", + "version": "4.1.0", + "homepage": "https://github.com/MikeMcl/bignumber.js", + "authors": [ + "Michael Mclaughlin <M8ch88l@gmail.com>" + ], + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic", + "moduleType": [ + "amd", + "globals", + "node" + ], + "keywords": [ + "arbitrary", + "precision", + "arithmetic", + "big", + "number", + "decimal", + "float", + "biginteger", + "bigdecimal", + "bignumber", + "bigint", + "bignum" + ], + "license": "MIT", + "ignore": [ + ".*", + "*.json", + "test" + ] +} + diff --git a/node_modules/bignumber.js/doc/API.html b/node_modules/bignumber.js/doc/API.html new file mode 100644 index 0000000000000000000000000000000000000000..c8df246f0ca722f21c0ae21e51dbf8ffd646771f --- /dev/null +++ b/node_modules/bignumber.js/doc/API.html @@ -0,0 +1,2197 @@ +<!DOCTYPE HTML> +<html> +<head> +<meta charset="utf-8"> +<meta http-equiv="X-UA-Compatible" content="IE=edge"> +<meta name="Author" content="M Mclaughlin"> +<title>bignumber.js API</title> +<style> +html{font-size:100%} +body{background:#fff;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px; + line-height:1.65em;min-height:100%;margin:0} +body,i{color:#000} +.nav{background:#fff;position:fixed;top:0;bottom:0;left:0;width:200px;overflow-y:auto; + padding:15px 0 30px 15px} +div.container{width:600px;margin:50px 0 50px 240px} +p{margin:0 0 1em;width:600px} +pre,ul{margin:1em 0} +h1,h2,h3,h4,h5{margin:0;padding:1.5em 0 0} +h1,h2{padding:.75em 0} +h1{font:400 3em Verdana,sans-serif;color:#000;margin-bottom:1em} +h2{font-size:2.25em;color:#ff2a00} +h3{font-size:1.75em;color:#4dc71f} +h4{font-size:1.75em;color:#ff2a00;padding-bottom:.75em} +h5{font-size:1.2em;margin-bottom:.4em} +h6{font-size:1.1em;margin-bottom:0.8em;padding:0.5em 0} +dd{padding-top:.35em} +dt{padding-top:.5em} +b{font-weight:700} +dt b{font-size:1.3em} +a,a:visited{color:#ff2a00;text-decoration:none} +a:active,a:hover{outline:0;text-decoration:underline} +.nav a,.nav b,.nav a:visited{display:block;color:#ff2a00;font-weight:700; margin-top:15px} +.nav b{color:#4dc71f;margin-top:20px;cursor:default;width:auto} +ul{list-style-type:none;padding:0 0 0 20px} +.nav ul{line-height:14px;padding-left:0;margin:5px 0 0} +.nav ul a,.nav ul a:visited,span{display:inline;color:#000;font-family:Verdana,Geneva,sans-serif; + font-size:11px;font-weight:400;margin:0} +.inset,ul.inset{margin-left:20px} +.inset{font-size:.9em} +.nav li{width:auto;margin:0 0 3px} +.alias{font-style:italic;margin-left:20px} +table{border-collapse:collapse;border-spacing:0;border:2px solid #a7dbd8;margin:1.75em 0;padding:0} +td,th{text-align:left;margin:0;padding:2px 5px;border:1px dotted #a7dbd8} +th{border-top:2px solid #a7dbd8;border-bottom:2px solid #a7dbd8;color:#ff2a00} +code,pre{font-family:Consolas, monaco, monospace;font-weight:400} +pre{background:#f5f5f5;white-space:pre-wrap;word-wrap:break-word;border-left:5px solid #abef98; + padding:1px 0 1px 15px;margin:1.2em 0} +code,.nav-title{color:#ff2a00} +.end{margin-bottom:25px} +.centre{text-align:center} +.error-table{font-size:13px;width:100%} +#faq{margin:3em 0 0} +li span{float:right;margin-right:10px;color:#c0c0c0} +#js{font:inherit;color:#4dc71f} +</style> +</head> +<body> + + <div class="nav"> + + <a class='nav-title' href="#">API</a> + + <b> CONSTRUCTOR </b> + <ul> + <li><a href="#bignumber">BigNumber</a></li> + </ul> + + <a href="#methods">Methods</a> + <ul> + <li><a href="#another">another</a></li> + <li><a href="#config" >config</a></li> + <li> + <ul class="inset"> + <li><a href="#decimal-places">DECIMAL_PLACES</a></li> + <li><a href="#rounding-mode" >ROUNDING_MODE</a></li> + <li><a href="#exponential-at">EXPONENTIAL_AT</a></li> + <li><a href="#range" >RANGE</a></li> + <li><a href="#errors" >ERRORS</a></li> + <li><a href="#crypto" >CRYPTO</a></li> + <li><a href="#modulo-mode" >MODULO_MODE</a></li> + <li><a href="#pow-precision" >POW_PRECISION</a></li> + <li><a href="#format" >FORMAT</a></li> + </ul> + </li> + <li><a href="#max" >max</a></li> + <li><a href="#min" >min</a></li> + <li><a href="#random">random</a></li> + </ul> + + <a href="#constructor-properties">Properties</a> + <ul> + <li><a href="#round-up" >ROUND_UP</a></li> + <li><a href="#round-down" >ROUND_DOWN</a></li> + <li><a href="#round-ceil" >ROUND_CEIL</a></li> + <li><a href="#round-floor" >ROUND_FLOOR</a></li> + <li><a href="#round-half-up" >ROUND_HALF_UP</a></li> + <li><a href="#round-half-down" >ROUND_HALF_DOWN</a></li> + <li><a href="#round-half-even" >ROUND_HALF_EVEN</a></li> + <li><a href="#round-half-ceil" >ROUND_HALF_CEIL</a></li> + <li><a href="#round-half-floor">ROUND_HALF_FLOOR</a></li> + </ul> + + <b> INSTANCE </b> + + <a href="#prototype-methods">Methods</a> + <ul> + <li><a href="#abs" >absoluteValue </a><span>abs</span> </li> + <li><a href="#ceil" >ceil </a> </li> + <li><a href="#cmp" >comparedTo </a><span>cmp</span> </li> + <li><a href="#dp" >decimalPlaces </a><span>dp</span> </li> + <li><a href="#div" >dividedBy </a><span>div</span> </li> + <li><a href="#divInt" >dividedToIntegerBy </a><span>divToInt</span></li> + <li><a href="#eq" >equals </a><span>eq</span> </li> + <li><a href="#floor" >floor </a> </li> + <li><a href="#gt" >greaterThan </a><span>gt</span> </li> + <li><a href="#gte" >greaterThanOrEqualTo</a><span>gte</span> </li> + <li><a href="#isF" >isFinite </a> </li> + <li><a href="#isInt" >isInteger </a><span>isInt</span> </li> + <li><a href="#isNaN" >isNaN </a> </li> + <li><a href="#isNeg" >isNegative </a><span>isNeg</span> </li> + <li><a href="#isZ" >isZero </a> </li> + <li><a href="#lt" >lessThan </a><span>lt</span> </li> + <li><a href="#lte" >lessThanOrEqualTo </a><span>lte</span> </li> + <li><a href="#minus" >minus </a><span>sub</span> </li> + <li><a href="#mod" >modulo </a><span>mod</span> </li> + <li><a href="#neg" >negated </a><span>neg</span> </li> + <li><a href="#plus" >plus </a><span>add</span> </li> + <li><a href="#sd" >precision </a><span>sd</span> </li> + <li><a href="#round" >round </a> </li> + <li><a href="#shift" >shift </a> </li> + <li><a href="#sqrt" >squareRoot </a><span>sqrt</span> </li> + <li><a href="#times" >times </a><span>mul</span> </li> + <li><a href="#toD" >toDigits </a> </li> + <li><a href="#toE" >toExponential </a> </li> + <li><a href="#toFix" >toFixed </a> </li> + <li><a href="#toFor" >toFormat </a> </li> + <li><a href="#toFr" >toFraction </a> </li> + <li><a href="#toJSON" >toJSON </a> </li> + <li><a href="#toN" >toNumber </a> </li> + <li><a href="#pow" >toPower </a><span>pow</span> </li> + <li><a href="#toP" >toPrecision </a> </li> + <li><a href="#toS" >toString </a> </li> + <li><a href="#trunc" >truncated </a><span>trunc</span> </li> + <li><a href="#valueOf">valueOf </a> </li> + </ul> + + <a href="#instance-properties">Properties</a> + <ul> + <li><a href="#coefficient">c: coefficient</a></li> + <li><a href="#exponent" >e: exponent</a></li> + <li><a href="#sign" >s: sign</a></li> + <li><a href="#isbig" >isBigNumber</a></li> + </ul> + + <a href="#zero-nan-infinity">Zero, NaN & Infinity</a> + <a href="#Errors">Errors</a> + <a class='end' href="#faq">FAQ</a> + + </div> + + <div class="container"> + + <h1>bignumber<span id='js'>.js</span></h1> + + <p>A JavaScript library for arbitrary-precision arithmetic.</p> + <p><a href="https://github.com/MikeMcl/bignumber.js">Hosted on GitHub</a>. </p> + + <h2>API</h2> + + <p> + See the <a href='https://github.com/MikeMcl/bignumber.js'>README</a> on GitHub for a + quick-start introduction. + </p> + <p> + In all examples below, <code>var</code> and semicolons are not shown, and if a commented-out + value is in quotes it means <code>toString</code> has been called on the preceding expression. + </p> + + + <h3>CONSTRUCTOR</h3> + + <h5 id="bignumber"> + BigNumber<code class='inset'>BigNumber(value [, base]) <i>⇒ BigNumber</i></code> + </h5> + <dl> + <dt><code>value</code></dt> + <dd> + <i>number|string|BigNumber</i>: see <a href='#range'>RANGE</a> for + range. + </dd> + <dd> + A numeric value. + </dd> + <dd> + Legitimate values include ±<code>0</code>, ±<code>Infinity</code> and + <code>NaN</code>. + </dd> + <dd> + Values of type <em>number</em> with more than <code>15</code> significant digits are + considered invalid (if <a href='#errors'><code>ERRORS</code></a> is true) as calling + <code><a href='#toS'>toString</a></code> or <code><a href='#valueOf'>valueOf</a></code> on + such numbers may not result in the intended value. + <pre>console.log( 823456789123456.3 ); // 823456789123456.2</pre> + </dd> + <dd> + There is no limit to the number of digits of a value of type <em>string</em> (other than + that of JavaScript's maximum array size). + </dd> + <dd> + Decimal string values may be in exponential, as well as normal (fixed-point) notation. + Non-decimal values must be in normal notation. + </dd> + <dd> + String values in hexadecimal literal form, e.g. <code>'0xff'</code>, are valid, as are + string values with the octal and binary prefixs <code>'0o'</code> and <code>'0b'</code>. + String values in octal literal form without the prefix will be interpreted as + decimals, e.g. <code>'011'</code> is interpreted as 11, not 9. + </dd> + <dd>Values in any base may have fraction digits.</dd> + <dd> + For bases from <code>10</code> to <code>36</code>, lower and/or upper case letters can be + used to represent values from <code>10</code> to <code>35</code>. + </dd> + <dd> + For bases above 36, <code>a-z</code> represents values from <code>10</code> to + <code>35</code>, <code>A-Z</code> from <code>36</code> to <code>61</code>, and + <code>$</code> and <code>_</code> represent <code>62</code> and <code>63</code> respectively + <i>(this can be changed by editing the <code>ALPHABET</code> variable near the top of the + source file)</i>. + </dd> + </dl> + <dl> + <dt><code>base</code></dt> + <dd> + <i>number</i>: integer, <code>2</code> to <code>64</code> inclusive + </dd> + <dd>The base of <code>value</code>.</dd> + <dd> + If <code>base</code> is omitted, or is <code>null</code> or <code>undefined</code>, base + <code>10</code> is assumed. + </dd> + </dl> + <br /> + <p>Returns a new instance of a BigNumber object.</p> + <p> + If a base is specified, the value is rounded according to + the current <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration. + </p> + <p> + See <a href='#Errors'>Errors</a> for the treatment of an invalid <code>value</code> or + <code>base</code>. + </p> + <pre> +x = new BigNumber(9) // '9' +y = new BigNumber(x) // '9' + +// 'new' is optional if ERRORS is false +BigNumber(435.345) // '435.345' + +new BigNumber('5032485723458348569331745.33434346346912144534543') +new BigNumber('4.321e+4') // '43210' +new BigNumber('-735.0918e-430') // '-7.350918e-428' +new BigNumber(Infinity) // 'Infinity' +new BigNumber(NaN) // 'NaN' +new BigNumber('.5') // '0.5' +new BigNumber('+2') // '2' +new BigNumber(-10110100.1, 2) // '-180.5' +new BigNumber(-0b10110100.1) // '-180.5' +new BigNumber('123412421.234324', 5) // '607236.557696' +new BigNumber('ff.8', 16) // '255.5' +new BigNumber('0xff.8') // '255.5'</pre> + <p> + The following throws <code>'not a base 2 number'</code> if + <a href='#errors'><code>ERRORS</code></a> is true, otherwise it returns a BigNumber with value + <code>NaN</code>. + </p> + <pre>new BigNumber(9, 2)</pre> + <p> + The following throws <code>'number type has more than 15 significant digits'</code> if + <a href='#errors'><code>ERRORS</code></a> is true, otherwise it returns a BigNumber with value + <code>96517860459076820</code>. + </p> + <pre>new BigNumber(96517860459076817.4395)</pre> + <p> + The following throws <code>'not a number'</code> if <a href='#errors'><code>ERRORS</code></a> + is true, otherwise it returns a BigNumber with value <code>NaN</code>. + </p> + <pre>new BigNumber('blurgh')</pre> + <p> + A value is only rounded by the constructor if a base is specified. + </p> + <pre>BigNumber.config({ DECIMAL_PLACES: 5 }) +new BigNumber(1.23456789) // '1.23456789' +new BigNumber(1.23456789, 10) // '1.23457'</pre> + + + + <h4 id="methods">Methods</h4> + <p>The static methods of a BigNumber constructor.</p> + + + + + <h5 id="another"> + another<code class='inset'>.another([obj]) <i>⇒ BigNumber constructor</i></code> + </h5> + <p><code>obj</code>: <i>object</i></p> + <p> + Returns a new independent BigNumber constructor with configuration as described by + <code>obj</code> (see <a href='#config'><code>config</code></a>), or with the default + configuration if <code>obj</code> is <code>null</code> or <code>undefined</code>. + </p> + <pre>BigNumber.config({ DECIMAL_PLACES: 5 }) +BN = BigNumber.another({ DECIMAL_PLACES: 9 }) + +x = new BigNumber(1) +y = new BN(1) + +x.div(3) // 0.33333 +y.div(3) // 0.333333333 + +// BN = BigNumber.another({ DECIMAL_PLACES: 9 }) is equivalent to: +BN = BigNumber.another() +BN.config({ DECIMAL_PLACES: 9 })</pre> + + + + <h5 id="config">config<code class='inset'>set([obj]) <i>⇒ object</i></code></h5> + <p> + <code>obj</code>: <i>object</i>: an object that contains some or all of the following + properties. + </p> + <p>Configures the settings for this particular BigNumber constructor.</p> + <p><i>Note: the configuration can also be supplied as an argument list, see below.</i></p> + <dl class='inset'> + <dt id="decimal-places"><code><b>DECIMAL_PLACES</b></code></dt> + <dd> + <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br /> + Default value: <code>20</code> + </dd> + <dd> + The <u>maximum</u> number of decimal places of the results of operations involving + division, i.e. division, square root and base conversion operations, and power + operations with negative exponents.<br /> + </dd> + <dd> + <pre>BigNumber.config({ DECIMAL_PLACES: 5 }) +BigNumber.set({ DECIMAL_PLACES: 5 }) // equivalent +BigNumber.config(5) // equivalent</pre> + </dd> + + + + <dt id="rounding-mode"><code><b>ROUNDING_MODE</b></code></dt> + <dd> + <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive<br /> + Default value: <code>4</code> <a href="#round-half-up">(<code>ROUND_HALF_UP</code>)</a> + </dd> + <dd> + The rounding mode used in the above operations and the default rounding mode of + <a href='#round'><code>round</code></a>, + <a href='#toE'><code>toExponential</code></a>, + <a href='#toFix'><code>toFixed</code></a>, + <a href='#toFor'><code>toFormat</code></a> and + <a href='#toP'><code>toPrecision</code></a>. + </dd> + <dd>The modes are available as enumerated properties of the BigNumber constructor.</dd> + <dd> + <pre>BigNumber.config({ ROUNDING_MODE: 0 }) +BigNumber.config(null, BigNumber.ROUND_UP) // equivalent</pre> + </dd> + + + + <dt id="exponential-at"><code><b>EXPONENTIAL_AT</b></code></dt> + <dd> + <i>number</i>: integer, magnitude <code>0</code> to <code>1e+9</code> inclusive, or + <br /> + <i>number</i>[]: [ integer <code>-1e+9</code> to <code>0</code> inclusive, integer + <code>0</code> to <code>1e+9</code> inclusive ]<br /> + Default value: <code>[-7, 20]</code> + </dd> + <dd> + The exponent value(s) at which <code>toString</code> returns exponential notation. + </dd> + <dd> + If a single number is assigned, the value is the exponent magnitude.<br /> + If an array of two numbers is assigned then the first number is the negative exponent + value at and beneath which exponential notation is used, and the second number is the + positive exponent value at and above which the same. + </dd> + <dd> + For example, to emulate JavaScript numbers in terms of the exponent values at which they + begin to use exponential notation, use <code>[-7, 20]</code>. + </dd> + <dd> + <pre>BigNumber.config({ EXPONENTIAL_AT: 2 }) +new BigNumber(12.3) // '12.3' e is only 1 +new BigNumber(123) // '1.23e+2' +new BigNumber(0.123) // '0.123' e is only -1 +new BigNumber(0.0123) // '1.23e-2' + +BigNumber.config({ EXPONENTIAL_AT: [-7, 20] }) +new BigNumber(123456789) // '123456789' e is only 8 +new BigNumber(0.000000123) // '1.23e-7' + +// Almost never return exponential notation: +BigNumber.config({ EXPONENTIAL_AT: 1e+9 }) + +// Always return exponential notation: +BigNumber.config({ EXPONENTIAL_AT: 0 })</pre> + </dd> + <dd> + Regardless of the value of <code>EXPONENTIAL_AT</code>, the <code>toFixed</code> method + will always return a value in normal notation and the <code>toExponential</code> method + will always return a value in exponential form. + </dd> + <dd> + Calling <code>toString</code> with a base argument, e.g. <code>toString(10)</code>, will + also always return normal notation. + </dd> + + + + <dt id="range"><code><b>RANGE</b></code></dt> + <dd> + <i>number</i>: integer, magnitude <code>1</code> to <code>1e+9</code> inclusive, or + <br /> + <i>number</i>[]: [ integer <code>-1e+9</code> to <code>-1</code> inclusive, integer + <code>1</code> to <code>1e+9</code> inclusive ]<br /> + Default value: <code>[-1e+9, 1e+9]</code> + </dd> + <dd> + The exponent value(s) beyond which overflow to <code>Infinity</code> and underflow to + zero occurs. + </dd> + <dd> + If a single number is assigned, it is the maximum exponent magnitude: values wth a + positive exponent of greater magnitude become <code>Infinity</code> and those with a + negative exponent of greater magnitude become zero. + <dd> + If an array of two numbers is assigned then the first number is the negative exponent + limit and the second number is the positive exponent limit. + </dd> + <dd> + For example, to emulate JavaScript numbers in terms of the exponent values at which they + become zero and <code>Infinity</code>, use <code>[-324, 308]</code>. + </dd> + <dd> + <pre>BigNumber.config({ RANGE: 500 }) +BigNumber.config().RANGE // [ -500, 500 ] +new BigNumber('9.999e499') // '9.999e+499' +new BigNumber('1e500') // 'Infinity' +new BigNumber('1e-499') // '1e-499' +new BigNumber('1e-500') // '0' + +BigNumber.config({ RANGE: [-3, 4] }) +new BigNumber(99999) // '99999' e is only 4 +new BigNumber(100000) // 'Infinity' e is 5 +new BigNumber(0.001) // '0.01' e is only -3 +new BigNumber(0.0001) // '0' e is -4</pre> + </dd> + <dd> + The largest possible magnitude of a finite BigNumber is + <code>9.999...e+1000000000</code>.<br /> + The smallest possible magnitude of a non-zero BigNumber is <code>1e-1000000000</code>. + </dd> + + + + <dt id="errors"><code><b>ERRORS</b></code></dt> + <dd> + <i>boolean|number</i>: <code>true</code>, <code>false</code>, <code>0</code> or + <code>1</code>.<br /> + Default value: <code>true</code> + </dd> + <dd> + The value that determines whether BigNumber Errors are thrown.<br /> + If <code>ERRORS</code> is false, no errors will be thrown. + </dd> + <dd>See <a href='#Errors'>Errors</a>.</dd> + <dd><pre>BigNumber.config({ ERRORS: false })</pre></dd> + + + + <dt id="crypto"><code><b>CRYPTO</b></code></dt> + <dd> + <i>boolean|number</i>: <code>true</code>, <code>false</code>, <code>0</code> or + <code>1</code>.<br /> + Default value: <code>false</code> + </dd> + <dd> + The value that determines whether cryptographically-secure pseudo-random number + generation is used. + </dd> + <dd> + If <code>CRYPTO</code> is set to <code>true</code> then the + <a href='#random'><code>random</code></a> method will generate random digits using + <code>crypto.getRandomValues</code> in browsers that support it, or + <code>crypto.randomBytes</code> if using a version of Node.js that supports it. + </dd> + <dd> + If neither function is supported by the host environment then attempting to set + <code>CRYPTO</code> to <code>true</code> will fail, and if <code>ERRORS</code> + is <code>true</code> an exception will be thrown. + </dd> + <dd> + If <code>CRYPTO</code> is <code>false</code> then the source of randomness used will be + <code>Math.random</code> (which is assumed to generate at least <code>30</code> bits of + randomness). + </dd> + <dd>See <a href='#random'><code>random</code></a>.</dd> + <dd> + <pre>BigNumber.config({ CRYPTO: true }) +BigNumber.config().CRYPTO // true +BigNumber.random() // 0.54340758610486147524</pre> + </dd> + + + + <dt id="modulo-mode"><code><b>MODULO_MODE</b></code></dt> + <dd> + <i>number</i>: integer, <code>0</code> to <code>9</code> inclusive<br /> + Default value: <code>1</code> (<a href="#round-down"><code>ROUND_DOWN</code></a>) + </dd> + <dd>The modulo mode used when calculating the modulus: <code>a mod n</code>.</dd> + <dd> + The quotient, <code>q = a / n</code>, is calculated according to the + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> that corresponds to the chosen + <code>MODULO_MODE</code>. + </dd> + <dd>The remainder, <code>r</code>, is calculated as: <code>r = a - n * q</code>.</dd> + <dd> + The modes that are most commonly used for the modulus/remainder operation are shown in + the following table. Although the other rounding modes can be used, they may not give + useful results. + </dd> + <dd> + <table> + <tr><th>Property</th><th>Value</th><th>Description</th></tr> + <tr> + <td><b>ROUND_UP</b></td><td class='centre'>0</td> + <td> + The remainder is positive if the dividend is negative, otherwise it is negative. + </td> + </tr> + <tr> + <td><b>ROUND_DOWN</b></td><td class='centre'>1</td> + <td> + The remainder has the same sign as the dividend.<br /> + This uses 'truncating division' and matches the behaviour of JavaScript's + remainder operator <code>%</code>. + </td> + </tr> + <tr> + <td><b>ROUND_FLOOR</b></td><td class='centre'>3</td> + <td> + The remainder has the same sign as the divisor.<br /> + This matches Python's <code>%</code> operator. + </td> + </tr> + <tr> + <td><b>ROUND_HALF_EVEN</b></td><td class='centre'>6</td> + <td>The <i>IEEE 754</i> remainder function.</td> + </tr> + <tr> + <td><b>EUCLID</b></td><td class='centre'>9</td> + <td> + The remainder is always positive. Euclidian division: <br /> + <code>q = sign(n) * floor(a / abs(n))</code> + </td> + </tr> + </table> + </dd> + <dd> + The rounding/modulo modes are available as enumerated properties of the BigNumber + constructor. + </dd> + <dd>See <a href='#mod'><code>modulo</code></a>.</dd> + <dd> + <pre>BigNumber.config({ MODULO_MODE: BigNumber.EUCLID }) +BigNumber.config({ MODULO_MODE: 9 }) // equivalent</pre> + </dd> + + + + <dt id="pow-precision"><code><b>POW_PRECISION</b></code></dt> + <dd> + <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive.<br /> + Default value: <code>0</code> + </dd> + <dd> + The <i>maximum</i> number of significant digits of the result of the power operation + (unless a modulus is specified). + </dd> + <dd>If set to <code>0</code>, the number of signifcant digits will not be limited.</dd> + <dd>See <a href='#pow'><code>toPower</code></a>.</dd> + <dd><pre>BigNumber.config({ POW_PRECISION: 100 })</pre></dd> + + + + <dt id="format"><code><b>FORMAT</b></code></dt> + <dd><i>object</i></dd> + <dd> + The <code>FORMAT</code> object configures the format of the string returned by the + <a href='#toFor'><code>toFormat</code></a> method. + </dd> + <dd> + The example below shows the properties of the <code>FORMAT</code> object that are + recognised, and their default values. + </dd> + <dd> + Unlike the other configuration properties, the values of the properties of the + <code>FORMAT</code> object will not be checked for validity. The existing + <code>FORMAT</code> object will simply be replaced by the object that is passed in. + Note that all the properties shown below do not have to be included. + </dd> + <dd>See <a href='#toFor'><code>toFormat</code></a> for examples of usage.</dd> + <dd> + <pre> +BigNumber.config({ + FORMAT: { + // the decimal separator + decimalSeparator: '.', + // the grouping separator of the integer part + groupSeparator: ',', + // the primary grouping size of the integer part + groupSize: 3, + // the secondary grouping size of the integer part + secondaryGroupSize: 0, + // the grouping separator of the fraction part + fractionGroupSeparator: ' ', + // the grouping size of the fraction part + fractionGroupSize: 0 + } +});</pre> + </dd> + </dl> + <br /> + <p>Returns an object with the above properties and their current values.</p> + <p> + If the value to be assigned to any of the above properties is <code>null</code> or + <code>undefined</code> it is ignored. + </p> + <p>See <a href='#Errors'>Errors</a> for the treatment of invalid values.</p> + <pre> +BigNumber.config({ + DECIMAL_PLACES: 40, + ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + EXPONENTIAL_AT: [-10, 20], + RANGE: [-500, 500], + ERRORS: true, + CRYPTO: true, + MODULO_MODE: BigNumber.ROUND_FLOOR, + POW_PRECISION: 80, + FORMAT: { + groupSize: 3, + groupSeparator: ' ', + decimalSeparator: ',' + } +}); + +// Alternatively but equivalently (excluding FORMAT): +BigNumber.config( 40, 7, [-10, 20], 500, 1, 1, 3, 80 ) + +obj = BigNumber.config(); +obj.ERRORS // true +obj.RANGE // [-500, 500]</pre> + + + + <h5 id="max"> + max<code class='inset'>.max([arg1 [, arg2, ...]]) <i>⇒ BigNumber</i></code> + </h5> + <p> + <code>arg1</code>, <code>arg2</code>, ...: <i>number|string|BigNumber</i><br /> + <i>See <code><a href="#bignumber">BigNumber</a></code> for further parameter details.</i> + </p> + <p> + Returns a BigNumber whose value is the maximum of <code>arg1</code>, + <code>arg2</code>,... . + </p> + <p>The argument to this method can also be an array of values.</p> + <p>The return value is always exact and unrounded.</p> + <pre>x = new BigNumber('3257869345.0378653') +BigNumber.max(4e9, x, '123456789.9') // '4000000000' + +arr = [12, '13', new BigNumber(14)] +BigNumber.max(arr) // '14'</pre> + + + + <h5 id="min"> + min<code class='inset'>.min([arg1 [, arg2, ...]]) <i>⇒ BigNumber</i></code> + </h5> + <p> + <code>arg1</code>, <code>arg2</code>, ...: <i>number|string|BigNumber</i><br /> + <i>See <code><a href="#bignumber">BigNumber</a></code> for further parameter details.</i> + </p> + <p> + Returns a BigNumber whose value is the minimum of <code>arg1</code>, + <code>arg2</code>,... . + </p> + <p>The argument to this method can also be an array of values.</p> + <p>The return value is always exact and unrounded.</p> + <pre>x = new BigNumber('3257869345.0378653') +BigNumber.min(4e9, x, '123456789.9') // '123456789.9' + +arr = [2, new BigNumber(-14), '-15.9999', -12] +BigNumber.min(arr) // '-15.9999'</pre> + + + + <h5 id="random"> + random<code class='inset'>.random([dp]) <i>⇒ BigNumber</i></code> + </h5> + <p><code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive</p> + <p> + Returns a new BigNumber with a pseudo-random value equal to or greater than <code>0</code> and + less than <code>1</code>. + </p> + <p> + The return value will have <code>dp</code> decimal places (or less if trailing zeros are + produced).<br /> + If <code>dp</code> is omitted then the number of decimal places will default to the current + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> setting. + </p> + <p> + Depending on the value of this BigNumber constructor's + <a href='#crypto'><code>CRYPTO</code></a> setting and the support for the + <code>crypto</code> object in the host environment, the random digits of the return value are + generated by either <code>Math.random</code> (fastest), <code>crypto.getRandomValues</code> + (Web Cryptography API in recent browsers) or <code>crypto.randomBytes</code> (Node.js). + </p> + <p> + If <a href='#crypto'><code>CRYPTO</code></a> is <code>true</code>, i.e. one of the + <code>crypto</code> methods is to be used, the value of a returned BigNumber should be + cryptographically-secure and statistically indistinguishable from a random value. + </p> + <pre>BigNumber.config({ DECIMAL_PLACES: 10 }) +BigNumber.random() // '0.4117936847' +BigNumber.random(20) // '0.78193327636914089009'</pre> + + + + <h4 id="constructor-properties">Properties</h4> + <p> + The library's enumerated rounding modes are stored as properties of the constructor.<br /> + (They are not referenced internally by the library itself.) + </p> + <p> + Rounding modes <code>0</code> to <code>6</code> (inclusive) are the same as those of Java's + BigDecimal class. + </p> + <table> + <tr> + <th>Property</th> + <th>Value</th> + <th>Description</th> + </tr> + <tr> + <td id="round-up"><b>ROUND_UP</b></td> + <td class='centre'>0</td> + <td>Rounds away from zero</td> + </tr> + <tr> + <td id="round-down"><b>ROUND_DOWN</b></td> + <td class='centre'>1</td> + <td>Rounds towards zero</td> + </tr> + <tr> + <td id="round-ceil"><b>ROUND_CEIL</b></td> + <td class='centre'>2</td> + <td>Rounds towards <code>Infinity</code></td> + </tr> + <tr> + <td id="round-floor"><b>ROUND_FLOOR</b></td> + <td class='centre'>3</td> + <td>Rounds towards <code>-Infinity</code></td> + </tr> + <tr> + <td id="round-half-up"><b>ROUND_HALF_UP</b></td> + <td class='centre'>4</td> + <td> + Rounds towards nearest neighbour.<br /> + If equidistant, rounds away from zero + </td> + </tr> + <tr> + <td id="round-half-down"><b>ROUND_HALF_DOWN</b></td> + <td class='centre'>5</td> + <td> + Rounds towards nearest neighbour.<br /> + If equidistant, rounds towards zero + </td> + </tr> + <tr> + <td id="round-half-even"><b>ROUND_HALF_EVEN</b></td> + <td class='centre'>6</td> + <td> + Rounds towards nearest neighbour.<br /> + If equidistant, rounds towards even neighbour + </td> + </tr> + <tr> + <td id="round-half-ceil"><b>ROUND_HALF_CEIL</b></td> + <td class='centre'>7</td> + <td> + Rounds towards nearest neighbour.<br /> + If equidistant, rounds towards <code>Infinity</code> + </td> + </tr> + <tr> + <td id="round-half-floor"><b>ROUND_HALF_FLOOR</b></td> + <td class='centre'>8</td> + <td> + Rounds towards nearest neighbour.<br /> + If equidistant, rounds towards <code>-Infinity</code> + </td> + </tr> + </table> + <pre> +BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL }) +BigNumber.config({ ROUNDING_MODE: 2 }) // equivalent</pre> + + + <h3>INSTANCE</h3> + + <h4 id="prototype-methods">Methods</h4> + <p>The methods inherited by a BigNumber instance from its constructor's prototype object.</p> + <p>A BigNumber is immutable in the sense that it is not changed by its methods. </p> + <p> + The treatment of ±<code>0</code>, ±<code>Infinity</code> and <code>NaN</code> is + consistent with how JavaScript treats these values. + </p> + <p> + Many method names have a shorter alias.<br /> + (Internally, the library always uses the shorter method names.) + </p> + + + + <h5 id="abs">absoluteValue<code class='inset'>.abs() <i>⇒ BigNumber</i></code></h5> + <p> + Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of + this BigNumber. + </p> + <p>The return value is always exact and unrounded.</p> + <pre> +x = new BigNumber(-0.8) +y = x.absoluteValue() // '0.8' +z = y.abs() // '0.8'</pre> + + + + <h5 id="ceil">ceil<code class='inset'>.ceil() <i>⇒ BigNumber</i></code></h5> + <p> + Returns a BigNumber whose value is the value of this BigNumber rounded to + a whole number in the direction of positive <code>Infinity</code>. + </p> + <pre> +x = new BigNumber(1.3) +x.ceil() // '2' +y = new BigNumber(-1.8) +y.ceil() // '-1'</pre> + + + + <h5 id="cmp">comparedTo<code class='inset'>.cmp(n [, base]) <i>⇒ number</i></code></h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <table> + <tr><th>Returns</th><th> </th></tr> + <tr> + <td class='centre'><code>1</code></td> + <td>If the value of this BigNumber is greater than the value of <code>n</code></td> + </tr> + <tr> + <td class='centre'><code>-1</code></td> + <td>If the value of this BigNumber is less than the value of <code>n</code></td> + </tr> + <tr> + <td class='centre'><code>0</code></td> + <td>If this BigNumber and <code>n</code> have the same value</td> + </tr> + <tr> + <td class='centre'><code>null</code></td> + <td>If the value of either this BigNumber or <code>n</code> is <code>NaN</code></td> + </tr> + </table> + <pre> +x = new BigNumber(Infinity) +y = new BigNumber(5) +x.comparedTo(y) // 1 +x.comparedTo(x.minus(1)) // 0 +y.cmp(NaN) // null +y.cmp('110', 2) // -1</pre> + + + + <h5 id="dp">decimalPlaces<code class='inset'>.dp() <i>⇒ number</i></code></h5> + <p> + Return the number of decimal places of the value of this BigNumber, or <code>null</code> if + the value of this BigNumber is ±<code>Infinity</code> or <code>NaN</code>. + </p> + <pre> +x = new BigNumber(123.45) +x.decimalPlaces() // 2 +y = new BigNumber('9.9e-101') +y.dp() // 102</pre> + + + + <h5 id="div">dividedBy<code class='inset'>.div(n [, base]) <i>⇒ BigNumber</i></code> + </h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p> + Returns a BigNumber whose value is the value of this BigNumber divided by + <code>n</code>, rounded according to the current + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration. + </p> + <pre> +x = new BigNumber(355) +y = new BigNumber(113) +x.dividedBy(y) // '3.14159292035398230088' +x.div(5) // '71' +x.div(47, 16) // '5'</pre> + + + + <h5 id="divInt"> + dividedToIntegerBy<code class='inset'>.divToInt(n [, base]) ⇒ + <i>BigNumber</i></code> + </h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p> + Return a BigNumber whose value is the integer part of dividing the value of this BigNumber by + <code>n</code>. + </p> + <pre> +x = new BigNumber(5) +y = new BigNumber(3) +x.dividedToIntegerBy(y) // '1' +x.divToInt(0.7) // '7' +x.divToInt('0.f', 16) // '5'</pre> + + + + <h5 id="eq">equals<code class='inset'>.eq(n [, base]) <i>⇒ boolean</i></code></h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p> + Returns <code>true</code> if the value of this BigNumber equals the value of <code>n</code>, + otherwise returns <code>false</code>.<br /> + As with JavaScript, <code>NaN</code> does not equal <code>NaN</code>. + </p> + <p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p> + <pre> +0 === 1e-324 // true +x = new BigNumber(0) +x.equals('1e-324') // false +BigNumber(-0).eq(x) // true ( -0 === 0 ) +BigNumber(255).eq('ff', 16) // true + +y = new BigNumber(NaN) +y.equals(NaN) // false</pre> + + + + <h5 id="floor">floor<code class='inset'>.floor() <i>⇒ BigNumber</i></code></h5> + <p> + Returns a BigNumber whose value is the value of this BigNumber rounded to a whole number in + the direction of negative <code>Infinity</code>. + </p> + <pre> +x = new BigNumber(1.8) +x.floor() // '1' +y = new BigNumber(-1.3) +y.floor() // '-2'</pre> + + + + <h5 id="gt">greaterThan<code class='inset'>.gt(n [, base]) <i>⇒ boolean</i></code></h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p> + Returns <code>true</code> if the value of this BigNumber is greater than the value of + <code>n</code>, otherwise returns <code>false</code>. + </p> + <p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p> + <pre> +0.1 > (0.3 - 0.2) // true +x = new BigNumber(0.1) +x.greaterThan(BigNumber(0.3).minus(0.2)) // false +BigNumber(0).gt(x) // false +BigNumber(11, 3).gt(11.1, 2) // true</pre> + + + + <h5 id="gte"> + greaterThanOrEqualTo<code class='inset'>.gte(n [, base]) <i>⇒ boolean</i></code> + </h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p> + Returns <code>true</code> if the value of this BigNumber is greater than or equal to the value + of <code>n</code>, otherwise returns <code>false</code>. + </p> + <p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p> + <pre> +(0.3 - 0.2) >= 0.1 // false +x = new BigNumber(0.3).minus(0.2) +x.greaterThanOrEqualTo(0.1) // true +BigNumber(1).gte(x) // true +BigNumber(10, 18).gte('i', 36) // true</pre> + + + + <h5 id="isF">isFinite<code class='inset'>.isFinite() <i>⇒ boolean</i></code></h5> + <p> + Returns <code>true</code> if the value of this BigNumber is a finite number, otherwise + returns <code>false</code>. + </p> + <p> + The only possible non-finite values of a BigNumber are <code>NaN</code>, <code>Infinity</code> + and <code>-Infinity</code>. + </p> + <pre> +x = new BigNumber(1) +x.isFinite() // true +y = new BigNumber(Infinity) +y.isFinite() // false</pre> + <p> + Note: The native method <code>isFinite()</code> can be used if + <code>n <= Number.MAX_VALUE</code>. + </p> + + + + <h5 id="isInt">isInteger<code class='inset'>.isInt() <i>⇒ boolean</i></code></h5> + <p> + Returns <code>true</code> if the value of this BigNumber is a whole number, otherwise returns + <code>false</code>. + </p> + <pre> +x = new BigNumber(1) +x.isInteger() // true +y = new BigNumber(123.456) +y.isInt() // false</pre> + + + + <h5 id="isNaN">isNaN<code class='inset'>.isNaN() <i>⇒ boolean</i></code></h5> + <p> + Returns <code>true</code> if the value of this BigNumber is <code>NaN</code>, otherwise + returns <code>false</code>. + </p> + <pre> +x = new BigNumber(NaN) +x.isNaN() // true +y = new BigNumber('Infinity') +y.isNaN() // false</pre> + <p>Note: The native method <code>isNaN()</code> can also be used.</p> + + + + <h5 id="isNeg">isNegative<code class='inset'>.isNeg() <i>⇒ boolean</i></code></h5> + <p> + Returns <code>true</code> if the value of this BigNumber is negative, otherwise returns + <code>false</code>. + </p> + <pre> +x = new BigNumber(-0) +x.isNegative() // true +y = new BigNumber(2) +y.isNeg() // false</pre> + <p>Note: <code>n < 0</code> can be used if <code>n <= -Number.MIN_VALUE</code>.</p> + + + + <h5 id="isZ">isZero<code class='inset'>.isZero() <i>⇒ boolean</i></code></h5> + <p> + Returns <code>true</code> if the value of this BigNumber is zero or minus zero, otherwise + returns <code>false</code>. + </p> + <pre> +x = new BigNumber(-0) +x.isZero() && x.isNeg() // true +y = new BigNumber(Infinity) +y.isZero() // false</pre> + <p>Note: <code>n == 0</code> can be used if <code>n >= Number.MIN_VALUE</code>.</p> + + + + <h5 id="lt">lessThan<code class='inset'>.lt(n [, base]) <i>⇒ boolean</i></code></h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p> + Returns <code>true</code> if the value of this BigNumber is less than the value of + <code>n</code>, otherwise returns <code>false</code>. + </p> + <p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p> + <pre> +(0.3 - 0.2) < 0.1 // true +x = new BigNumber(0.3).minus(0.2) +x.lessThan(0.1) // false +BigNumber(0).lt(x) // true +BigNumber(11.1, 2).lt(11, 3) // true</pre> + + + + <h5 id="lte"> + lessThanOrEqualTo<code class='inset'>.lte(n [, base]) <i>⇒ boolean</i></code> + </h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p> + Returns <code>true</code> if the value of this BigNumber is less than or equal to the value of + <code>n</code>, otherwise returns <code>false</code>. + </p> + <p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p> + <pre> +0.1 <= (0.3 - 0.2) // false +x = new BigNumber(0.1) +x.lessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true +BigNumber(-1).lte(x) // true +BigNumber(10, 18).lte('i', 36) // true</pre> + + + + <h5 id="minus"> + minus<code class='inset'>.minus(n [, base]) <i>⇒ BigNumber</i></code> + </h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p>Returns a BigNumber whose value is the value of this BigNumber minus <code>n</code>.</p> + <p>The return value is always exact and unrounded.</p> + <pre> +0.3 - 0.1 // 0.19999999999999998 +x = new BigNumber(0.3) +x.minus(0.1) // '0.2' +x.minus(0.6, 20) // '0'</pre> + + + + <h5 id="mod">modulo<code class='inset'>.mod(n [, base]) <i>⇒ BigNumber</i></code></h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p> + Returns a BigNumber whose value is the value of this BigNumber modulo <code>n</code>, i.e. + the integer remainder of dividing this BigNumber by <code>n</code>. + </p> + <p> + The value returned, and in particular its sign, is dependent on the value of the + <a href='#modulo-mode'><code>MODULO_MODE</code></a> setting of this BigNumber constructor. + If it is <code>1</code> (default value), the result will have the same sign as this BigNumber, + and it will match that of Javascript's <code>%</code> operator (within the limits of double + precision) and BigDecimal's <code>remainder</code> method. + </p> + <p>The return value is always exact and unrounded.</p> + <p> + See <a href='#modulo-mode'><code>MODULO_MODE</code></a> for a description of the other + modulo modes. + </p> + <pre> +1 % 0.9 // 0.09999999999999998 +x = new BigNumber(1) +x.modulo(0.9) // '0.1' +y = new BigNumber(33) +y.mod('a', 33) // '3'</pre> + + + + <h5 id="neg">negated<code class='inset'>.neg() <i>⇒ BigNumber</i></code></h5> + <p> + Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by + <code>-1</code>. + </p> + <pre> +x = new BigNumber(1.8) +x.negated() // '-1.8' +y = new BigNumber(-1.3) +y.neg() // '1.3'</pre> + + + + <h5 id="plus">plus<code class='inset'>.plus(n [, base]) <i>⇒ BigNumber</i></code></h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p>Returns a BigNumber whose value is the value of this BigNumber plus <code>n</code>.</p> + <p>The return value is always exact and unrounded.</p> + <pre> +0.1 + 0.2 // 0.30000000000000004 +x = new BigNumber(0.1) +y = x.plus(0.2) // '0.3' +BigNumber(0.7).plus(x).plus(y) // '1' +x.plus('0.1', 8) // '0.225'</pre> + + + + <h5 id="sd">precision<code class='inset'>.sd([z]) <i>⇒ number</i></code></h5> + <p> + <code>z</code>: <i>boolean|number</i>: <code>true</code>, <code>false</code>, <code>0</code> + or <code>1</code> + </p> + <p>Returns the number of significant digits of the value of this BigNumber.</p> + <p> + If <code>z</code> is <code>true</code> or <code>1</code> then any trailing zeros of the + integer part of a number are counted as significant digits, otherwise they are not. + </p> + <pre> +x = new BigNumber(1.234) +x.precision() // 4 +y = new BigNumber(987000) +y.sd() // 3 +y.sd(true) // 6</pre> + + + + <h5 id="round">round<code class='inset'>.round([dp [, rm]]) <i>⇒ BigNumber</i></code></h5> + <p> + <code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br /> + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive + </p> + <p> + Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + <code>rm</code> to a maximum of <code>dp</code> decimal places. + </p> + <p> + if <code>dp</code> is omitted, or is <code>null</code> or <code>undefined</code>, the + return value is <code>n</code> rounded to a whole number.<br /> + if <code>rm</code> is omitted, or is <code>null</code> or <code>undefined</code>, + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used. + </p> + <p> + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range + <code>dp</code> or <code>rm</code> values. + </p> + <pre> +x = 1234.56 +Math.round(x) // 1235 + +y = new BigNumber(x) +y.round() // '1235' +y.round(1) // '1234.6' +y.round(2) // '1234.56' +y.round(10) // '1234.56' +y.round(0, 1) // '1234' +y.round(0, 6) // '1235' +y.round(1, 1) // '1234.5' +y.round(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' +y // '1234.56'</pre> + + + + <h5 id="shift">shift<code class='inset'>.shift(n) <i>⇒ BigNumber</i></code></h5> + <p> + <code>n</code>: <i>number</i>: integer, + <code>-9007199254740991</code> to <code>9007199254740991</code> inclusive + </p> + <p> + Returns a BigNumber whose value is the value of this BigNumber shifted <code>n</code> places. + <p> + The shift is of the decimal point, i.e. of powers of ten, and is to the left if <code>n</code> + is negative or to the right if <code>n</code> is positive. + </p> + <p>The return value is always exact and unrounded.</p> + <pre> +x = new BigNumber(1.23) +x.shift(3) // '1230' +x.shift(-3) // '0.00123'</pre> + + + + <h5 id="sqrt">squareRoot<code class='inset'>.sqrt() <i>⇒ BigNumber</i></code></h5> + <p> + Returns a BigNumber whose value is the square root of the value of this BigNumber, + rounded according to the current + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration. + </p> + <p> + The return value will be correctly rounded, i.e. rounded as if the result was first calculated + to an infinite number of correct digits before rounding. + </p> + <pre> +x = new BigNumber(16) +x.squareRoot() // '4' +y = new BigNumber(3) +y.sqrt() // '1.73205080756887729353'</pre> + + + + <h5 id="times">times<code class='inset'>.times(n [, base]) <i>⇒ BigNumber</i></code></h5> + <p> + <code>n</code>: <i>number|string|BigNumber</i><br /> + <code>base</code>: <i>number</i><br /> + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i> + </p> + <p>Returns a BigNumber whose value is the value of this BigNumber times <code>n</code>.</p> + <p>The return value is always exact and unrounded.</p> + <pre> +0.6 * 3 // 1.7999999999999998 +x = new BigNumber(0.6) +y = x.times(3) // '1.8' +BigNumber('7e+500').times(y) // '1.26e+501' +x.times('-a', 16) // '-6'</pre> + + + + <h5 id="toD"> + toDigits<code class='inset'>.toDigits([sd [, rm]]) <i>⇒ BigNumber</i></code> + </h5> + <p> + <code>sd</code>: <i>number</i>: integer, <code>1</code> to <code>1e+9</code> inclusive.<br /> + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive. + </p> + <p> + Returns a BigNumber whose value is the value of this BigNumber rounded to <code>sd</code> + significant digits using rounding mode <code>rm</code>. + </p> + <p> + If <code>sd</code> is omitted or is <code>null</code> or <code>undefined</code>, the return + value will not be rounded.<br /> + If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>, + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> will be used. + </p> + <p> + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range + <code>sd</code> or <code>rm</code> values. + </p> + <pre> +BigNumber.config({ precision: 5, rounding: 4 }) +x = new BigNumber(9876.54321) + +x.toDigits() // '9876.5' +x.toDigits(6) // '9876.54' +x.toDigits(6, BigNumber.ROUND_UP) // '9876.55' +x.toDigits(2) // '9900' +x.toDigits(2, 1) // '9800' +x // '9876.54321'</pre> + + + + <h5 id="toE"> + toExponential<code class='inset'>.toExponential([dp [, rm]]) <i>⇒ string</i></code> + </h5> + <p> + <code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br /> + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive + </p> + <p> + Returns a string representing the value of this BigNumber in exponential notation rounded + using rounding mode <code>rm</code> to <code>dp</code> decimal places, i.e with one digit + before the decimal point and <code>dp</code> digits after it. + </p> + <p> + If the value of this BigNumber in exponential notation has fewer than <code>dp</code> fraction + digits, the return value will be appended with zeros accordingly. + </p> + <p> + If <code>dp</code> is omitted, or is <code>null</code> or <code>undefined</code>, the number + of digits after the decimal point defaults to the minimum number of digits necessary to + represent the value exactly.<br /> + If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>, + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used. + </p> + <p> + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range + <code>dp</code> or <code>rm</code> values. + </p> + <pre> +x = 45.6 +y = new BigNumber(x) +x.toExponential() // '4.56e+1' +y.toExponential() // '4.56e+1' +x.toExponential(0) // '5e+1' +y.toExponential(0) // '5e+1' +x.toExponential(1) // '4.6e+1' +y.toExponential(1) // '4.6e+1' +y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN) +x.toExponential(3) // '4.560e+1' +y.toExponential(3) // '4.560e+1'</pre> + + + + <h5 id="toFix"> + toFixed<code class='inset'>.toFixed([dp [, rm]]) <i>⇒ string</i></code> + </h5> + <p> + <code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br /> + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive + </p> + <p> + Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to <code>dp</code> decimal places using rounding mode <code>rm</code>. + </p> + <p> + If the value of this BigNumber in normal notation has fewer than <code>dp</code> fraction + digits, the return value will be appended with zeros accordingly. + </p> + <p> + Unlike <code>Number.prototype.toFixed</code>, which returns exponential notation if a number + is greater or equal to <code>10<sup>21</sup></code>, this method will always return normal + notation. + </p> + <p> + If <code>dp</code> is omitted or is <code>null</code> or <code>undefined</code>, the return + value will be unrounded and in normal notation. This is also unlike + <code>Number.prototype.toFixed</code>, which returns the value to zero decimal places.<br /> + It is useful when fixed-point notation is required and the current + <a href="#exponential-at"><code>EXPONENTIAL_AT</code></a> setting causes + <code><a href='#toS'>toString</a></code> to return exponential notation.<br /> + If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>, + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used. + </p> + <p> + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range + <code>dp</code> or <code>rm</code> values. + </p> + <pre> +x = 3.456 +y = new BigNumber(x) +x.toFixed() // '3' +y.toFixed() // '3.456' +y.toFixed(0) // '3' +x.toFixed(2) // '3.46' +y.toFixed(2) // '3.46' +y.toFixed(2, 1) // '3.45' (ROUND_DOWN) +x.toFixed(5) // '3.45600' +y.toFixed(5) // '3.45600'</pre> + + + + <h5 id="toFor"> + toFormat<code class='inset'>.toFormat([dp [, rm]]) <i>⇒ string</i></code> + </h5> + <p> + <code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br /> + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive + </p> + <p> + <p> + Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to <code>dp</code> decimal places using rounding mode <code>rm</code>, and formatted + according to the properties of the <a href='#format'><code>FORMAT</code></a> object. + </p> + <p> + See the examples below for the properties of the + <a href='#format'><code>FORMAT</code></a> object, their types and their usage. + </p> + <p> + If <code>dp</code> is omitted or is <code>null</code> or <code>undefined</code>, then the + return value is not rounded to a fixed number of decimal places.<br /> + If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>, + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used. + </p> + <p> + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range + <code>dp</code> or <code>rm</code> values. + </p> + <pre> +format = { + decimalSeparator: '.', + groupSeparator: ',', + groupSize: 3, + secondaryGroupSize: 0, + fractionGroupSeparator: ' ', + fractionGroupSize: 0 +} +BigNumber.config({ FORMAT: format }) + +x = new BigNumber('123456789.123456789') +x.toFormat() // '123,456,789.123456789' +x.toFormat(1) // '123,456,789.1' + +// If a reference to the object assigned to FORMAT has been retained, +// the format properties can be changed directly +format.groupSeparator = ' ' +format.fractionGroupSize = 5 +x.toFormat() // '123 456 789.12345 6789' + +BigNumber.config({ + FORMAT: { + decimalSeparator: ',', + groupSeparator: '.', + groupSize: 3, + secondaryGroupSize: 2 + } +}) + +x.toFormat(6) // '12.34.56.789,123'</pre> + + + + <h5 id="toFr"> + toFraction<code class='inset'>.toFraction([max]) <i>⇒ [string, string]</i></code> + </h5> + <p> + <code>max</code>: <i>number|string|BigNumber</i>: integer >= <code>1</code> and < + <code>Infinity</code> + </p> + <p> + Returns a string array representing the value of this BigNumber as a simple fraction with an + integer numerator and an integer denominator. The denominator will be a positive non-zero + value less than or equal to <code>max</code>. + </p> + <p> + If a maximum denominator, <code>max</code>, is not specified, or is <code>null</code> or + <code>undefined</code>, the denominator will be the lowest value necessary to represent the + number exactly. + </p> + <p> + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range + <code>max</code> values. + </p> + <pre> +x = new BigNumber(1.75) +x.toFraction() // '7, 4' + +pi = new BigNumber('3.14159265358') +pi.toFraction() // '157079632679,50000000000' +pi.toFraction(100000) // '312689, 99532' +pi.toFraction(10000) // '355, 113' +pi.toFraction(100) // '311, 99' +pi.toFraction(10) // '22, 7' +pi.toFraction(1) // '3, 1'</pre> + + + + <h5 id="toJSON">toJSON<code class='inset'>.toJSON() <i>⇒ string</i></code></h5> + <p>As <code>valueOf</code>.</p> + <pre> +x = new BigNumber('177.7e+457') +y = new BigNumber(235.4325) +z = new BigNumber('0.0098074') + +// Serialize an array of three BigNumbers +str = JSON.stringify( [x, y, z] ) +// "["1.777e+459","235.4325","0.0098074"]" + +// Return an array of three BigNumbers +JSON.parse(str, function (key, val) { + return key === '' ? val : new BigNumber(val) +})</pre> + + + + <h5 id="toN">toNumber<code class='inset'>.toNumber() <i>⇒ number</i></code></h5> + <p>Returns the value of this BigNumber as a JavaScript number primitive.</p> + <p> + Type coercion with, for example, the unary plus operator will also work, except that a + BigNumber with the value minus zero will be converted to positive zero. + </p> + <pre> +x = new BigNumber(456.789) +x.toNumber() // 456.789 ++x // 456.789 + +y = new BigNumber('45987349857634085409857349856430985') +y.toNumber() // 4.598734985763409e+34 + +z = new BigNumber(-0) +1 / +z // Infinity +1 / z.toNumber() // -Infinity</pre> + + + + <h5 id="pow">toPower<code class='inset'>.pow(n [, m]) <i>⇒ BigNumber</i></code></h5> + <p> + <code>n</code>: <i>number</i>: integer, + <code>-9007199254740991</code> to <code>9007199254740991</code> inclusive<br /> + <code>m</code>: <i>number|string|BigNumber</i> + </p> + <p> + Returns a BigNumber whose value is the value of this BigNumber raised to the power + <code>n</code>, and optionally modulo a modulus <code>m</code>. + </p> + <p> + If <code>n</code> is negative the result is rounded according to the current + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration. + </p> + <p> + If <code>n</code> is not an integer or is out of range: + </p> + <p class='inset'> + If <code>ERRORS</code> is <code>true</code> a BigNumber Error is thrown,<br /> + else if <code>n</code> is greater than <code>9007199254740991</code>, it is interpreted as + <code>Infinity</code>;<br /> + else if <code>n</code> is less than <code>-9007199254740991</code>, it is interpreted as + <code>-Infinity</code>;<br /> + else if <code>n</code> is otherwise a number, it is truncated to an integer;<br /> + else it is interpreted as <code>NaN</code>. + </p> + <p> + As the number of digits of the result of the power operation can grow so large so quickly, + e.g. 123.456<sup>10000</sup> has over <code>50000</code> digits, the number of significant + digits calculated is limited to the value of the + <a href='#pow-precision'><code>POW_PRECISION</code></a> setting (unless a modulus + <code>m</code> is specified). + </p> + <p> + By default <a href='#pow-precision'><code>POW_PRECISION</code></a> is set to <code>0</code>. + This means that an unlimited number of significant digits will be calculated, and that the + method's performance will decrease dramatically for larger exponents. + </p> + <p> + Negative exponents will be calculated to the number of decimal places specified by + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> (but not to more than + <a href='#pow-precision'><code>POW_PRECISION</code></a> significant digits). + </p> + <p> + If <code>m</code> is specified and the value of <code>m</code>, <code>n</code> and this + BigNumber are positive integers, then a fast modular exponentiation algorithm is used, + otherwise if any of the values is not a positive integer the operation will simply be + performed as <code>x.toPower(n).modulo(m)</code> with a + <a href='#pow-precision'><code>POW_PRECISION</code></a> of <code>0</code>. + </p> + <pre> +Math.pow(0.7, 2) // 0.48999999999999994 +x = new BigNumber(0.7) +x.toPower(2) // '0.49' +BigNumber(3).pow(-2) // '0.11111111111111111111'</pre> + + + + <h5 id="toP"> + toPrecision<code class='inset'>.toPrecision([sd [, rm]]) <i>⇒ string</i></code> + </h5> + <p> + <code>sd</code>: <i>number</i>: integer, <code>1</code> to <code>1e+9</code> inclusive<br /> + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive + </p> + <p> + Returns a string representing the value of this BigNumber rounded to <code>sd</code> + significant digits using rounding mode <code>rm</code>. + </p> + <p> + If <code>sd</code> is less than the number of digits necessary to represent the integer part + of the value in normal (fixed-point) notation, then exponential notation is used. + </p> + <p> + If <code>sd</code> is omitted, or is <code>null</code> or <code>undefined</code>, then the + return value is the same as <code>n.toString()</code>.<br /> + If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>, + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used. + </p> + <p> + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range + <code>sd</code> or <code>rm</code> values. + </p> + <pre> +x = 45.6 +y = new BigNumber(x) +x.toPrecision() // '45.6' +y.toPrecision() // '45.6' +x.toPrecision(1) // '5e+1' +y.toPrecision(1) // '5e+1' +y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP) +y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN) +x.toPrecision(5) // '45.600' +y.toPrecision(5) // '45.600'</pre> + + + + <h5 id="toS">toString<code class='inset'>.toString([base]) <i>⇒ string</i></code></h5> + <p><code>base</code>: <i>number</i>: integer, <code>2</code> to <code>64</code> inclusive</p> + <p> + Returns a string representing the value of this BigNumber in the specified base, or base + <code>10</code> if <code>base</code> is omitted or is <code>null</code> or + <code>undefined</code>. + </p> + <p> + For bases above <code>10</code>, values from <code>10</code> to <code>35</code> are + represented by <code>a-z</code> (as with <code>Number.prototype.toString</code>), + <code>36</code> to <code>61</code> by <code>A-Z</code>, and <code>62</code> and + <code>63</code> by <code>$</code> and <code>_</code> respectively. + </p> + <p> + If a base is specified the value is rounded according to the current + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> + and <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration. + </p> + <p> + If a base is not specified, and this BigNumber has a positive + exponent that is equal to or greater than the positive component of the + current <a href="#exponential-at"><code>EXPONENTIAL_AT</code></a> setting, + or a negative exponent equal to or less than the negative component of the + setting, then exponential notation is returned. + </p> + <p>If <code>base</code> is <code>null</code> or <code>undefined</code> it is ignored.</p> + <p> + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range + <code>base</code> values. + </p> + <pre> +x = new BigNumber(750000) +x.toString() // '750000' +BigNumber.config({ EXPONENTIAL_AT: 5 }) +x.toString() // '7.5e+5' + +y = new BigNumber(362.875) +y.toString(2) // '101101010.111' +y.toString(9) // '442.77777777777777777778' +y.toString(32) // 'ba.s' + +BigNumber.config({ DECIMAL_PLACES: 4 }); +z = new BigNumber('1.23456789') +z.toString() // '1.23456789' +z.toString(10) // '1.2346'</pre> + + + + <h5 id="trunc">truncated<code class='inset'>.trunc() <i>⇒ BigNumber</i></code></h5> + <p> + Returns a BigNumber whose value is the value of this BigNumber truncated to a whole number. + </p> + <pre> +x = new BigNumber(123.456) +x.truncated() // '123' +y = new BigNumber(-12.3) +y.trunc() // '-12'</pre> + + + + <h5 id="valueOf">valueOf<code class='inset'>.valueOf() <i>⇒ string</i></code></h5> + <p> + As <code>toString</code>, but does not accept a base argument and includes the minus sign + for negative zero. + </p> + <pre> +x = new BigNumber('-0') +x.toString() // '0' +x.valueOf() // '-0' +y = new BigNumber('1.777e+457') +y.valueOf() // '1.777e+457'</pre> + + + + <h4 id="instance-properties">Properties</h4> + <p>The properties of a BigNumber instance:</p> + <table> + <tr> + <th>Property</th> + <th>Description</th> + <th>Type</th> + <th>Value</th> + </tr> + <tr> + <td class='centre' id='coefficient'><b>c</b></td> + <td>coefficient<sup>*</sup></td> + <td><i>number</i><code>[]</code></td> + <td> Array of base <code>1e14</code> numbers</td> + </tr> + <tr> + <td class='centre' id='exponent'><b>e</b></td> + <td>exponent</td> + <td><i>number</i></td> + <td>Integer, <code>-1000000000</code> to <code>1000000000</code> inclusive</td> + </tr> + <tr> + <td class='centre' id='sign'><b>s</b></td> + <td>sign</td> + <td><i>number</i></td> + <td><code>-1</code> or <code>1</code></td> + </tr> + <tr> + <td class='centre' id='isbig'><b>isBigNumber</b></td> + <td>type identifier</td> + <td><i>boolean</i></td> + <td><code>true</code></td> + </tr> + </table> + <p><sup>*</sup>significand</p> + <p> + The value of any of the <code>c</code>, <code>e</code> and <code>s</code> properties may also + be <code>null</code>. + </p> + <p> + From v2.0.0 of this library, the value of the coefficient of a BigNumber is stored in a + normalised base <code>100000000000000</code> floating point format, as opposed to the base + <code>10</code> format used in v1.x.x + </p> + <p> + This change means the properties of a BigNumber are now best considered to be read-only. + Previously it was acceptable to change the exponent of a BigNumber by writing to its exponent + property directly, but this is no longer recommended as the number of digits in the first + element of the coefficient array is dependent on the exponent, so the coefficient would also + need to be altered. + </p> + <p> + Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are + not necessarily preserved. + </p> + <pre>x = new BigNumber(0.123) // '0.123' +x.toExponential() // '1.23e-1' +x.c // '1,2,3' +x.e // -1 +x.s // 1 + +y = new Number(-123.4567000e+2) // '-12345.67' +y.toExponential() // '-1.234567e+4' +z = new BigNumber('-123.4567000e+2') // '-12345.67' +z.toExponential() // '-1.234567e+4' +z.c // '1,2,3,4,5,6,7' +z.e // 4 +z.s // -1</pre> + <p>Checking if a value is a BigNumber instance:</p> + <pre> +x = new BigNumber(3) +x instanceof BigNumber // true +x.isBigNumber // true + +BN = BigNumber.another(); + +y = new BN(3) +y instanceof BigNumber // false +y.isBigNumber // true</pre> + + + + + <h4 id="zero-nan-infinity">Zero, NaN and Infinity</h4> + <p> + The table below shows how ±<code>0</code>, <code>NaN</code> and + ±<code>Infinity</code> are stored. + </p> + <table> + <tr> + <th> </th> + <th class='centre'>c</th> + <th class='centre'>e</th> + <th class='centre'>s</th> + </tr> + <tr> + <td>±0</td> + <td><code>[0]</code></td> + <td><code>0</code></td> + <td><code>±1</code></td> + </tr> + <tr> + <td>NaN</td> + <td><code>null</code></td> + <td><code>null</code></td> + <td><code>null</code></td> + </tr> + <tr> + <td>±Infinity</td> + <td><code>null</code></td> + <td><code>null</code></td> + <td><code>±1</code></td> + </tr> + </table> + <pre> +x = new Number(-0) // 0 +1 / x == -Infinity // true + +y = new BigNumber(-0) // '0' +y.c // '0' ( [0].toString() ) +y.e // 0 +y.s // -1</pre> + + + + <h4 id='Errors'>Errors</h4> + <p> + The errors that are thrown are generic <code>Error</code> objects with <code>name</code> + <i>BigNumber Error</i>. + </p> + <p> + The table below shows the errors that may be thrown if <code>ERRORS</code> is + <code>true</code>, and the action taken if <code>ERRORS</code> is <code>false</code>. + </p> + <table class='error-table'> + <tr> + <th>Method(s)</th> + <th>ERRORS: true<br />Throw BigNumber Error</th> + <th>ERRORS: false<br />Action on invalid argument</th> + </tr> + <tr> + <td rowspan=5> + <code> + BigNumber<br /> + comparedTo<br /> + dividedBy<br /> + dividedToIntegerBy<br /> + equals<br /> + greaterThan<br /> + greaterThanOrEqualTo<br /> + lessThan<br /> + lessThanOrEqualTo<br /> + minus<br /> + modulo<br /> + plus<br /> + times + </code></td> + <td>number type has more than<br />15 significant digits</td> + <td>Accept.</td> + </tr> + <tr> + <td>not a base... number</td> + <td>Substitute <code>NaN</code>.</td> + </tr> + <tr> + <td>base not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td>base out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td>not a number<sup>*</sup></td> + <td>Substitute <code>NaN</code>.</td> + </tr> + <tr> + <td><code>another</code></td> + <td>not an object</td> + <td>Ignore.</td> + </tr> + <tr> + <td rowspan=17><code>config</code></td> + <td><code>DECIMAL_PLACES</code> not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td><code>DECIMAL_PLACES</code> out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>ROUNDING_MODE</code> not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td><code>ROUNDING_MODE</code> out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>EXPONENTIAL_AT</code> not an integer<br />or not [integer, integer]</td> + <td>Truncate to integer(s).<br />Ignore if not number(s).</td> + </tr> + <tr> + <td><code>EXPONENTIAL_AT</code> out of range<br />or not [negative, positive]</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>RANGE</code> not an integer<br />or not [integer, integer]</td> + <td> Truncate to integer(s).<br />Ignore if not number(s).</td> + </tr> + <tr> + <td><code>RANGE</code> cannot be zero</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>RANGE</code> out of range<br />or not [negative, positive]</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>ERRORS</code> not a boolean<br />or binary digit</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>CRYPTO</code> not a boolean<br />or binary digit</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>CRYPTO</code> crypto unavailable</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>MODULO_MODE</code> not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td><code>MODULO_MODE</code> out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>POW_PRECISION</code> not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td><code>POW_PRECISION</code> out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>FORMAT</code> not an object</td> + <td>Ignore.</td> + </tr> + <tr> + <td><code>precision</code></td> + <td>argument not a boolean<br />or binary digit</td> + <td>Ignore.</td> + </tr> + <tr> + <td rowspan=4><code>round</code></td> + <td>decimal places not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td>decimal places out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td>rounding mode not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td>rounding mode out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td rowspan=2><code>shift</code></td> + <td>argument not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td>argument out of range</td> + <td>Substitute ±<code>Infinity</code>. + </tr> + <tr> + <td rowspan=4> + <code>toExponential</code><br /> + <code>toFixed</code><br /> + <code>toFormat</code> + </td> + <td>decimal places not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td>decimal places out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td>rounding mode not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td>rounding mode out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td rowspan=2><code>toFraction</code></td> + <td>max denominator not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td>max denominator out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td rowspan=4> + <code>toDigits</code><br /> + <code>toPrecision</code> + </td> + <td>precision not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td>precision out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td>rounding mode not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td>rounding mode out of range</td> + <td>Ignore.</td> + </tr> + <tr> + <td rowspan=2><code>toPower</code></td> + <td>exponent not an integer</td> + <td>Truncate to integer.<br />Substitute <code>NaN</code> if not a number.</td> + </tr> + <tr> + <td>exponent out of range</td> + <td>Substitute ±<code>Infinity</code>. + </td> + </tr> + <tr> + <td rowspan=2><code>toString</code></td> + <td>base not an integer</td> + <td>Truncate to integer.<br />Ignore if not a number.</td> + </tr> + <tr> + <td>base out of range</td> + <td>Ignore.</td> + </tr> + </table> + <p><sup>*</sup>No error is thrown if the value is <code>NaN</code> or 'NaN'.</p> + <p> + The message of a <i>BigNumber Error</i> will also contain the name of the method from which + the error originated. + </p> + <p>To determine if an exception is a <i>BigNumber Error</i>:</p> + <pre> +try { + // ... +} catch (e) { + if ( e instanceof Error && e.name == 'BigNumber Error' ) { + // ... + } +}</pre> + + + + <h4 id='faq'>FAQ</h4> + + <h6>Why are trailing fractional zeros removed from BigNumbers?</h6> + <p> + Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the + precision of a value. This can be useful but the results of arithmetic operations can be + misleading. + </p> + <pre> +x = new BigDecimal("1.0") +y = new BigDecimal("1.1000") +z = x.add(y) // 2.1000 + +x = new BigDecimal("1.20") +y = new BigDecimal("3.45000") +z = x.multiply(y) // 4.1400000</pre> + <p> + To specify the precision of a value is to specify that the value lies + within a certain range. + </p> + <p> + In the first example, <code>x</code> has a value of <code>1.0</code>. The trailing zero shows + the precision of the value, implying that it is in the range <code>0.95</code> to + <code>1.05</code>. Similarly, the precision indicated by the trailing zeros of <code>y</code> + indicates that the value is in the range <code>1.09995</code> to <code>1.10005</code>. + </p> + <p> + If we add the two lowest values in the ranges we have, <code>0.95 + 1.09995 = 2.04995</code>, + and if we add the two highest values we have, <code>1.05 + 1.10005 = 2.15005</code>, so the + range of the result of the addition implied by the precision of its operands is + <code>2.04995</code> to <code>2.15005</code>. + </p> + <p> + The result given by BigDecimal of <code>2.1000</code> however, indicates that the value is in + the range <code>2.09995</code> to <code>2.10005</code> and therefore the precision implied by + its trailing zeros may be misleading. + </p> + <p> + In the second example, the true range is <code>4.122744</code> to <code>4.157256</code> yet + the BigDecimal answer of <code>4.1400000</code> indicates a range of <code>4.13999995</code> + to <code>4.14000005</code>. Again, the precision implied by the trailing zeros may be + misleading. + </p> + <p> + This library, like binary floating point and most calculators, does not retain trailing + fractional zeros. Instead, the <code>toExponential</code>, <code>toFixed</code> and + <code>toPrecision</code> methods enable trailing zeros to be added if and when required.<br /> + </p> + </div> + +</body> +</html> diff --git a/node_modules/bignumber.js/package.json b/node_modules/bignumber.js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dabdc31095468ee4c5f015dbc0b86ad6d00735e1 --- /dev/null +++ b/node_modules/bignumber.js/package.json @@ -0,0 +1,66 @@ +{ + "_from": "bignumber.js@4.1.0", + "_id": "bignumber.js@4.1.0", + "_inBundle": false, + "_integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA==", + "_location": "/bignumber.js", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "bignumber.js@4.1.0", + "name": "bignumber.js", + "escapedName": "bignumber.js", + "rawSpec": "4.1.0", + "saveSpec": null, + "fetchSpec": "4.1.0" + }, + "_requiredBy": [ + "/mysql" + ], + "_resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz", + "_shasum": "db6f14067c140bd46624815a7916c92d9b6c24b1", + "_spec": "bignumber.js@4.1.0", + "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mysql", + "author": { + "name": "Michael Mclaughlin", + "email": "M8ch88l@gmail.com" + }, + "bugs": { + "url": "https://github.com/MikeMcl/bignumber.js/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic", + "engines": { + "node": "*" + }, + "homepage": "https://github.com/MikeMcl/bignumber.js#readme", + "keywords": [ + "arbitrary", + "precision", + "arithmetic", + "big", + "number", + "decimal", + "float", + "biginteger", + "bigdecimal", + "bignumber", + "bigint", + "bignum" + ], + "license": "MIT", + "main": "bignumber.js", + "name": "bignumber.js", + "repository": { + "type": "git", + "url": "git+https://github.com/MikeMcl/bignumber.js.git" + }, + "scripts": { + "build": "uglifyjs bignumber.js --source-map bignumber.js.map -c -m -o bignumber.min.js --preamble \"/* bignumber.js v4.1.0 https://github.com/MikeMcl/bignumber.js/LICENCE */\"", + "test": "node ./test/every-test.js" + }, + "types": "bignumber.d.ts", + "version": "4.1.0" +} diff --git a/node_modules/bson/HISTORY.md b/node_modules/bson/HISTORY.md deleted file mode 100644 index 63953a2adcc65a154b580551a8d5940b7edfe1a9..0000000000000000000000000000000000000000 --- a/node_modules/bson/HISTORY.md +++ /dev/null @@ -1,253 +0,0 @@ -<a name="1.1.0"></a> -# [1.1.0](https://github.com/mongodb/js-bson/compare/v1.0.9...v1.1.0) (2018-08-13) - - -### Bug Fixes - -* **serializer:** do not use checkKeys for $clusterTime ([573e141](https://github.com/mongodb/js-bson/commit/573e141)) - - - -<a name="1.0.9"></a> -## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07) - - -### Bug Fixes - -* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f)) - - - -<a name="1.0.7"></a> -## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06) - - -### Bug Fixes - -* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5)) -* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b)) -* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c)) -* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10)) - - - -<a name="1.0.6"></a> -## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12) - - -### Features - -* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc)) - - - -<a name="1.0.5"></a> -## 1.0.5 (2018-02-26) - - -### Bug Fixes - -* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45)) -* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) - - - -1.0.4 2016-01-11 ----------------- -- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. - -1.0.3 2016-01-03 ----------------- -- Fixed toString for ObjectId so it will work with inspect. - -1.0.2 2016-01-02 ----------------- -- Minor optimizations for ObjectID to use Buffer.from where available. - -1.0.1 2016-12-06 ----------------- -- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. - -1.0.0 2016-12-06 ----------------- -- Introduced new BSON API and documentation. - -0.5.7 2016-11-18 ------------------ -- NODE-848 BSON Regex flags must be alphabetically ordered. - -0.5.6 2016-10-19 ------------------ -- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. -- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). - -0.5.5 2016-09-15 ------------------ -- Added DBPointer up conversion to DBRef - -0.5.4 2016-08-23 ------------------ -- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. - -0.5.3 2016-07-11 ------------------ -- Throw error if ObjectId is not a string or a buffer. - -0.5.2 2016-07-11 ------------------ -- All values encoded big-endian style for ObjectId. - -0.5.1 2016-07-11 ------------------ -- Fixed encoding/decoding issue in ObjectId timestamp generation. -- Removed BinaryParser dependency from the serializer/deserializer. - -0.5.0 2016-07-05 ------------------ -- Added Decimal128 type and extended test suite to include entire bson corpus. - -0.4.23 2016-04-08 ------------------ -- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. -- Remove one package from dependency due to having been pulled from NPM. - -0.4.22 2016-03-04 ------------------ -- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). -- Fixed issue with undefined type on deserializing. - -0.4.21 2016-01-12 ------------------ -- Minor optimizations to avoid non needed object creation. - -0.4.20 2015-10-15 ------------------ -- Added bower file to repository. -- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) - -0.4.19 2015-10-15 ------------------ -- Remove all support for bson-ext. - -0.4.18 2015-10-15 ------------------ -- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 -- add option for deserializing binary into Buffer object #116 - -0.4.17 2015-10-15 ------------------ -- Validate regexp string for null bytes and throw if there is one. - -0.4.16 2015-10-07 ------------------ -- Fixed issue with return statement in Map.js. - -0.4.15 2015-10-06 ------------------ -- Exposed Map correctly via index.js file. - -0.4.14 2015-10-06 ------------------ -- Exposed Map correctly via bson.js file. - -0.4.13 2015-10-06 ------------------ -- Added ES6 Map type serialization as well as a polyfill for ES5. - -0.4.12 2015-09-18 ------------------ -- Made ignore undefined an optional parameter. - -0.4.11 2015-08-06 ------------------ -- Minor fix for invalid key checking. - -0.4.10 2015-08-06 ------------------ -- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. -- Some performance improvements by in lining code. - -0.4.9 2015-08-06 ----------------- -- Undefined fields are omitted from serialization in objects. - -0.4.8 2015-07-14 ----------------- -- Fixed size validation to ensure we can deserialize from dumped files. - -0.4.7 2015-06-26 ----------------- -- Added ability to instruct deserializer to return raw BSON buffers for named array fields. -- Minor deserialization optimization by moving inlined function out. - -0.4.6 2015-06-17 ----------------- -- Fixed serializeWithBufferAndIndex bug. - -0.4.5 2015-06-17 ----------------- -- Removed any references to the shared buffer to avoid non GC collectible bson instances. - -0.4.4 2015-06-17 ----------------- -- Fixed rethrowing of error when not RangeError. - -0.4.3 2015-06-17 ----------------- -- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. - -0.4.2 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.1 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.0 2015-06-16 ----------------- -- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. -- Removed bson-ext extension dependency for now. - -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 diff --git a/node_modules/bson/LICENSE.md b/node_modules/bson/LICENSE.md deleted file mode 100644 index 261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64..0000000000000000000000000000000000000000 --- a/node_modules/bson/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ - 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/bson/README.md b/node_modules/bson/README.md deleted file mode 100644 index 0688341000f10b0c88cebeabc4b1c95ad3627820..0000000000000000000000000000000000000000 --- a/node_modules/bson/README.md +++ /dev/null @@ -1,170 +0,0 @@ -# BSON parser - -BSON is short for Binary JSON and is the binary-encoded serialization of JSON-like documents. You can learn more about it in [the specification](http://bsonspec.org). - -This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory. - -This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). - -## Usage - -To build a new version perform the following operations: - -``` -npm install -npm run build -``` - -A simple example of how to use BSON in the browser: - -```html -<script src="./browser_build/bson.js"></script> - -<script> - function start() { - // Get the Long type - var Long = BSON.Long; - // Create a bson parser instance - var bson = new BSON(); - - // Serialize document - var doc = { long: Long.fromNumber(100) } - - // Serialize a document - var data = bson.serialize(doc) - // De serialize it again - var doc_2 = bson.deserialize(data) - } -</script> -``` - -A simple example of how to use BSON in `Node.js`: - -```js -// Get BSON parser class -var BSON = require('bson') -// Get the Long type -var Long = BSON.Long; -// Create a bson parser instance -var bson = new BSON(); - -// Serialize document -var doc = { long: Long.fromNumber(100) } - -// Serialize a document -var data = bson.serialize(doc) -console.log('data:', data) - -// Deserialize the resulting Buffer -var doc_2 = bson.deserialize(data) -console.log('doc_2:', doc_2) -``` - -## Installation - -`npm install bson` - -## API - -### BSON types - -For all BSON types documentation, please refer to the following sources: - * [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/) - * [BSON Spec](https://bsonspec.org/) - -### BSON serialization and deserialiation - -**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON. - -#### BSON.serialize - -The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer. - - * `BSON.serialize(object, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. - -#### BSON.serializeWithBufferAndIndex - -The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. - - * `BSON.serializeWithBufferAndIndex(object, buffer, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. - * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - -#### BSON.calculateObjectSize - -The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object. - - * `BSON.calculateObjectSize(object, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. - -#### BSON.deserialize - -The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object. - - * `BSON.deserialize(buffer, options)` - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - -#### BSON.deserializeStream - -The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents. - - * `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)` - * @param {Buffer} buffer 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.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - -## FAQ - -#### Why does `undefined` get converted to `null`? - -The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. - -#### How do I add custom serialization logic? - -This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. - -```javascript -var bson = new BSON(); - -class CustomSerialize { - toBSON() { - return 42; - } -} - -const obj = { answer: new CustomSerialize() }; -// "{ answer: 42 }" -console.log(bson.deserialize(bson.serialize(obj))); -``` diff --git a/node_modules/bson/bower.json b/node_modules/bson/bower.json deleted file mode 100644 index b32140eadb815bf08cf0c193caab9fa0792b1a86..0000000000000000000000000000000000000000 --- a/node_modules/bson/bower.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "author": "Christian Amor Kvalheim <christkv@gmail.com>", - "main": "./browser_build/bson.js", - "license": "Apache-2.0", - "moduleType": [ - "globals", - "node" - ], - "ignore": [ - "**/.*", - "alternate_parsers", - "benchmarks", - "bower_components", - "node_modules", - "test", - "tools" - ] -} diff --git a/node_modules/bson/browser_build/bson.js b/node_modules/bson/browser_build/bson.js deleted file mode 100644 index a02bf14a69f4b90de2bc5bbe5161c5e2dc2808f3..0000000000000000000000000000000000000000 --- a/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,17748 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else { - var a = factory(); - for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; - } -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.loaded = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = "/"; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(1); - module.exports = __webpack_require__(327); - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {"use strict"; - - __webpack_require__(2); - - __webpack_require__(323); - - __webpack_require__(324); - - if (global._babelPolyfill) { - throw new Error("only one instance of babel-polyfill is allowed"); - } - global._babelPolyfill = true; - - var DEFINE_PROPERTY = "defineProperty"; - function define(O, key, value) { - O[key] || Object[DEFINE_PROPERTY](O, key, { - writable: true, - configurable: true, - value: value - }); - } - - define(String.prototype, "padLeft", "".padStart); - define(String.prototype, "padRight", "".padEnd); - - "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { - [][key] && define(Array, key, Function.call.bind([][key])); - }); - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(3); - __webpack_require__(51); - __webpack_require__(52); - __webpack_require__(53); - __webpack_require__(54); - __webpack_require__(56); - __webpack_require__(59); - __webpack_require__(60); - __webpack_require__(61); - __webpack_require__(62); - __webpack_require__(63); - __webpack_require__(64); - __webpack_require__(65); - __webpack_require__(66); - __webpack_require__(67); - __webpack_require__(69); - __webpack_require__(71); - __webpack_require__(73); - __webpack_require__(75); - __webpack_require__(78); - __webpack_require__(79); - __webpack_require__(80); - __webpack_require__(84); - __webpack_require__(86); - __webpack_require__(88); - __webpack_require__(91); - __webpack_require__(92); - __webpack_require__(93); - __webpack_require__(94); - __webpack_require__(96); - __webpack_require__(97); - __webpack_require__(98); - __webpack_require__(99); - __webpack_require__(100); - __webpack_require__(101); - __webpack_require__(102); - __webpack_require__(104); - __webpack_require__(105); - __webpack_require__(106); - __webpack_require__(108); - __webpack_require__(109); - __webpack_require__(110); - __webpack_require__(112); - __webpack_require__(114); - __webpack_require__(115); - __webpack_require__(116); - __webpack_require__(117); - __webpack_require__(118); - __webpack_require__(119); - __webpack_require__(120); - __webpack_require__(121); - __webpack_require__(122); - __webpack_require__(123); - __webpack_require__(124); - __webpack_require__(125); - __webpack_require__(126); - __webpack_require__(131); - __webpack_require__(132); - __webpack_require__(136); - __webpack_require__(137); - __webpack_require__(138); - __webpack_require__(139); - __webpack_require__(141); - __webpack_require__(142); - __webpack_require__(143); - __webpack_require__(144); - __webpack_require__(145); - __webpack_require__(146); - __webpack_require__(147); - __webpack_require__(148); - __webpack_require__(149); - __webpack_require__(150); - __webpack_require__(151); - __webpack_require__(152); - __webpack_require__(153); - __webpack_require__(154); - __webpack_require__(155); - __webpack_require__(157); - __webpack_require__(158); - __webpack_require__(160); - __webpack_require__(161); - __webpack_require__(167); - __webpack_require__(168); - __webpack_require__(170); - __webpack_require__(171); - __webpack_require__(172); - __webpack_require__(176); - __webpack_require__(177); - __webpack_require__(178); - __webpack_require__(179); - __webpack_require__(180); - __webpack_require__(182); - __webpack_require__(183); - __webpack_require__(184); - __webpack_require__(185); - __webpack_require__(188); - __webpack_require__(190); - __webpack_require__(191); - __webpack_require__(192); - __webpack_require__(194); - __webpack_require__(196); - __webpack_require__(198); - __webpack_require__(199); - __webpack_require__(200); - __webpack_require__(202); - __webpack_require__(203); - __webpack_require__(204); - __webpack_require__(205); - __webpack_require__(216); - __webpack_require__(220); - __webpack_require__(221); - __webpack_require__(223); - __webpack_require__(224); - __webpack_require__(228); - __webpack_require__(229); - __webpack_require__(231); - __webpack_require__(232); - __webpack_require__(233); - __webpack_require__(234); - __webpack_require__(235); - __webpack_require__(236); - __webpack_require__(237); - __webpack_require__(238); - __webpack_require__(239); - __webpack_require__(240); - __webpack_require__(241); - __webpack_require__(242); - __webpack_require__(243); - __webpack_require__(244); - __webpack_require__(245); - __webpack_require__(246); - __webpack_require__(247); - __webpack_require__(248); - __webpack_require__(249); - __webpack_require__(251); - __webpack_require__(252); - __webpack_require__(253); - __webpack_require__(254); - __webpack_require__(255); - __webpack_require__(257); - __webpack_require__(258); - __webpack_require__(259); - __webpack_require__(261); - __webpack_require__(262); - __webpack_require__(263); - __webpack_require__(264); - __webpack_require__(265); - __webpack_require__(266); - __webpack_require__(267); - __webpack_require__(268); - __webpack_require__(270); - __webpack_require__(271); - __webpack_require__(273); - __webpack_require__(274); - __webpack_require__(275); - __webpack_require__(276); - __webpack_require__(279); - __webpack_require__(280); - __webpack_require__(282); - __webpack_require__(283); - __webpack_require__(284); - __webpack_require__(285); - __webpack_require__(287); - __webpack_require__(288); - __webpack_require__(289); - __webpack_require__(290); - __webpack_require__(291); - __webpack_require__(292); - __webpack_require__(293); - __webpack_require__(294); - __webpack_require__(295); - __webpack_require__(296); - __webpack_require__(298); - __webpack_require__(299); - __webpack_require__(300); - __webpack_require__(301); - __webpack_require__(302); - __webpack_require__(303); - __webpack_require__(304); - __webpack_require__(305); - __webpack_require__(306); - __webpack_require__(307); - __webpack_require__(308); - __webpack_require__(310); - __webpack_require__(311); - __webpack_require__(312); - __webpack_require__(313); - __webpack_require__(314); - __webpack_require__(315); - __webpack_require__(316); - __webpack_require__(317); - __webpack_require__(318); - __webpack_require__(319); - __webpack_require__(320); - __webpack_require__(321); - __webpack_require__(322); - module.exports = __webpack_require__(9); - - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // ECMAScript 6 symbols shim - var global = __webpack_require__(4); - var has = __webpack_require__(5); - var DESCRIPTORS = __webpack_require__(6); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var META = __webpack_require__(22).KEY; - var $fails = __webpack_require__(7); - var shared = __webpack_require__(23); - var setToStringTag = __webpack_require__(25); - var uid = __webpack_require__(19); - var wks = __webpack_require__(26); - var wksExt = __webpack_require__(27); - var wksDefine = __webpack_require__(28); - var enumKeys = __webpack_require__(29); - var isArray = __webpack_require__(44); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var toIObject = __webpack_require__(32); - var toPrimitive = __webpack_require__(16); - var createDesc = __webpack_require__(17); - var _create = __webpack_require__(45); - var gOPNExt = __webpack_require__(48); - var $GOPD = __webpack_require__(50); - var $DP = __webpack_require__(11); - var $keys = __webpack_require__(30); - var gOPD = $GOPD.f; - var dP = $DP.f; - var gOPN = gOPNExt.f; - var $Symbol = global.Symbol; - var $JSON = global.JSON; - var _stringify = $JSON && $JSON.stringify; - var PROTOTYPE = 'prototype'; - var HIDDEN = wks('_hidden'); - var TO_PRIMITIVE = wks('toPrimitive'); - var isEnum = {}.propertyIsEnumerable; - var SymbolRegistry = shared('symbol-registry'); - var AllSymbols = shared('symbols'); - var OPSymbols = shared('op-symbols'); - var ObjectProto = Object[PROTOTYPE]; - var USE_NATIVE = typeof $Symbol == 'function'; - var QObject = global.QObject; - // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 - var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; - - // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 - var setSymbolDesc = DESCRIPTORS && $fails(function () { - return _create(dP({}, 'a', { - get: function () { return dP(this, 'a', { value: 7 }).a; } - })).a != 7; - }) ? function (it, key, D) { - var protoDesc = gOPD(ObjectProto, key); - if (protoDesc) delete ObjectProto[key]; - dP(it, key, D); - if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); - } : dP; - - var wrap = function (tag) { - var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); - sym._k = tag; - return sym; - }; - - var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { - return typeof it == 'symbol'; - } : function (it) { - return it instanceof $Symbol; - }; - - var $defineProperty = function defineProperty(it, key, D) { - if (it === ObjectProto) $defineProperty(OPSymbols, key, D); - anObject(it); - key = toPrimitive(key, true); - anObject(D); - if (has(AllSymbols, key)) { - if (!D.enumerable) { - if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); - it[HIDDEN][key] = true; - } else { - if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; - D = _create(D, { enumerable: createDesc(0, false) }); - } return setSymbolDesc(it, key, D); - } return dP(it, key, D); - }; - var $defineProperties = function defineProperties(it, P) { - anObject(it); - var keys = enumKeys(P = toIObject(P)); - var i = 0; - var l = keys.length; - var key; - while (l > i) $defineProperty(it, key = keys[i++], P[key]); - return it; - }; - var $create = function create(it, P) { - return P === undefined ? _create(it) : $defineProperties(_create(it), P); - }; - var $propertyIsEnumerable = function propertyIsEnumerable(key) { - var E = isEnum.call(this, key = toPrimitive(key, true)); - if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; - return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; - }; - var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { - it = toIObject(it); - key = toPrimitive(key, true); - if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; - var D = gOPD(it, key); - if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; - return D; - }; - var $getOwnPropertyNames = function getOwnPropertyNames(it) { - var names = gOPN(toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); - } return result; - }; - var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { - var IS_OP = it === ObjectProto; - var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); - } return result; - }; - - // 19.4.1.1 Symbol([description]) - if (!USE_NATIVE) { - $Symbol = function Symbol() { - if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); - var tag = uid(arguments.length > 0 ? arguments[0] : undefined); - var $set = function (value) { - if (this === ObjectProto) $set.call(OPSymbols, value); - if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; - setSymbolDesc(this, tag, createDesc(1, value)); - }; - if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); - return wrap(tag); - }; - redefine($Symbol[PROTOTYPE], 'toString', function toString() { - return this._k; - }); - - $GOPD.f = $getOwnPropertyDescriptor; - $DP.f = $defineProperty; - __webpack_require__(49).f = gOPNExt.f = $getOwnPropertyNames; - __webpack_require__(43).f = $propertyIsEnumerable; - __webpack_require__(42).f = $getOwnPropertySymbols; - - if (DESCRIPTORS && !__webpack_require__(24)) { - redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); - } - - wksExt.f = function (name) { - return wrap(wks(name)); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); - - for (var es6Symbols = ( - // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 - 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' - ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); - - for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); - - $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { - // 19.4.2.1 Symbol.for(key) - 'for': function (key) { - return has(SymbolRegistry, key += '') - ? SymbolRegistry[key] - : SymbolRegistry[key] = $Symbol(key); - }, - // 19.4.2.5 Symbol.keyFor(sym) - keyFor: function keyFor(sym) { - if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); - for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; - }, - useSetter: function () { setter = true; }, - useSimple: function () { setter = false; } - }); - - $export($export.S + $export.F * !USE_NATIVE, 'Object', { - // 19.1.2.2 Object.create(O [, Properties]) - create: $create, - // 19.1.2.4 Object.defineProperty(O, P, Attributes) - defineProperty: $defineProperty, - // 19.1.2.3 Object.defineProperties(O, Properties) - defineProperties: $defineProperties, - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - getOwnPropertyDescriptor: $getOwnPropertyDescriptor, - // 19.1.2.7 Object.getOwnPropertyNames(O) - getOwnPropertyNames: $getOwnPropertyNames, - // 19.1.2.8 Object.getOwnPropertySymbols(O) - getOwnPropertySymbols: $getOwnPropertySymbols - }); - - // 24.3.2 JSON.stringify(value [, replacer [, space]]) - $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { - var S = $Symbol(); - // MS Edge converts symbol values to JSON as {} - // WebKit converts symbol values to JSON as null - // V8 throws on boxed symbols - return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; - })), 'JSON', { - stringify: function stringify(it) { - var args = [it]; - var i = 1; - var replacer, $replacer; - while (arguments.length > i) args.push(arguments[i++]); - $replacer = replacer = args[1]; - if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined - if (!isArray(replacer)) replacer = function (key, value) { - if (typeof $replacer == 'function') value = $replacer.call(this, key, value); - if (!isSymbol(value)) return value; - }; - args[1] = replacer; - return _stringify.apply($JSON, args); - } - }); - - // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) - $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); - // 19.4.3.5 Symbol.prototype[@@toStringTag] - setToStringTag($Symbol, 'Symbol'); - // 20.2.1.9 Math[@@toStringTag] - setToStringTag(Math, 'Math', true); - // 24.3.3 JSON[@@toStringTag] - setToStringTag(global.JSON, 'JSON', true); - - -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self - // eslint-disable-next-line no-new-func - : Function('return this')(); - if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef - - -/***/ }), -/* 5 */ -/***/ (function(module, exports) { - - var hasOwnProperty = {}.hasOwnProperty; - module.exports = function (it, key) { - return hasOwnProperty.call(it, key); - }; - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - - // Thank's IE8 for his funny defineProperty - module.exports = !__webpack_require__(7)(function () { - return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; - }); - - -/***/ }), -/* 7 */ -/***/ (function(module, exports) { - - module.exports = function (exec) { - try { - return !!exec(); - } catch (e) { - return true; - } - }; - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var hide = __webpack_require__(10); - var redefine = __webpack_require__(18); - var ctx = __webpack_require__(20); - var PROTOTYPE = 'prototype'; - - var $export = function (type, name, source) { - var IS_FORCED = type & $export.F; - var IS_GLOBAL = type & $export.G; - var IS_STATIC = type & $export.S; - var IS_PROTO = type & $export.P; - var IS_BIND = type & $export.B; - var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; - var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); - var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); - var key, own, out, exp; - if (IS_GLOBAL) source = name; - for (key in source) { - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - // export native or passed - out = (own ? target : source)[key]; - // bind timers to global for call from export context - exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // extend global - if (target) redefine(target, key, out, type & $export.U); - // export - if (exports[key] != out) hide(exports, key, exp); - if (IS_PROTO && expProto[key] != out) expProto[key] = out; - } - }; - global.core = core; - // type bitmap - $export.F = 1; // forced - $export.G = 2; // global - $export.S = 4; // static - $export.P = 8; // proto - $export.B = 16; // bind - $export.W = 32; // wrap - $export.U = 64; // safe - $export.R = 128; // real proto method for `library` - module.exports = $export; - - -/***/ }), -/* 9 */ -/***/ (function(module, exports) { - - var core = module.exports = { version: '2.5.7' }; - if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11); - var createDesc = __webpack_require__(17); - module.exports = __webpack_require__(6) ? function (object, key, value) { - return dP.f(object, key, createDesc(1, value)); - } : function (object, key, value) { - object[key] = value; - return object; - }; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12); - var IE8_DOM_DEFINE = __webpack_require__(14); - var toPrimitive = __webpack_require__(16); - var dP = Object.defineProperty; - - exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes) { - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if (IE8_DOM_DEFINE) try { - return dP(O, P, Attributes); - } catch (e) { /* empty */ } - if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); - if ('value' in Attributes) O[P] = Attributes.value; - return O; - }; - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function (it) { - if (!isObject(it)) throw TypeError(it + ' is not an object!'); - return it; - }; - - -/***/ }), -/* 13 */ -/***/ (function(module, exports) { - - module.exports = function (it) { - return typeof it === 'object' ? it !== null : typeof it === 'function'; - }; - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - - module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function () { - return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7; - }); - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var document = __webpack_require__(4).document; - // typeof document.createElement is 'object' in old IE - var is = isObject(document) && isObject(document.createElement); - module.exports = function (it) { - return is ? document.createElement(it) : {}; - }; - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.1 ToPrimitive(input [, PreferredType]) - var isObject = __webpack_require__(13); - // instead of the ES6 spec version, we didn't implement @@toPrimitive case - // and the second argument - flag - preferred type is a string - module.exports = function (it, S) { - if (!isObject(it)) return it; - var fn, val; - if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; - if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - throw TypeError("Can't convert object to primitive value"); - }; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports) { - - module.exports = function (bitmap, value) { - return { - enumerable: !(bitmap & 1), - configurable: !(bitmap & 2), - writable: !(bitmap & 4), - value: value - }; - }; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var has = __webpack_require__(5); - var SRC = __webpack_require__(19)('src'); - var TO_STRING = 'toString'; - var $toString = Function[TO_STRING]; - var TPL = ('' + $toString).split(TO_STRING); - - __webpack_require__(9).inspectSource = function (it) { - return $toString.call(it); - }; - - (module.exports = function (O, key, val, safe) { - var isFunction = typeof val == 'function'; - if (isFunction) has(val, 'name') || hide(val, 'name', key); - if (O[key] === val) return; - if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); - if (O === global) { - O[key] = val; - } else if (!safe) { - delete O[key]; - hide(O, key, val); - } else if (O[key]) { - O[key] = val; - } else { - hide(O, key, val); - } - // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative - })(Function.prototype, TO_STRING, function toString() { - return typeof this == 'function' && this[SRC] || $toString.call(this); - }); - - -/***/ }), -/* 19 */ -/***/ (function(module, exports) { - - var id = 0; - var px = Math.random(); - module.exports = function (key) { - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); - }; - - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - - // optional / simple context binding - var aFunction = __webpack_require__(21); - module.exports = function (fn, that, length) { - aFunction(fn); - if (that === undefined) return fn; - switch (length) { - case 1: return function (a) { - return fn.call(that, a); - }; - case 2: return function (a, b) { - return fn.call(that, a, b); - }; - case 3: return function (a, b, c) { - return fn.call(that, a, b, c); - }; - } - return function (/* ...args */) { - return fn.apply(that, arguments); - }; - }; - - -/***/ }), -/* 21 */ -/***/ (function(module, exports) { - - module.exports = function (it) { - if (typeof it != 'function') throw TypeError(it + ' is not a function!'); - return it; - }; - - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - - var META = __webpack_require__(19)('meta'); - var isObject = __webpack_require__(13); - var has = __webpack_require__(5); - var setDesc = __webpack_require__(11).f; - var id = 0; - var isExtensible = Object.isExtensible || function () { - return true; - }; - var FREEZE = !__webpack_require__(7)(function () { - return isExtensible(Object.preventExtensions({})); - }); - var setMeta = function (it) { - setDesc(it, META, { value: { - i: 'O' + ++id, // object ID - w: {} // weak collections IDs - } }); - }; - var fastKey = function (it, create) { - // return primitive with prefix - if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return 'F'; - // not necessary to add metadata - if (!create) return 'E'; - // add missing metadata - setMeta(it); - // return object ID - } return it[META].i; - }; - var getWeak = function (it, create) { - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return true; - // not necessary to add metadata - if (!create) return false; - // add missing metadata - setMeta(it); - // return hash weak collections IDs - } return it[META].w; - }; - // add metadata on freeze-family methods calling - var onFreeze = function (it) { - if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); - return it; - }; - var meta = module.exports = { - KEY: META, - NEED: false, - fastKey: fastKey, - getWeak: getWeak, - onFreeze: onFreeze - }; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - - var core = __webpack_require__(9); - var global = __webpack_require__(4); - var SHARED = '__core-js_shared__'; - var store = global[SHARED] || (global[SHARED] = {}); - - (module.exports = function (key, value) { - return store[key] || (store[key] = value !== undefined ? value : {}); - })('versions', []).push({ - version: core.version, - mode: __webpack_require__(24) ? 'pure' : 'global', - copyright: '© 2018 Denis Pushkarev (zloirock.ru)' - }); - - -/***/ }), -/* 24 */ -/***/ (function(module, exports) { - - module.exports = false; - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - - var def = __webpack_require__(11).f; - var has = __webpack_require__(5); - var TAG = __webpack_require__(26)('toStringTag'); - - module.exports = function (it, tag, stat) { - if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); - }; - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - - var store = __webpack_require__(23)('wks'); - var uid = __webpack_require__(19); - var Symbol = __webpack_require__(4).Symbol; - var USE_SYMBOL = typeof Symbol == 'function'; - - var $exports = module.exports = function (name) { - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); - }; - - $exports.store = store; - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - - exports.f = __webpack_require__(26); - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var LIBRARY = __webpack_require__(24); - var wksExt = __webpack_require__(27); - var defineProperty = __webpack_require__(11).f; - module.exports = function (name) { - var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); - if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); - }; - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - - // all enumerable object keys, includes symbols - var getKeys = __webpack_require__(30); - var gOPS = __webpack_require__(42); - var pIE = __webpack_require__(43); - module.exports = function (it) { - var result = getKeys(it); - var getSymbols = gOPS.f; - if (getSymbols) { - var symbols = getSymbols(it); - var isEnum = pIE.f; - var i = 0; - var key; - while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); - } return result; - }; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.14 / 15.2.3.14 Object.keys(O) - var $keys = __webpack_require__(31); - var enumBugKeys = __webpack_require__(41); - - module.exports = Object.keys || function keys(O) { - return $keys(O, enumBugKeys); - }; - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - - var has = __webpack_require__(5); - var toIObject = __webpack_require__(32); - var arrayIndexOf = __webpack_require__(36)(false); - var IE_PROTO = __webpack_require__(40)('IE_PROTO'); - - module.exports = function (object, names) { - var O = toIObject(object); - var i = 0; - var result = []; - var key; - for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while (names.length > i) if (has(O, key = names[i++])) { - ~arrayIndexOf(result, key) || result.push(key); - } - return result; - }; - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - - // to indexed object, toObject with fallback for non-array-like ES3 strings - var IObject = __webpack_require__(33); - var defined = __webpack_require__(35); - module.exports = function (it) { - return IObject(defined(it)); - }; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - - // fallback for non-array-like ES3 and non-enumerable old V8 strings - var cof = __webpack_require__(34); - // eslint-disable-next-line no-prototype-builtins - module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { - return cof(it) == 'String' ? it.split('') : Object(it); - }; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports) { - - var toString = {}.toString; - - module.exports = function (it) { - return toString.call(it).slice(8, -1); - }; - - -/***/ }), -/* 35 */ -/***/ (function(module, exports) { - - // 7.2.1 RequireObjectCoercible(argument) - module.exports = function (it) { - if (it == undefined) throw TypeError("Can't call method on " + it); - return it; - }; - - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - - // false -> Array#indexOf - // true -> Array#includes - var toIObject = __webpack_require__(32); - var toLength = __webpack_require__(37); - var toAbsoluteIndex = __webpack_require__(39); - module.exports = function (IS_INCLUDES) { - return function ($this, el, fromIndex) { - var O = toIObject($this); - var length = toLength(O.length); - var index = toAbsoluteIndex(fromIndex, length); - var value; - // Array#includes uses SameValueZero equality algorithm - // eslint-disable-next-line no-self-compare - if (IS_INCLUDES && el != el) while (length > index) { - value = O[index++]; - // eslint-disable-next-line no-self-compare - if (value != value) return true; - // Array#indexOf ignores holes, Array#includes - not - } else for (;length > index; index++) if (IS_INCLUDES || index in O) { - if (O[index] === el) return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; - }; - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.15 ToLength - var toInteger = __webpack_require__(38); - var min = Math.min; - module.exports = function (it) { - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 - }; - - -/***/ }), -/* 38 */ -/***/ (function(module, exports) { - - // 7.1.4 ToInteger - var ceil = Math.ceil; - var floor = Math.floor; - module.exports = function (it) { - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); - }; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(38); - var max = Math.max; - var min = Math.min; - module.exports = function (index, length) { - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); - }; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - - var shared = __webpack_require__(23)('keys'); - var uid = __webpack_require__(19); - module.exports = function (key) { - return shared[key] || (shared[key] = uid(key)); - }; - - -/***/ }), -/* 41 */ -/***/ (function(module, exports) { - - // IE 8- don't enum bug keys - module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' - ).split(','); - - -/***/ }), -/* 42 */ -/***/ (function(module, exports) { - - exports.f = Object.getOwnPropertySymbols; - - -/***/ }), -/* 43 */ -/***/ (function(module, exports) { - - exports.f = {}.propertyIsEnumerable; - - -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.2.2 IsArray(argument) - var cof = __webpack_require__(34); - module.exports = Array.isArray || function isArray(arg) { - return cof(arg) == 'Array'; - }; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - var anObject = __webpack_require__(12); - var dPs = __webpack_require__(46); - var enumBugKeys = __webpack_require__(41); - var IE_PROTO = __webpack_require__(40)('IE_PROTO'); - var Empty = function () { /* empty */ }; - var PROTOTYPE = 'prototype'; - - // Create object with fake `null` prototype: use iframe Object with cleared prototype - var createDict = function () { - // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(15)('iframe'); - var i = enumBugKeys.length; - var lt = '<'; - var gt = '>'; - var iframeDocument; - iframe.style.display = 'none'; - __webpack_require__(47).appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); - }; - - module.exports = Object.create || function create(O, Properties) { - var result; - if (O !== null) { - Empty[PROTOTYPE] = anObject(O); - result = new Empty(); - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); - }; - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11); - var anObject = __webpack_require__(12); - var getKeys = __webpack_require__(30); - - module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties) { - anObject(O); - var keys = getKeys(Properties); - var length = keys.length; - var i = 0; - var P; - while (length > i) dP.f(O, P = keys[i++], Properties[P]); - return O; - }; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - - var document = __webpack_require__(4).document; - module.exports = document && document.documentElement; - - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - - // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window - var toIObject = __webpack_require__(32); - var gOPN = __webpack_require__(49).f; - var toString = {}.toString; - - var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; - - var getWindowNames = function (it) { - try { - return gOPN(it); - } catch (e) { - return windowNames.slice(); - } - }; - - module.exports.f = function getOwnPropertyNames(it) { - return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); - }; - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) - var $keys = __webpack_require__(31); - var hiddenKeys = __webpack_require__(41).concat('length', 'prototype'); - - exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { - return $keys(O, hiddenKeys); - }; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - - var pIE = __webpack_require__(43); - var createDesc = __webpack_require__(17); - var toIObject = __webpack_require__(32); - var toPrimitive = __webpack_require__(16); - var has = __webpack_require__(5); - var IE8_DOM_DEFINE = __webpack_require__(14); - var gOPD = Object.getOwnPropertyDescriptor; - - exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P) { - O = toIObject(O); - P = toPrimitive(P, true); - if (IE8_DOM_DEFINE) try { - return gOPD(O, P); - } catch (e) { /* empty */ } - if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); - }; - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - $export($export.S, 'Object', { create: __webpack_require__(45) }); - - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperty: __webpack_require__(11).f }); - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperties: __webpack_require__(46) }); - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - var toIObject = __webpack_require__(32); - var $getOwnPropertyDescriptor = __webpack_require__(50).f; - - __webpack_require__(55)('getOwnPropertyDescriptor', function () { - return function getOwnPropertyDescriptor(it, key) { - return $getOwnPropertyDescriptor(toIObject(it), key); - }; - }); - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - - // most Object methods by ES6 should accept primitives - var $export = __webpack_require__(8); - var core = __webpack_require__(9); - var fails = __webpack_require__(7); - module.exports = function (KEY, exec) { - var fn = (core.Object || {})[KEY] || Object[KEY]; - var exp = {}; - exp[KEY] = exec(fn); - $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); - }; - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.9 Object.getPrototypeOf(O) - var toObject = __webpack_require__(57); - var $getPrototypeOf = __webpack_require__(58); - - __webpack_require__(55)('getPrototypeOf', function () { - return function getPrototypeOf(it) { - return $getPrototypeOf(toObject(it)); - }; - }); - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.13 ToObject(argument) - var defined = __webpack_require__(35); - module.exports = function (it) { - return Object(defined(it)); - }; - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) - var has = __webpack_require__(5); - var toObject = __webpack_require__(57); - var IE_PROTO = __webpack_require__(40)('IE_PROTO'); - var ObjectProto = Object.prototype; - - module.exports = Object.getPrototypeOf || function (O) { - O = toObject(O); - if (has(O, IE_PROTO)) return O[IE_PROTO]; - if (typeof O.constructor == 'function' && O instanceof O.constructor) { - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; - }; - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.14 Object.keys(O) - var toObject = __webpack_require__(57); - var $keys = __webpack_require__(30); - - __webpack_require__(55)('keys', function () { - return function keys(it) { - return $keys(toObject(it)); - }; - }); - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.7 Object.getOwnPropertyNames(O) - __webpack_require__(55)('getOwnPropertyNames', function () { - return __webpack_require__(48).f; - }); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.5 Object.freeze(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(22).onFreeze; - - __webpack_require__(55)('freeze', function ($freeze) { - return function freeze(it) { - return $freeze && isObject(it) ? $freeze(meta(it)) : it; - }; - }); - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.17 Object.seal(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(22).onFreeze; - - __webpack_require__(55)('seal', function ($seal) { - return function seal(it) { - return $seal && isObject(it) ? $seal(meta(it)) : it; - }; - }); - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.15 Object.preventExtensions(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(22).onFreeze; - - __webpack_require__(55)('preventExtensions', function ($preventExtensions) { - return function preventExtensions(it) { - return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; - }; - }); - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.12 Object.isFrozen(O) - var isObject = __webpack_require__(13); - - __webpack_require__(55)('isFrozen', function ($isFrozen) { - return function isFrozen(it) { - return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; - }; - }); - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.13 Object.isSealed(O) - var isObject = __webpack_require__(13); - - __webpack_require__(55)('isSealed', function ($isSealed) { - return function isSealed(it) { - return isObject(it) ? $isSealed ? $isSealed(it) : false : true; - }; - }); - - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.11 Object.isExtensible(O) - var isObject = __webpack_require__(13); - - __webpack_require__(55)('isExtensible', function ($isExtensible) { - return function isExtensible(it) { - return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; - }; - }); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.1 Object.assign(target, source) - var $export = __webpack_require__(8); - - $export($export.S + $export.F, 'Object', { assign: __webpack_require__(68) }); - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.2.1 Object.assign(target, source, ...) - var getKeys = __webpack_require__(30); - var gOPS = __webpack_require__(42); - var pIE = __webpack_require__(43); - var toObject = __webpack_require__(57); - var IObject = __webpack_require__(33); - var $assign = Object.assign; - - // should work with symbols and should have deterministic property order (V8 bug) - module.exports = !$assign || __webpack_require__(7)(function () { - var A = {}; - var B = {}; - // eslint-disable-next-line no-undef - var S = Symbol(); - var K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function (k) { B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; - }) ? function assign(target, source) { // eslint-disable-line no-unused-vars - var T = toObject(target); - var aLen = arguments.length; - var index = 1; - var getSymbols = gOPS.f; - var isEnum = pIE.f; - while (aLen > index) { - var S = IObject(arguments[index++]); - var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); - var length = keys.length; - var j = 0; - var key; - while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; - } return T; - } : $assign; - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.10 Object.is(value1, value2) - var $export = __webpack_require__(8); - $export($export.S, 'Object', { is: __webpack_require__(70) }); - - -/***/ }), -/* 70 */ -/***/ (function(module, exports) { - - // 7.2.9 SameValue(x, y) - module.exports = Object.is || function is(x, y) { - // eslint-disable-next-line no-self-compare - return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; - }; - - -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.19 Object.setPrototypeOf(O, proto) - var $export = __webpack_require__(8); - $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(72).set }); - - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - - // Works with __proto__ only. Old v8 can't work with null proto objects. - /* eslint-disable no-proto */ - var isObject = __webpack_require__(13); - var anObject = __webpack_require__(12); - var check = function (O, proto) { - anObject(O); - if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); - }; - module.exports = { - set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line - function (test, buggy, set) { - try { - set = __webpack_require__(20)(Function.call, __webpack_require__(50).f(Object.prototype, '__proto__').set, 2); - set(test, []); - buggy = !(test instanceof Array); - } catch (e) { buggy = true; } - return function setPrototypeOf(O, proto) { - check(O, proto); - if (buggy) O.__proto__ = proto; - else set(O, proto); - return O; - }; - }({}, false) : undefined), - check: check - }; - - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.3.6 Object.prototype.toString() - var classof = __webpack_require__(74); - var test = {}; - test[__webpack_require__(26)('toStringTag')] = 'z'; - if (test + '' != '[object z]') { - __webpack_require__(18)(Object.prototype, 'toString', function toString() { - return '[object ' + classof(this) + ']'; - }, true); - } - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - - // getting tag from 19.1.3.6 Object.prototype.toString() - var cof = __webpack_require__(34); - var TAG = __webpack_require__(26)('toStringTag'); - // ES3 wrong here - var ARG = cof(function () { return arguments; }()) == 'Arguments'; - - // fallback for IE11 Script Access Denied error - var tryGet = function (it, key) { - try { - return it[key]; - } catch (e) { /* empty */ } - }; - - module.exports = function (it) { - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; - }; - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) - var $export = __webpack_require__(8); - - $export($export.P, 'Function', { bind: __webpack_require__(76) }); - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var aFunction = __webpack_require__(21); - var isObject = __webpack_require__(13); - var invoke = __webpack_require__(77); - var arraySlice = [].slice; - var factories = {}; - - var construct = function (F, len, args) { - if (!(len in factories)) { - for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; - // eslint-disable-next-line no-new-func - factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); - } return factories[len](F, args); - }; - - module.exports = Function.bind || function bind(that /* , ...args */) { - var fn = aFunction(this); - var partArgs = arraySlice.call(arguments, 1); - var bound = function (/* args... */) { - var args = partArgs.concat(arraySlice.call(arguments)); - return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); - }; - if (isObject(fn.prototype)) bound.prototype = fn.prototype; - return bound; - }; - - -/***/ }), -/* 77 */ -/***/ (function(module, exports) { - - // fast apply, http://jsperf.lnkit.com/fast-apply/5 - module.exports = function (fn, args, that) { - var un = that === undefined; - switch (args.length) { - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); - }; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11).f; - var FProto = Function.prototype; - var nameRE = /^\s*function ([^ (]*)/; - var NAME = 'name'; - - // 19.2.4.2 name - NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { - configurable: true, - get: function () { - try { - return ('' + this).match(nameRE)[1]; - } catch (e) { - return ''; - } - } - }); - - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var isObject = __webpack_require__(13); - var getPrototypeOf = __webpack_require__(58); - var HAS_INSTANCE = __webpack_require__(26)('hasInstance'); - var FunctionProto = Function.prototype; - // 19.2.3.6 Function.prototype[@@hasInstance](V) - if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(11).f(FunctionProto, HAS_INSTANCE, { value: function (O) { - if (typeof this != 'function' || !isObject(O)) return false; - if (!isObject(this.prototype)) return O instanceof this; - // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: - while (O = getPrototypeOf(O)) if (this.prototype === O) return true; - return false; - } }); - - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseInt = __webpack_require__(81); - // 18.2.5 parseInt(string, radix) - $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); - - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - - var $parseInt = __webpack_require__(4).parseInt; - var $trim = __webpack_require__(82).trim; - var ws = __webpack_require__(83); - var hex = /^[-+]?0[xX]/; - - module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) { - var string = $trim(String(str), 3); - return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); - } : $parseInt; - - -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var defined = __webpack_require__(35); - var fails = __webpack_require__(7); - var spaces = __webpack_require__(83); - var space = '[' + spaces + ']'; - var non = '\u200b\u0085'; - var ltrim = RegExp('^' + space + space + '*'); - var rtrim = RegExp(space + space + '*$'); - - var exporter = function (KEY, exec, ALIAS) { - var exp = {}; - var FORCE = fails(function () { - return !!spaces[KEY]() || non[KEY]() != non; - }); - var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; - if (ALIAS) exp[ALIAS] = fn; - $export($export.P + $export.F * FORCE, 'String', exp); - }; - - // 1 -> String#trimLeft - // 2 -> String#trimRight - // 3 -> String#trim - var trim = exporter.trim = function (string, TYPE) { - string = String(defined(string)); - if (TYPE & 1) string = string.replace(ltrim, ''); - if (TYPE & 2) string = string.replace(rtrim, ''); - return string; - }; - - module.exports = exporter; - - -/***/ }), -/* 83 */ -/***/ (function(module, exports) { - - module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; - - -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseFloat = __webpack_require__(85); - // 18.2.4 parseFloat(string) - $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); - - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - - var $parseFloat = __webpack_require__(4).parseFloat; - var $trim = __webpack_require__(82).trim; - - module.exports = 1 / $parseFloat(__webpack_require__(83) + '-0') !== -Infinity ? function parseFloat(str) { - var string = $trim(String(str), 3); - var result = $parseFloat(string); - return result === 0 && string.charAt(0) == '-' ? -0 : result; - } : $parseFloat; - - -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var has = __webpack_require__(5); - var cof = __webpack_require__(34); - var inheritIfRequired = __webpack_require__(87); - var toPrimitive = __webpack_require__(16); - var fails = __webpack_require__(7); - var gOPN = __webpack_require__(49).f; - var gOPD = __webpack_require__(50).f; - var dP = __webpack_require__(11).f; - var $trim = __webpack_require__(82).trim; - var NUMBER = 'Number'; - var $Number = global[NUMBER]; - var Base = $Number; - var proto = $Number.prototype; - // Opera ~12 has broken Object#toString - var BROKEN_COF = cof(__webpack_require__(45)(proto)) == NUMBER; - var TRIM = 'trim' in String.prototype; - - // 7.1.3 ToNumber(argument) - var toNumber = function (argument) { - var it = toPrimitive(argument, false); - if (typeof it == 'string' && it.length > 2) { - it = TRIM ? it.trim() : $trim(it, 3); - var first = it.charCodeAt(0); - var third, radix, maxCode; - if (first === 43 || first === 45) { - third = it.charCodeAt(2); - if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix - } else if (first === 48) { - switch (it.charCodeAt(1)) { - case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i - case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i - default: return +it; - } - for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) { - code = digits.charCodeAt(i); - // parseInt parses a string to a first unavailable symbol - // but ToNumber should return NaN if a string contains unavailable symbols - if (code < 48 || code > maxCode) return NaN; - } return parseInt(digits, radix); - } - } return +it; - }; - - if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { - $Number = function Number(value) { - var it = arguments.length < 1 ? 0 : value; - var that = this; - return that instanceof $Number - // check on 1..constructor(foo) case - && (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER) - ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); - }; - for (var keys = __webpack_require__(6) ? gOPN(Base) : ( - // ES3: - 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + - // ES6 (in case, if modules with ES6 Number statics required before): - 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + - 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' - ).split(','), j = 0, key; keys.length > j; j++) { - if (has(Base, key = keys[j]) && !has($Number, key)) { - dP($Number, key, gOPD(Base, key)); - } - } - $Number.prototype = proto; - proto.constructor = $Number; - __webpack_require__(18)(global, NUMBER, $Number); - } - - -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var setPrototypeOf = __webpack_require__(72).set; - module.exports = function (that, target, C) { - var S = target.constructor; - var P; - if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { - setPrototypeOf(that, P); - } return that; - }; - - -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toInteger = __webpack_require__(38); - var aNumberValue = __webpack_require__(89); - var repeat = __webpack_require__(90); - var $toFixed = 1.0.toFixed; - var floor = Math.floor; - var data = [0, 0, 0, 0, 0, 0]; - var ERROR = 'Number.toFixed: incorrect invocation!'; - var ZERO = '0'; - - var multiply = function (n, c) { - var i = -1; - var c2 = c; - while (++i < 6) { - c2 += n * data[i]; - data[i] = c2 % 1e7; - c2 = floor(c2 / 1e7); - } - }; - var divide = function (n) { - var i = 6; - var c = 0; - while (--i >= 0) { - c += data[i]; - data[i] = floor(c / n); - c = (c % n) * 1e7; - } - }; - var numToString = function () { - var i = 6; - var s = ''; - while (--i >= 0) { - if (s !== '' || i === 0 || data[i] !== 0) { - var t = String(data[i]); - s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; - } - } return s; - }; - var pow = function (x, n, acc) { - return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); - }; - var log = function (x) { - var n = 0; - var x2 = x; - while (x2 >= 4096) { - n += 12; - x2 /= 4096; - } - while (x2 >= 2) { - n += 1; - x2 /= 2; - } return n; - }; - - $export($export.P + $export.F * (!!$toFixed && ( - 0.00008.toFixed(3) !== '0.000' || - 0.9.toFixed(0) !== '1' || - 1.255.toFixed(2) !== '1.25' || - 1000000000000000128.0.toFixed(0) !== '1000000000000000128' - ) || !__webpack_require__(7)(function () { - // V8 ~ Android 4.3- - $toFixed.call({}); - })), 'Number', { - toFixed: function toFixed(fractionDigits) { - var x = aNumberValue(this, ERROR); - var f = toInteger(fractionDigits); - var s = ''; - var m = ZERO; - var e, z, j, k; - if (f < 0 || f > 20) throw RangeError(ERROR); - // eslint-disable-next-line no-self-compare - if (x != x) return 'NaN'; - if (x <= -1e21 || x >= 1e21) return String(x); - if (x < 0) { - s = '-'; - x = -x; - } - if (x > 1e-21) { - e = log(x * pow(2, 69, 1)) - 69; - z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); - z *= 0x10000000000000; - e = 52 - e; - if (e > 0) { - multiply(0, z); - j = f; - while (j >= 7) { - multiply(1e7, 0); - j -= 7; - } - multiply(pow(10, j, 1), 0); - j = e - 1; - while (j >= 23) { - divide(1 << 23); - j -= 23; - } - divide(1 << j); - multiply(1, 1); - divide(2); - m = numToString(); - } else { - multiply(0, z); - multiply(1 << -e, 0); - m = numToString() + repeat.call(ZERO, f); - } - } - if (f > 0) { - k = m.length; - m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); - } else { - m = s + m; - } return m; - } - }); - - -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { - - var cof = __webpack_require__(34); - module.exports = function (it, msg) { - if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); - return +it; - }; - - -/***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var toInteger = __webpack_require__(38); - var defined = __webpack_require__(35); - - module.exports = function repeat(count) { - var str = String(defined(this)); - var res = ''; - var n = toInteger(count); - if (n < 0 || n == Infinity) throw RangeError("Count can't be negative"); - for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str; - return res; - }; - - -/***/ }), -/* 91 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $fails = __webpack_require__(7); - var aNumberValue = __webpack_require__(89); - var $toPrecision = 1.0.toPrecision; - - $export($export.P + $export.F * ($fails(function () { - // IE7- - return $toPrecision.call(1, undefined) !== '1'; - }) || !$fails(function () { - // V8 ~ Android 4.3- - $toPrecision.call({}); - })), 'Number', { - toPrecision: function toPrecision(precision) { - var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); - return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); - } - }); - - -/***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.1 Number.EPSILON - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); - - -/***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.2 Number.isFinite(number) - var $export = __webpack_require__(8); - var _isFinite = __webpack_require__(4).isFinite; - - $export($export.S, 'Number', { - isFinite: function isFinite(it) { - return typeof it == 'number' && _isFinite(it); - } - }); - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { isInteger: __webpack_require__(95) }); - - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var isObject = __webpack_require__(13); - var floor = Math.floor; - module.exports = function isInteger(it) { - return !isObject(it) && isFinite(it) && floor(it) === it; - }; - - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.4 Number.isNaN(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { - isNaN: function isNaN(number) { - // eslint-disable-next-line no-self-compare - return number != number; - } - }); - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.5 Number.isSafeInteger(number) - var $export = __webpack_require__(8); - var isInteger = __webpack_require__(95); - var abs = Math.abs; - - $export($export.S, 'Number', { - isSafeInteger: function isSafeInteger(number) { - return isInteger(number) && abs(number) <= 0x1fffffffffffff; - } - }); - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.6 Number.MAX_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.10 Number.MIN_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseFloat = __webpack_require__(85); - // 20.1.2.12 Number.parseFloat(string) - $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseInt = __webpack_require__(81); - // 20.1.2.13 Number.parseInt(string, radix) - $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.3 Math.acosh(x) - var $export = __webpack_require__(8); - var log1p = __webpack_require__(103); - var sqrt = Math.sqrt; - var $acosh = Math.acosh; - - $export($export.S + $export.F * !($acosh - // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 - && Math.floor($acosh(Number.MAX_VALUE)) == 710 - // Tor Browser bug: Math.acosh(Infinity) -> NaN - && $acosh(Infinity) == Infinity - ), 'Math', { - acosh: function acosh(x) { - return (x = +x) < 1 ? NaN : x > 94906265.62425156 - ? Math.log(x) + Math.LN2 - : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); - } - }); - - -/***/ }), -/* 103 */ -/***/ (function(module, exports) { - - // 20.2.2.20 Math.log1p(x) - module.exports = Math.log1p || function log1p(x) { - return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); - }; - - -/***/ }), -/* 104 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.5 Math.asinh(x) - var $export = __webpack_require__(8); - var $asinh = Math.asinh; - - function asinh(x) { - return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); - } - - // Tor Browser bug: Math.asinh(0) -> -0 - $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); - - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.7 Math.atanh(x) - var $export = __webpack_require__(8); - var $atanh = Math.atanh; - - // Tor Browser bug: Math.atanh(-0) -> 0 - $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { - atanh: function atanh(x) { - return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; - } - }); - - -/***/ }), -/* 106 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.9 Math.cbrt(x) - var $export = __webpack_require__(8); - var sign = __webpack_require__(107); - - $export($export.S, 'Math', { - cbrt: function cbrt(x) { - return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); - } - }); - - -/***/ }), -/* 107 */ -/***/ (function(module, exports) { - - // 20.2.2.28 Math.sign(x) - module.exports = Math.sign || function sign(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; - }; - - -/***/ }), -/* 108 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.11 Math.clz32(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clz32: function clz32(x) { - return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; - } - }); - - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.12 Math.cosh(x) - var $export = __webpack_require__(8); - var exp = Math.exp; - - $export($export.S, 'Math', { - cosh: function cosh(x) { - return (exp(x = +x) + exp(-x)) / 2; - } - }); - - -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.14 Math.expm1(x) - var $export = __webpack_require__(8); - var $expm1 = __webpack_require__(111); - - $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); - - -/***/ }), -/* 111 */ -/***/ (function(module, exports) { - - // 20.2.2.14 Math.expm1(x) - var $expm1 = Math.expm1; - module.exports = (!$expm1 - // Old FF bug - || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 - // Tor Browser bug - || $expm1(-2e-17) != -2e-17 - ) ? function expm1(x) { - return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; - } : $expm1; - - -/***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { fround: __webpack_require__(113) }); - - -/***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var sign = __webpack_require__(107); - var pow = Math.pow; - var EPSILON = pow(2, -52); - var EPSILON32 = pow(2, -23); - var MAX32 = pow(2, 127) * (2 - EPSILON32); - var MIN32 = pow(2, -126); - - var roundTiesToEven = function (n) { - return n + 1 / EPSILON - 1 / EPSILON; - }; - - module.exports = Math.fround || function fround(x) { - var $abs = Math.abs(x); - var $sign = sign(x); - var a, result; - if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; - a = (1 + EPSILON32 / EPSILON) * $abs; - result = a - (a - $abs); - // eslint-disable-next-line no-self-compare - if (result > MAX32 || result != result) return $sign * Infinity; - return $sign * result; - }; - - -/***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) - var $export = __webpack_require__(8); - var abs = Math.abs; - - $export($export.S, 'Math', { - hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars - var sum = 0; - var i = 0; - var aLen = arguments.length; - var larg = 0; - var arg, div; - while (i < aLen) { - arg = abs(arguments[i++]); - if (larg < arg) { - div = larg / arg; - sum = sum * div * div + 1; - larg = arg; - } else if (arg > 0) { - div = arg / larg; - sum += div * div; - } else sum += arg; - } - return larg === Infinity ? Infinity : larg * Math.sqrt(sum); - } - }); - - -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.18 Math.imul(x, y) - var $export = __webpack_require__(8); - var $imul = Math.imul; - - // some WebKit versions fails with big numbers, some has wrong arity - $export($export.S + $export.F * __webpack_require__(7)(function () { - return $imul(0xffffffff, 5) != -5 || $imul.length != 2; - }), 'Math', { - imul: function imul(x, y) { - var UINT16 = 0xffff; - var xn = +x; - var yn = +y; - var xl = UINT16 & xn; - var yl = UINT16 & yn; - return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); - } - }); - - -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.21 Math.log10(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log10: function log10(x) { - return Math.log(x) * Math.LOG10E; - } - }); - - -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.20 Math.log1p(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { log1p: __webpack_require__(103) }); - - -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.22 Math.log2(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log2: function log2(x) { - return Math.log(x) / Math.LN2; - } - }); - - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.28 Math.sign(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { sign: __webpack_require__(107) }); - - -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.30 Math.sinh(x) - var $export = __webpack_require__(8); - var expm1 = __webpack_require__(111); - var exp = Math.exp; - - // V8 near Chromium 38 has a problem with very small numbers - $export($export.S + $export.F * __webpack_require__(7)(function () { - return !Math.sinh(-2e-17) != -2e-17; - }), 'Math', { - sinh: function sinh(x) { - return Math.abs(x = +x) < 1 - ? (expm1(x) - expm1(-x)) / 2 - : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); - } - }); - - -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.33 Math.tanh(x) - var $export = __webpack_require__(8); - var expm1 = __webpack_require__(111); - var exp = Math.exp; - - $export($export.S, 'Math', { - tanh: function tanh(x) { - var a = expm1(x = +x); - var b = expm1(-x); - return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); - } - }); - - -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.34 Math.trunc(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - trunc: function trunc(it) { - return (it > 0 ? Math.floor : Math.ceil)(it); - } - }); - - -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var toAbsoluteIndex = __webpack_require__(39); - var fromCharCode = String.fromCharCode; - var $fromCodePoint = String.fromCodePoint; - - // length should be 1, old FF problem - $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { - // 21.1.2.2 String.fromCodePoint(...codePoints) - fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars - var res = []; - var aLen = arguments.length; - var i = 0; - var code; - while (aLen > i) { - code = +arguments[i++]; - if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point'); - res.push(code < 0x10000 - ? fromCharCode(code) - : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) - ); - } return res.join(''); - } - }); - - -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(32); - var toLength = __webpack_require__(37); - - $export($export.S, 'String', { - // 21.1.2.4 String.raw(callSite, ...substitutions) - raw: function raw(callSite) { - var tpl = toIObject(callSite.raw); - var len = toLength(tpl.length); - var aLen = arguments.length; - var res = []; - var i = 0; - while (len > i) { - res.push(String(tpl[i++])); - if (i < aLen) res.push(String(arguments[i])); - } return res.join(''); - } - }); - - -/***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.1.3.25 String.prototype.trim() - __webpack_require__(82)('trim', function ($trim) { - return function trim() { - return $trim(this, 3); - }; - }); - - -/***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $at = __webpack_require__(127)(true); - - // 21.1.3.27 String.prototype[@@iterator]() - __webpack_require__(128)(String, 'String', function (iterated) { - this._t = String(iterated); // target - this._i = 0; // next index - // 21.1.5.2.1 %StringIteratorPrototype%.next() - }, function () { - var O = this._t; - var index = this._i; - var point; - if (index >= O.length) return { value: undefined, done: true }; - point = $at(O, index); - this._i += point.length; - return { value: point, done: false }; - }); - - -/***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(38); - var defined = __webpack_require__(35); - // true -> String#at - // false -> String#codePointAt - module.exports = function (TO_STRING) { - return function (that, pos) { - var s = String(defined(that)); - var i = toInteger(pos); - var l = s.length; - var a, b; - if (i < 0 || i >= l) return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; - }; - - -/***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(24); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var hide = __webpack_require__(10); - var Iterators = __webpack_require__(129); - var $iterCreate = __webpack_require__(130); - var setToStringTag = __webpack_require__(25); - var getPrototypeOf = __webpack_require__(58); - var ITERATOR = __webpack_require__(26)('iterator'); - var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` - var FF_ITERATOR = '@@iterator'; - var KEYS = 'keys'; - var VALUES = 'values'; - - var returnThis = function () { return this; }; - - module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { - $iterCreate(Constructor, NAME, next); - var getMethod = function (kind) { - if (!BUGGY && kind in proto) return proto[kind]; - switch (kind) { - case KEYS: return function keys() { return new Constructor(this, kind); }; - case VALUES: return function values() { return new Constructor(this, kind); }; - } return function entries() { return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator'; - var DEF_VALUES = DEFAULT == VALUES; - var VALUES_BUG = false; - var proto = Base.prototype; - var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; - var $default = $native || getMethod(DEFAULT); - var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; - var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; - var methods, key, IteratorPrototype; - // Fix native - if ($anyNative) { - IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); - if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if (DEF_VALUES && $native && $native.name !== VALUES) { - VALUES_BUG = true; - $default = function values() { return $native.call(this); }; - } - // Define iterator - if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if (DEFAULT) { - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if (FORCED) for (key in methods) { - if (!(key in proto)) redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; - }; - - -/***/ }), -/* 129 */ -/***/ (function(module, exports) { - - module.exports = {}; - - -/***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var create = __webpack_require__(45); - var descriptor = __webpack_require__(17); - var setToStringTag = __webpack_require__(25); - var IteratorPrototype = {}; - - // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() - __webpack_require__(10)(IteratorPrototype, __webpack_require__(26)('iterator'), function () { return this; }); - - module.exports = function (Constructor, NAME, next) { - Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); - setToStringTag(Constructor, NAME + ' Iterator'); - }; - - -/***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $at = __webpack_require__(127)(false); - $export($export.P, 'String', { - // 21.1.3.3 String.prototype.codePointAt(pos) - codePointAt: function codePointAt(pos) { - return $at(this, pos); - } - }); - - -/***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) - 'use strict'; - var $export = __webpack_require__(8); - var toLength = __webpack_require__(37); - var context = __webpack_require__(133); - var ENDS_WITH = 'endsWith'; - var $endsWith = ''[ENDS_WITH]; - - $export($export.P + $export.F * __webpack_require__(135)(ENDS_WITH), 'String', { - endsWith: function endsWith(searchString /* , endPosition = @length */) { - var that = context(this, searchString, ENDS_WITH); - var endPosition = arguments.length > 1 ? arguments[1] : undefined; - var len = toLength(that.length); - var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); - var search = String(searchString); - return $endsWith - ? $endsWith.call(that, search, end) - : that.slice(end - search.length, end) === search; - } - }); - - -/***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { - - // helper for String#{startsWith, endsWith, includes} - var isRegExp = __webpack_require__(134); - var defined = __webpack_require__(35); - - module.exports = function (that, searchString, NAME) { - if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!"); - return String(defined(that)); - }; - - -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.2.8 IsRegExp(argument) - var isObject = __webpack_require__(13); - var cof = __webpack_require__(34); - var MATCH = __webpack_require__(26)('match'); - module.exports = function (it) { - var isRegExp; - return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); - }; - - -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - - var MATCH = __webpack_require__(26)('match'); - module.exports = function (KEY) { - var re = /./; - try { - '/./'[KEY](re); - } catch (e) { - try { - re[MATCH] = false; - return !'/./'[KEY](re); - } catch (f) { /* empty */ } - } return true; - }; - - -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.7 String.prototype.includes(searchString, position = 0) - 'use strict'; - var $export = __webpack_require__(8); - var context = __webpack_require__(133); - var INCLUDES = 'includes'; - - $export($export.P + $export.F * __webpack_require__(135)(INCLUDES), 'String', { - includes: function includes(searchString /* , position = 0 */) { - return !!~context(this, searchString, INCLUDES) - .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - - $export($export.P, 'String', { - // 21.1.3.13 String.prototype.repeat(count) - repeat: __webpack_require__(90) - }); - - -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) - 'use strict'; - var $export = __webpack_require__(8); - var toLength = __webpack_require__(37); - var context = __webpack_require__(133); - var STARTS_WITH = 'startsWith'; - var $startsWith = ''[STARTS_WITH]; - - $export($export.P + $export.F * __webpack_require__(135)(STARTS_WITH), 'String', { - startsWith: function startsWith(searchString /* , position = 0 */) { - var that = context(this, searchString, STARTS_WITH); - var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)); - var search = String(searchString); - return $startsWith - ? $startsWith.call(that, search, index) - : that.slice(index, index + search.length) === search; - } - }); - - -/***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.2 String.prototype.anchor(name) - __webpack_require__(140)('anchor', function (createHTML) { - return function anchor(name) { - return createHTML(this, 'a', 'name', name); - }; - }); - - -/***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var fails = __webpack_require__(7); - var defined = __webpack_require__(35); - var quot = /"/g; - // B.2.3.2.1 CreateHTML(string, tag, attribute, value) - var createHTML = function (string, tag, attribute, value) { - var S = String(defined(string)); - var p1 = '<' + tag; - if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; - return p1 + '>' + S + '</' + tag + '>'; - }; - module.exports = function (NAME, exec) { - var O = {}; - O[NAME] = exec(createHTML); - $export($export.P + $export.F * fails(function () { - var test = ''[NAME]('"'); - return test !== test.toLowerCase() || test.split('"').length > 3; - }), 'String', O); - }; - - -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.3 String.prototype.big() - __webpack_require__(140)('big', function (createHTML) { - return function big() { - return createHTML(this, 'big', '', ''); - }; - }); - - -/***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.4 String.prototype.blink() - __webpack_require__(140)('blink', function (createHTML) { - return function blink() { - return createHTML(this, 'blink', '', ''); - }; - }); - - -/***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.5 String.prototype.bold() - __webpack_require__(140)('bold', function (createHTML) { - return function bold() { - return createHTML(this, 'b', '', ''); - }; - }); - - -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.6 String.prototype.fixed() - __webpack_require__(140)('fixed', function (createHTML) { - return function fixed() { - return createHTML(this, 'tt', '', ''); - }; - }); - - -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.7 String.prototype.fontcolor(color) - __webpack_require__(140)('fontcolor', function (createHTML) { - return function fontcolor(color) { - return createHTML(this, 'font', 'color', color); - }; - }); - - -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.8 String.prototype.fontsize(size) - __webpack_require__(140)('fontsize', function (createHTML) { - return function fontsize(size) { - return createHTML(this, 'font', 'size', size); - }; - }); - - -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.9 String.prototype.italics() - __webpack_require__(140)('italics', function (createHTML) { - return function italics() { - return createHTML(this, 'i', '', ''); - }; - }); - - -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.10 String.prototype.link(url) - __webpack_require__(140)('link', function (createHTML) { - return function link(url) { - return createHTML(this, 'a', 'href', url); - }; - }); - - -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.11 String.prototype.small() - __webpack_require__(140)('small', function (createHTML) { - return function small() { - return createHTML(this, 'small', '', ''); - }; - }); - - -/***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.12 String.prototype.strike() - __webpack_require__(140)('strike', function (createHTML) { - return function strike() { - return createHTML(this, 'strike', '', ''); - }; - }); - - -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.13 String.prototype.sub() - __webpack_require__(140)('sub', function (createHTML) { - return function sub() { - return createHTML(this, 'sub', '', ''); - }; - }); - - -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.14 String.prototype.sup() - __webpack_require__(140)('sup', function (createHTML) { - return function sup() { - return createHTML(this, 'sup', '', ''); - }; - }); - - -/***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.3.3.1 / 15.9.4.4 Date.now() - var $export = __webpack_require__(8); - - $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); - - -/***/ }), -/* 154 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var toPrimitive = __webpack_require__(16); - - $export($export.P + $export.F * __webpack_require__(7)(function () { - return new Date(NaN).toJSON() !== null - || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; - }), 'Date', { - // eslint-disable-next-line no-unused-vars - toJSON: function toJSON(key) { - var O = toObject(this); - var pv = toPrimitive(O); - return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); - } - }); - - -/***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var $export = __webpack_require__(8); - var toISOString = __webpack_require__(156); - - // PhantomJS / old WebKit has a broken implementations - $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', { - toISOString: toISOString - }); - - -/***/ }), -/* 156 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var fails = __webpack_require__(7); - var getTime = Date.prototype.getTime; - var $toISOString = Date.prototype.toISOString; - - var lz = function (num) { - return num > 9 ? num : '0' + num; - }; - - // PhantomJS / old WebKit has a broken implementations - module.exports = (fails(function () { - return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; - }) || !fails(function () { - $toISOString.call(new Date(NaN)); - })) ? function toISOString() { - if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); - var d = this; - var y = d.getUTCFullYear(); - var m = d.getUTCMilliseconds(); - var s = y < 0 ? '-' : y > 9999 ? '+' : ''; - return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + - '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + - 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + - ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; - } : $toISOString; - - -/***/ }), -/* 157 */ -/***/ (function(module, exports, __webpack_require__) { - - var DateProto = Date.prototype; - var INVALID_DATE = 'Invalid Date'; - var TO_STRING = 'toString'; - var $toString = DateProto[TO_STRING]; - var getTime = DateProto.getTime; - if (new Date(NaN) + '' != INVALID_DATE) { - __webpack_require__(18)(DateProto, TO_STRING, function toString() { - var value = getTime.call(this); - // eslint-disable-next-line no-self-compare - return value === value ? $toString.call(this) : INVALID_DATE; - }); - } - - -/***/ }), -/* 158 */ -/***/ (function(module, exports, __webpack_require__) { - - var TO_PRIMITIVE = __webpack_require__(26)('toPrimitive'); - var proto = Date.prototype; - - if (!(TO_PRIMITIVE in proto)) __webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(159)); - - -/***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var anObject = __webpack_require__(12); - var toPrimitive = __webpack_require__(16); - var NUMBER = 'number'; - - module.exports = function (hint) { - if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint'); - return toPrimitive(anObject(this), hint != NUMBER); - }; - - -/***/ }), -/* 160 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) - var $export = __webpack_require__(8); - - $export($export.S, 'Array', { isArray: __webpack_require__(44) }); - - -/***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var ctx = __webpack_require__(20); - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var call = __webpack_require__(162); - var isArrayIter = __webpack_require__(163); - var toLength = __webpack_require__(37); - var createProperty = __webpack_require__(164); - var getIterFn = __webpack_require__(165); - - $export($export.S + $export.F * !__webpack_require__(166)(function (iter) { Array.from(iter); }), 'Array', { - // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) - from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { - var O = toObject(arrayLike); - var C = typeof this == 'function' ? this : Array; - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var index = 0; - var iterFn = getIterFn(O); - var length, result, step, iterator; - if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); - // if object isn't iterable or it's array with default iterator - use simple case - if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { - for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { - createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); - } - } else { - length = toLength(O.length); - for (result = new C(length); length > index; index++) { - createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); - } - } - result.length = index; - return result; - } - }); - - -/***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { - - // call something on iterator step with safe closing on error - var anObject = __webpack_require__(12); - module.exports = function (iterator, fn, value, entries) { - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch (e) { - var ret = iterator['return']; - if (ret !== undefined) anObject(ret.call(iterator)); - throw e; - } - }; - - -/***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { - - // check on default Array iterator - var Iterators = __webpack_require__(129); - var ITERATOR = __webpack_require__(26)('iterator'); - var ArrayProto = Array.prototype; - - module.exports = function (it) { - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); - }; - - -/***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $defineProperty = __webpack_require__(11); - var createDesc = __webpack_require__(17); - - module.exports = function (object, index, value) { - if (index in object) $defineProperty.f(object, index, createDesc(0, value)); - else object[index] = value; - }; - - -/***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { - - var classof = __webpack_require__(74); - var ITERATOR = __webpack_require__(26)('iterator'); - var Iterators = __webpack_require__(129); - module.exports = __webpack_require__(9).getIteratorMethod = function (it) { - if (it != undefined) return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; - }; - - -/***/ }), -/* 166 */ -/***/ (function(module, exports, __webpack_require__) { - - var ITERATOR = __webpack_require__(26)('iterator'); - var SAFE_CLOSING = false; - - try { - var riter = [7][ITERATOR](); - riter['return'] = function () { SAFE_CLOSING = true; }; - // eslint-disable-next-line no-throw-literal - Array.from(riter, function () { throw 2; }); - } catch (e) { /* empty */ } - - module.exports = function (exec, skipClosing) { - if (!skipClosing && !SAFE_CLOSING) return false; - var safe = false; - try { - var arr = [7]; - var iter = arr[ITERATOR](); - iter.next = function () { return { done: safe = true }; }; - arr[ITERATOR] = function () { return iter; }; - exec(arr); - } catch (e) { /* empty */ } - return safe; - }; - - -/***/ }), -/* 167 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var createProperty = __webpack_require__(164); - - // WebKit Array.of isn't generic - $export($export.S + $export.F * __webpack_require__(7)(function () { - function F() { /* empty */ } - return !(Array.of.call(F) instanceof F); - }), 'Array', { - // 22.1.2.3 Array.of( ...items) - of: function of(/* ...args */) { - var index = 0; - var aLen = arguments.length; - var result = new (typeof this == 'function' ? this : Array)(aLen); - while (aLen > index) createProperty(result, index, arguments[index++]); - result.length = aLen; - return result; - } - }); - - -/***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.13 Array.prototype.join(separator) - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(32); - var arrayJoin = [].join; - - // fallback for not array-like strings - $export($export.P + $export.F * (__webpack_require__(33) != Object || !__webpack_require__(169)(arrayJoin)), 'Array', { - join: function join(separator) { - return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); - } - }); - - -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var fails = __webpack_require__(7); - - module.exports = function (method, arg) { - return !!method && fails(function () { - // eslint-disable-next-line no-useless-call - arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null); - }); - }; - - -/***/ }), -/* 170 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var html = __webpack_require__(47); - var cof = __webpack_require__(34); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - var arraySlice = [].slice; - - // fallback for not array-like ES3 strings and DOM objects - $export($export.P + $export.F * __webpack_require__(7)(function () { - if (html) arraySlice.call(html); - }), 'Array', { - slice: function slice(begin, end) { - var len = toLength(this.length); - var klass = cof(this); - end = end === undefined ? len : end; - if (klass == 'Array') return arraySlice.call(this, begin, end); - var start = toAbsoluteIndex(begin, len); - var upTo = toAbsoluteIndex(end, len); - var size = toLength(upTo - start); - var cloned = new Array(size); - var i = 0; - for (; i < size; i++) cloned[i] = klass == 'String' - ? this.charAt(start + i) - : this[start + i]; - return cloned; - } - }); - - -/***/ }), -/* 171 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(21); - var toObject = __webpack_require__(57); - var fails = __webpack_require__(7); - var $sort = [].sort; - var test = [1, 2, 3]; - - $export($export.P + $export.F * (fails(function () { - // IE8- - test.sort(undefined); - }) || !fails(function () { - // V8 bug - test.sort(null); - // Old WebKit - }) || !__webpack_require__(169)($sort)), 'Array', { - // 22.1.3.25 Array.prototype.sort(comparefn) - sort: function sort(comparefn) { - return comparefn === undefined - ? $sort.call(toObject(this)) - : $sort.call(toObject(this), aFunction(comparefn)); - } - }); - - -/***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $forEach = __webpack_require__(173)(0); - var STRICT = __webpack_require__(169)([].forEach, true); - - $export($export.P + $export.F * !STRICT, 'Array', { - // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) - forEach: function forEach(callbackfn /* , thisArg */) { - return $forEach(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 173 */ -/***/ (function(module, exports, __webpack_require__) { - - // 0 -> Array#forEach - // 1 -> Array#map - // 2 -> Array#filter - // 3 -> Array#some - // 4 -> Array#every - // 5 -> Array#find - // 6 -> Array#findIndex - var ctx = __webpack_require__(20); - var IObject = __webpack_require__(33); - var toObject = __webpack_require__(57); - var toLength = __webpack_require__(37); - var asc = __webpack_require__(174); - module.exports = function (TYPE, $create) { - var IS_MAP = TYPE == 1; - var IS_FILTER = TYPE == 2; - var IS_SOME = TYPE == 3; - var IS_EVERY = TYPE == 4; - var IS_FIND_INDEX = TYPE == 6; - var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; - var create = $create || asc; - return function ($this, callbackfn, that) { - var O = toObject($this); - var self = IObject(O); - var f = ctx(callbackfn, that, 3); - var length = toLength(self.length); - var index = 0; - var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; - var val, res; - for (;length > index; index++) if (NO_HOLES || index in self) { - val = self[index]; - res = f(val, index, O); - if (TYPE) { - if (IS_MAP) result[index] = res; // map - else if (res) switch (TYPE) { - case 3: return true; // some - case 5: return val; // find - case 6: return index; // findIndex - case 2: result.push(val); // filter - } else if (IS_EVERY) return false; // every - } - } - return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; - }; - }; - - -/***/ }), -/* 174 */ -/***/ (function(module, exports, __webpack_require__) { - - // 9.4.2.3 ArraySpeciesCreate(originalArray, length) - var speciesConstructor = __webpack_require__(175); - - module.exports = function (original, length) { - return new (speciesConstructor(original))(length); - }; - - -/***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var isArray = __webpack_require__(44); - var SPECIES = __webpack_require__(26)('species'); - - module.exports = function (original) { - var C; - if (isArray(original)) { - C = original.constructor; - // cross-realm fallback - if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; - if (isObject(C)) { - C = C[SPECIES]; - if (C === null) C = undefined; - } - } return C === undefined ? Array : C; - }; - - -/***/ }), -/* 176 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $map = __webpack_require__(173)(1); - - $export($export.P + $export.F * !__webpack_require__(169)([].map, true), 'Array', { - // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) - map: function map(callbackfn /* , thisArg */) { - return $map(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 177 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $filter = __webpack_require__(173)(2); - - $export($export.P + $export.F * !__webpack_require__(169)([].filter, true), 'Array', { - // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) - filter: function filter(callbackfn /* , thisArg */) { - return $filter(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 178 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $some = __webpack_require__(173)(3); - - $export($export.P + $export.F * !__webpack_require__(169)([].some, true), 'Array', { - // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) - some: function some(callbackfn /* , thisArg */) { - return $some(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 179 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $every = __webpack_require__(173)(4); - - $export($export.P + $export.F * !__webpack_require__(169)([].every, true), 'Array', { - // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) - every: function every(callbackfn /* , thisArg */) { - return $every(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 180 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $reduce = __webpack_require__(181); - - $export($export.P + $export.F * !__webpack_require__(169)([].reduce, true), 'Array', { - // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) - reduce: function reduce(callbackfn /* , initialValue */) { - return $reduce(this, callbackfn, arguments.length, arguments[1], false); - } - }); - - -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { - - var aFunction = __webpack_require__(21); - var toObject = __webpack_require__(57); - var IObject = __webpack_require__(33); - var toLength = __webpack_require__(37); - - module.exports = function (that, callbackfn, aLen, memo, isRight) { - aFunction(callbackfn); - var O = toObject(that); - var self = IObject(O); - var length = toLength(O.length); - var index = isRight ? length - 1 : 0; - var i = isRight ? -1 : 1; - if (aLen < 2) for (;;) { - if (index in self) { - memo = self[index]; - index += i; - break; - } - index += i; - if (isRight ? index < 0 : length <= index) { - throw TypeError('Reduce of empty array with no initial value'); - } - } - for (;isRight ? index >= 0 : length > index; index += i) if (index in self) { - memo = callbackfn(memo, self[index], index, O); - } - return memo; - }; - - -/***/ }), -/* 182 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $reduce = __webpack_require__(181); - - $export($export.P + $export.F * !__webpack_require__(169)([].reduceRight, true), 'Array', { - // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) - reduceRight: function reduceRight(callbackfn /* , initialValue */) { - return $reduce(this, callbackfn, arguments.length, arguments[1], true); - } - }); - - -/***/ }), -/* 183 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $indexOf = __webpack_require__(36)(false); - var $native = [].indexOf; - var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { - // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) - indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { - return NEGATIVE_ZERO - // convert -0 to +0 - ? $native.apply(this, arguments) || 0 - : $indexOf(this, searchElement, arguments[1]); - } - }); - - -/***/ }), -/* 184 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(32); - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - var $native = [].lastIndexOf; - var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { - // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) - lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { - // convert -0 to +0 - if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0; - var O = toIObject(this); - var length = toLength(O.length); - var index = length - 1; - if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1])); - if (index < 0) index = length + index; - for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0; - return -1; - } - }); - - -/***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', { copyWithin: __webpack_require__(186) }); - - __webpack_require__(187)('copyWithin'); - - -/***/ }), -/* 186 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - 'use strict'; - var toObject = __webpack_require__(57); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - - module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { - var O = toObject(this); - var len = toLength(O.length); - var to = toAbsoluteIndex(target, len); - var from = toAbsoluteIndex(start, len); - var end = arguments.length > 2 ? arguments[2] : undefined; - var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); - var inc = 1; - if (from < to && to < from + count) { - inc = -1; - from += count - 1; - to += count - 1; - } - while (count-- > 0) { - if (from in O) O[to] = O[from]; - else delete O[to]; - to += inc; - from += inc; - } return O; - }; - - -/***/ }), -/* 187 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.31 Array.prototype[@@unscopables] - var UNSCOPABLES = __webpack_require__(26)('unscopables'); - var ArrayProto = Array.prototype; - if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); - module.exports = function (key) { - ArrayProto[UNSCOPABLES][key] = true; - }; - - -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', { fill: __webpack_require__(189) }); - - __webpack_require__(187)('fill'); - - -/***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - 'use strict'; - var toObject = __webpack_require__(57); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - module.exports = function fill(value /* , start = 0, end = @length */) { - var O = toObject(this); - var length = toLength(O.length); - var aLen = arguments.length; - var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); - var end = aLen > 2 ? arguments[2] : undefined; - var endPos = end === undefined ? length : toAbsoluteIndex(end, length); - while (endPos > index) O[index++] = value; - return O; - }; - - -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) - var $export = __webpack_require__(8); - var $find = __webpack_require__(173)(5); - var KEY = 'find'; - var forced = true; - // Shouldn't skip holes - if (KEY in []) Array(1)[KEY](function () { forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - find: function find(callbackfn /* , that = undefined */) { - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(187)(KEY); - - -/***/ }), -/* 191 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) - var $export = __webpack_require__(8); - var $find = __webpack_require__(173)(6); - var KEY = 'findIndex'; - var forced = true; - // Shouldn't skip holes - if (KEY in []) Array(1)[KEY](function () { forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - findIndex: function findIndex(callbackfn /* , that = undefined */) { - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(187)(KEY); - - -/***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(193)('Array'); - - -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var dP = __webpack_require__(11); - var DESCRIPTORS = __webpack_require__(6); - var SPECIES = __webpack_require__(26)('species'); - - module.exports = function (KEY) { - var C = global[KEY]; - if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { - configurable: true, - get: function () { return this; } - }); - }; - - -/***/ }), -/* 194 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var addToUnscopables = __webpack_require__(187); - var step = __webpack_require__(195); - var Iterators = __webpack_require__(129); - var toIObject = __webpack_require__(32); - - // 22.1.3.4 Array.prototype.entries() - // 22.1.3.13 Array.prototype.keys() - // 22.1.3.29 Array.prototype.values() - // 22.1.3.30 Array.prototype[@@iterator]() - module.exports = __webpack_require__(128)(Array, 'Array', function (iterated, kind) { - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind - // 22.1.5.2.1 %ArrayIteratorPrototype%.next() - }, function () { - var O = this._t; - var kind = this._k; - var index = this._i++; - if (!O || index >= O.length) { - this._t = undefined; - return step(1); - } - if (kind == 'keys') return step(0, index); - if (kind == 'values') return step(0, O[index]); - return step(0, [index, O[index]]); - }, 'values'); - - // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) - Iterators.Arguments = Iterators.Array; - - addToUnscopables('keys'); - addToUnscopables('values'); - addToUnscopables('entries'); - - -/***/ }), -/* 195 */ -/***/ (function(module, exports) { - - module.exports = function (done, value) { - return { value: value, done: !!done }; - }; - - -/***/ }), -/* 196 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var inheritIfRequired = __webpack_require__(87); - var dP = __webpack_require__(11).f; - var gOPN = __webpack_require__(49).f; - var isRegExp = __webpack_require__(134); - var $flags = __webpack_require__(197); - var $RegExp = global.RegExp; - var Base = $RegExp; - var proto = $RegExp.prototype; - var re1 = /a/g; - var re2 = /a/g; - // "new" creates a new object, old webkit buggy here - var CORRECT_NEW = new $RegExp(re1) !== re1; - - if (__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function () { - re2[__webpack_require__(26)('match')] = false; - // RegExp constructor can alter flags and IsRegExp works correct with @@match - return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; - }))) { - $RegExp = function RegExp(p, f) { - var tiRE = this instanceof $RegExp; - var piRE = isRegExp(p); - var fiU = f === undefined; - return !tiRE && piRE && p.constructor === $RegExp && fiU ? p - : inheritIfRequired(CORRECT_NEW - ? new Base(piRE && !fiU ? p.source : p, f) - : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) - , tiRE ? this : proto, $RegExp); - }; - var proxy = function (key) { - key in $RegExp || dP($RegExp, key, { - configurable: true, - get: function () { return Base[key]; }, - set: function (it) { Base[key] = it; } - }); - }; - for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]); - proto.constructor = $RegExp; - $RegExp.prototype = proto; - __webpack_require__(18)(global, 'RegExp', $RegExp); - } - - __webpack_require__(193)('RegExp'); - - -/***/ }), -/* 197 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.2.5.3 get RegExp.prototype.flags - var anObject = __webpack_require__(12); - module.exports = function () { - var that = anObject(this); - var result = ''; - if (that.global) result += 'g'; - if (that.ignoreCase) result += 'i'; - if (that.multiline) result += 'm'; - if (that.unicode) result += 'u'; - if (that.sticky) result += 'y'; - return result; - }; - - -/***/ }), -/* 198 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - __webpack_require__(199); - var anObject = __webpack_require__(12); - var $flags = __webpack_require__(197); - var DESCRIPTORS = __webpack_require__(6); - var TO_STRING = 'toString'; - var $toString = /./[TO_STRING]; - - var define = function (fn) { - __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); - }; - - // 21.2.5.14 RegExp.prototype.toString() - if (__webpack_require__(7)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) { - define(function toString() { - var R = anObject(this); - return '/'.concat(R.source, '/', - 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); - }); - // FF44- RegExp#toString has a wrong name - } else if ($toString.name != TO_STRING) { - define(function toString() { - return $toString.call(this); - }); - } - - -/***/ }), -/* 199 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.2.5.3 get RegExp.prototype.flags() - if (__webpack_require__(6) && /./g.flags != 'g') __webpack_require__(11).f(RegExp.prototype, 'flags', { - configurable: true, - get: __webpack_require__(197) - }); - - -/***/ }), -/* 200 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@match logic - __webpack_require__(201)('match', 1, function (defined, MATCH, $match) { - // 21.1.3.11 String.prototype.match(regexp) - return [function match(regexp) { - 'use strict'; - var O = defined(this); - var fn = regexp == undefined ? undefined : regexp[MATCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); - }, $match]; - }); - - -/***/ }), -/* 201 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var hide = __webpack_require__(10); - var redefine = __webpack_require__(18); - var fails = __webpack_require__(7); - var defined = __webpack_require__(35); - var wks = __webpack_require__(26); - - module.exports = function (KEY, length, exec) { - var SYMBOL = wks(KEY); - var fns = exec(defined, SYMBOL, ''[KEY]); - var strfn = fns[0]; - var rxfn = fns[1]; - if (fails(function () { - var O = {}; - O[SYMBOL] = function () { return 7; }; - return ''[KEY](O) != 7; - })) { - redefine(String.prototype, KEY, strfn); - hide(RegExp.prototype, SYMBOL, length == 2 - // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) - // 21.2.5.11 RegExp.prototype[@@split](string, limit) - ? function (string, arg) { return rxfn.call(string, this, arg); } - // 21.2.5.6 RegExp.prototype[@@match](string) - // 21.2.5.9 RegExp.prototype[@@search](string) - : function (string) { return rxfn.call(string, this); } - ); - } - }; - - -/***/ }), -/* 202 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@replace logic - __webpack_require__(201)('replace', 2, function (defined, REPLACE, $replace) { - // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) - return [function replace(searchValue, replaceValue) { - 'use strict'; - var O = defined(this); - var fn = searchValue == undefined ? undefined : searchValue[REPLACE]; - return fn !== undefined - ? fn.call(searchValue, O, replaceValue) - : $replace.call(String(O), searchValue, replaceValue); - }, $replace]; - }); - - -/***/ }), -/* 203 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@search logic - __webpack_require__(201)('search', 1, function (defined, SEARCH, $search) { - // 21.1.3.15 String.prototype.search(regexp) - return [function search(regexp) { - 'use strict'; - var O = defined(this); - var fn = regexp == undefined ? undefined : regexp[SEARCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); - }, $search]; - }); - - -/***/ }), -/* 204 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@split logic - __webpack_require__(201)('split', 2, function (defined, SPLIT, $split) { - 'use strict'; - var isRegExp = __webpack_require__(134); - var _split = $split; - var $push = [].push; - var $SPLIT = 'split'; - var LENGTH = 'length'; - var LAST_INDEX = 'lastIndex'; - if ( - 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || - 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || - 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || - '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || - '.'[$SPLIT](/()()/)[LENGTH] > 1 || - ''[$SPLIT](/.?/)[LENGTH] - ) { - var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group - // based on es5-shim implementation, need to rework it - $split = function (separator, limit) { - var string = String(this); - if (separator === undefined && limit === 0) return []; - // If `separator` is not a regex, use native split - if (!isRegExp(separator)) return _split.call(string, separator, limit); - var output = []; - var flags = (separator.ignoreCase ? 'i' : '') + - (separator.multiline ? 'm' : '') + - (separator.unicode ? 'u' : '') + - (separator.sticky ? 'y' : ''); - var lastLastIndex = 0; - var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; - // Make `global` and avoid `lastIndex` issues by working with a copy - var separatorCopy = new RegExp(separator.source, flags + 'g'); - var separator2, match, lastIndex, lastLength, i; - // Doesn't need flags gy, but they don't hurt - if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); - while (match = separatorCopy.exec(string)) { - // `separatorCopy.lastIndex` is not reliable cross-browser - lastIndex = match.index + match[0][LENGTH]; - if (lastIndex > lastLastIndex) { - output.push(string.slice(lastLastIndex, match.index)); - // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG - // eslint-disable-next-line no-loop-func - if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () { - for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined; - }); - if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1)); - lastLength = match[0][LENGTH]; - lastLastIndex = lastIndex; - if (output[LENGTH] >= splitLimit) break; - } - if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop - } - if (lastLastIndex === string[LENGTH]) { - if (lastLength || !separatorCopy.test('')) output.push(''); - } else output.push(string.slice(lastLastIndex)); - return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; - }; - // Chakra, V8 - } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) { - $split = function (separator, limit) { - return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); - }; - } - // 21.1.3.17 String.prototype.split(separator, limit) - return [function split(separator, limit) { - var O = defined(this); - var fn = separator == undefined ? undefined : separator[SPLIT]; - return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); - }, $split]; - }); - - -/***/ }), -/* 205 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(24); - var global = __webpack_require__(4); - var ctx = __webpack_require__(20); - var classof = __webpack_require__(74); - var $export = __webpack_require__(8); - var isObject = __webpack_require__(13); - var aFunction = __webpack_require__(21); - var anInstance = __webpack_require__(206); - var forOf = __webpack_require__(207); - var speciesConstructor = __webpack_require__(208); - var task = __webpack_require__(209).set; - var microtask = __webpack_require__(210)(); - var newPromiseCapabilityModule = __webpack_require__(211); - var perform = __webpack_require__(212); - var userAgent = __webpack_require__(213); - var promiseResolve = __webpack_require__(214); - var PROMISE = 'Promise'; - var TypeError = global.TypeError; - var process = global.process; - var versions = process && process.versions; - var v8 = versions && versions.v8 || ''; - var $Promise = global[PROMISE]; - var isNode = classof(process) == 'process'; - var empty = function () { /* empty */ }; - var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; - var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; - - var USE_NATIVE = !!function () { - try { - // correct subclassing with @@species support - var promise = $Promise.resolve(1); - var FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function (exec) { - exec(empty, empty); - }; - // unhandled rejections tracking support, NodeJS Promise without it fails @@species test - return (isNode || typeof PromiseRejectionEvent == 'function') - && promise.then(empty) instanceof FakePromise - // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables - // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 - // we can't detect it synchronously, so just check versions - && v8.indexOf('6.6') !== 0 - && userAgent.indexOf('Chrome/66') === -1; - } catch (e) { /* empty */ } - }(); - - // helpers - var isThenable = function (it) { - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; - }; - var notify = function (promise, isReject) { - if (promise._n) return; - promise._n = true; - var chain = promise._c; - microtask(function () { - var value = promise._v; - var ok = promise._s == 1; - var i = 0; - var run = function (reaction) { - var handler = ok ? reaction.ok : reaction.fail; - var resolve = reaction.resolve; - var reject = reaction.reject; - var domain = reaction.domain; - var result, then, exited; - try { - if (handler) { - if (!ok) { - if (promise._h == 2) onHandleUnhandled(promise); - promise._h = 1; - } - if (handler === true) result = value; - else { - if (domain) domain.enter(); - result = handler(value); // may throw - if (domain) { - domain.exit(); - exited = true; - } - } - if (result === reaction.promise) { - reject(TypeError('Promise-chain cycle')); - } else if (then = isThenable(result)) { - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch (e) { - if (domain && !exited) domain.exit(); - reject(e); - } - }; - while (chain.length > i) run(chain[i++]); // variable length - can't use forEach - promise._c = []; - promise._n = false; - if (isReject && !promise._h) onUnhandled(promise); - }); - }; - var onUnhandled = function (promise) { - task.call(global, function () { - var value = promise._v; - var unhandled = isUnhandled(promise); - var result, handler, console; - if (unhandled) { - result = perform(function () { - if (isNode) { - process.emit('unhandledRejection', value, promise); - } else if (handler = global.onunhandledrejection) { - handler({ promise: promise, reason: value }); - } else if ((console = global.console) && console.error) { - console.error('Unhandled promise rejection', value); - } - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - promise._h = isNode || isUnhandled(promise) ? 2 : 1; - } promise._a = undefined; - if (unhandled && result.e) throw result.v; - }); - }; - var isUnhandled = function (promise) { - return promise._h !== 1 && (promise._a || promise._c).length === 0; - }; - var onHandleUnhandled = function (promise) { - task.call(global, function () { - var handler; - if (isNode) { - process.emit('rejectionHandled', promise); - } else if (handler = global.onrejectionhandled) { - handler({ promise: promise, reason: promise._v }); - } - }); - }; - var $reject = function (value) { - var promise = this; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - promise._v = value; - promise._s = 2; - if (!promise._a) promise._a = promise._c.slice(); - notify(promise, true); - }; - var $resolve = function (value) { - var promise = this; - var then; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - try { - if (promise === value) throw TypeError("Promise can't be resolved itself"); - if (then = isThenable(value)) { - microtask(function () { - var wrapper = { _w: promise, _d: false }; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch (e) { - $reject.call(wrapper, e); - } - }); - } else { - promise._v = value; - promise._s = 1; - notify(promise, false); - } - } catch (e) { - $reject.call({ _w: promise, _d: false }, e); // wrap - } - }; - - // constructor polyfill - if (!USE_NATIVE) { - // 25.4.3.1 Promise(executor) - $Promise = function Promise(executor) { - anInstance(this, $Promise, PROMISE, '_h'); - aFunction(executor); - Internal.call(this); - try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); - } catch (err) { - $reject.call(this, err); - } - }; - // eslint-disable-next-line no-unused-vars - Internal = function Promise(executor) { - this._c = []; // <- awaiting reactions - this._a = undefined; // <- checked in isUnhandled reactions - this._s = 0; // <- state - this._d = false; // <- done - this._v = undefined; // <- value - this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled - this._n = false; // <- notify - }; - Internal.prototype = __webpack_require__(215)($Promise.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected) { - var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = isNode ? process.domain : undefined; - this._c.push(reaction); - if (this._a) this._a.push(reaction); - if (this._s) notify(this, false); - return reaction.promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function (onRejected) { - return this.then(undefined, onRejected); - } - }); - OwnPromiseCapability = function () { - var promise = new Internal(); - this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); - }; - newPromiseCapabilityModule.f = newPromiseCapability = function (C) { - return C === $Promise || C === Wrapper - ? new OwnPromiseCapability(C) - : newGenericPromiseCapability(C); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); - __webpack_require__(25)($Promise, PROMISE); - __webpack_require__(193)(PROMISE); - Wrapper = __webpack_require__(9)[PROMISE]; - - // statics - $export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r) { - var capability = newPromiseCapability(this); - var $$reject = capability.reject; - $$reject(r); - return capability.promise; - } - }); - $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x) { - return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); - } - }); - $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(166)(function (iter) { - $Promise.all(iter)['catch'](empty); - })), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var resolve = capability.resolve; - var reject = capability.reject; - var result = perform(function () { - var values = []; - var index = 0; - var remaining = 1; - forOf(iterable, false, function (promise) { - var $index = index++; - var alreadyCalled = false; - values.push(undefined); - remaining++; - C.resolve(promise).then(function (value) { - if (alreadyCalled) return; - alreadyCalled = true; - values[$index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if (result.e) reject(result.v); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var reject = capability.reject; - var result = perform(function () { - forOf(iterable, false, function (promise) { - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if (result.e) reject(result.v); - return capability.promise; - } - }); - - -/***/ }), -/* 206 */ -/***/ (function(module, exports) { - - module.exports = function (it, Constructor, name, forbiddenField) { - if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { - throw TypeError(name + ': incorrect invocation!'); - } return it; - }; - - -/***/ }), -/* 207 */ -/***/ (function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(20); - var call = __webpack_require__(162); - var isArrayIter = __webpack_require__(163); - var anObject = __webpack_require__(12); - var toLength = __webpack_require__(37); - var getIterFn = __webpack_require__(165); - var BREAK = {}; - var RETURN = {}; - var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { - var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); - var f = ctx(fn, that, entries ? 2 : 1); - var index = 0; - var length, step, iterator, result; - if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { - result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - if (result === BREAK || result === RETURN) return result; - } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { - result = call(iterator, f, step.value, entries); - if (result === BREAK || result === RETURN) return result; - } - }; - exports.BREAK = BREAK; - exports.RETURN = RETURN; - - -/***/ }), -/* 208 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.3.20 SpeciesConstructor(O, defaultConstructor) - var anObject = __webpack_require__(12); - var aFunction = __webpack_require__(21); - var SPECIES = __webpack_require__(26)('species'); - module.exports = function (O, D) { - var C = anObject(O).constructor; - var S; - return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); - }; - - -/***/ }), -/* 209 */ -/***/ (function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(20); - var invoke = __webpack_require__(77); - var html = __webpack_require__(47); - var cel = __webpack_require__(15); - var global = __webpack_require__(4); - var process = global.process; - var setTask = global.setImmediate; - var clearTask = global.clearImmediate; - var MessageChannel = global.MessageChannel; - var Dispatch = global.Dispatch; - var counter = 0; - var queue = {}; - var ONREADYSTATECHANGE = 'onreadystatechange'; - var defer, channel, port; - var run = function () { - var id = +this; - // eslint-disable-next-line no-prototype-builtins - if (queue.hasOwnProperty(id)) { - var fn = queue[id]; - delete queue[id]; - fn(); - } - }; - var listener = function (event) { - run.call(event.data); - }; - // Node.js 0.9+ & IE10+ has setImmediate, otherwise: - if (!setTask || !clearTask) { - setTask = function setImmediate(fn) { - var args = []; - var i = 1; - while (arguments.length > i) args.push(arguments[i++]); - queue[++counter] = function () { - // eslint-disable-next-line no-new-func - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id) { - delete queue[id]; - }; - // Node.js 0.8- - if (__webpack_require__(34)(process) == 'process') { - defer = function (id) { - process.nextTick(ctx(run, id, 1)); - }; - // Sphere (JS game engine) Dispatch API - } else if (Dispatch && Dispatch.now) { - defer = function (id) { - Dispatch.now(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if (MessageChannel) { - channel = new MessageChannel(); - port = channel.port2; - channel.port1.onmessage = listener; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { - defer = function (id) { - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listener, false); - // IE8- - } else if (ONREADYSTATECHANGE in cel('script')) { - defer = function (id) { - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers - } else { - defer = function (id) { - setTimeout(ctx(run, id, 1), 0); - }; - } - } - module.exports = { - set: setTask, - clear: clearTask - }; - - -/***/ }), -/* 210 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var macrotask = __webpack_require__(209).set; - var Observer = global.MutationObserver || global.WebKitMutationObserver; - var process = global.process; - var Promise = global.Promise; - var isNode = __webpack_require__(34)(process) == 'process'; - - module.exports = function () { - var head, last, notify; - - var flush = function () { - var parent, fn; - if (isNode && (parent = process.domain)) parent.exit(); - while (head) { - fn = head.fn; - head = head.next; - try { - fn(); - } catch (e) { - if (head) notify(); - else last = undefined; - throw e; - } - } last = undefined; - if (parent) parent.enter(); - }; - - // Node.js - if (isNode) { - notify = function () { - process.nextTick(flush); - }; - // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 - } else if (Observer && !(global.navigator && global.navigator.standalone)) { - var toggle = true; - var node = document.createTextNode(''); - new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new - notify = function () { - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if (Promise && Promise.resolve) { - // Promise.resolve without an argument throws an error in LG WebOS 2 - var promise = Promise.resolve(undefined); - notify = function () { - promise.then(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function () { - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; - } - - return function (fn) { - var task = { fn: fn, next: undefined }; - if (last) last.next = task; - if (!head) { - head = task; - notify(); - } last = task; - }; - }; - - -/***/ }), -/* 211 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 25.4.1.5 NewPromiseCapability(C) - var aFunction = __webpack_require__(21); - - function PromiseCapability(C) { - var resolve, reject; - this.promise = new C(function ($$resolve, $$reject) { - if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction(resolve); - this.reject = aFunction(reject); - } - - module.exports.f = function (C) { - return new PromiseCapability(C); - }; - - -/***/ }), -/* 212 */ -/***/ (function(module, exports) { - - module.exports = function (exec) { - try { - return { e: false, v: exec() }; - } catch (e) { - return { e: true, v: e }; - } - }; - - -/***/ }), -/* 213 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var navigator = global.navigator; - - module.exports = navigator && navigator.userAgent || ''; - - -/***/ }), -/* 214 */ -/***/ (function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var newPromiseCapability = __webpack_require__(211); - - module.exports = function (C, x) { - anObject(C); - if (isObject(x) && x.constructor === C) return x; - var promiseCapability = newPromiseCapability.f(C); - var resolve = promiseCapability.resolve; - resolve(x); - return promiseCapability.promise; - }; - - -/***/ }), -/* 215 */ -/***/ (function(module, exports, __webpack_require__) { - - var redefine = __webpack_require__(18); - module.exports = function (target, src, safe) { - for (var key in src) redefine(target, key, src[key], safe); - return target; - }; - - -/***/ }), -/* 216 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(217); - var validate = __webpack_require__(218); - var MAP = 'Map'; - - // 23.1 Map Objects - module.exports = __webpack_require__(219)(MAP, function (get) { - return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.1.3.6 Map.prototype.get(key) - get: function get(key) { - var entry = strong.getEntry(validate(this, MAP), key); - return entry && entry.v; - }, - // 23.1.3.9 Map.prototype.set(key, value) - set: function set(key, value) { - return strong.def(validate(this, MAP), key === 0 ? 0 : key, value); - } - }, strong, true); - - -/***/ }), -/* 217 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var dP = __webpack_require__(11).f; - var create = __webpack_require__(45); - var redefineAll = __webpack_require__(215); - var ctx = __webpack_require__(20); - var anInstance = __webpack_require__(206); - var forOf = __webpack_require__(207); - var $iterDefine = __webpack_require__(128); - var step = __webpack_require__(195); - var setSpecies = __webpack_require__(193); - var DESCRIPTORS = __webpack_require__(6); - var fastKey = __webpack_require__(22).fastKey; - var validate = __webpack_require__(218); - var SIZE = DESCRIPTORS ? '_s' : 'size'; - - var getEntry = function (that, key) { - // fast case - var index = fastKey(key); - var entry; - if (index !== 'F') return that._i[index]; - // frozen object case - for (entry = that._f; entry; entry = entry.n) { - if (entry.k == key) return entry; - } - }; - - module.exports = { - getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, NAME, '_i'); - that._t = NAME; // collection type - that._i = create(null); // index - that._f = undefined; // first entry - that._l = undefined; // last entry - that[SIZE] = 0; // size - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.1.3.1 Map.prototype.clear() - // 23.2.3.2 Set.prototype.clear() - clear: function clear() { - for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { - entry.r = true; - if (entry.p) entry.p = entry.p.n = undefined; - delete data[entry.i]; - } - that._f = that._l = undefined; - that[SIZE] = 0; - }, - // 23.1.3.3 Map.prototype.delete(key) - // 23.2.3.4 Set.prototype.delete(value) - 'delete': function (key) { - var that = validate(this, NAME); - var entry = getEntry(that, key); - if (entry) { - var next = entry.n; - var prev = entry.p; - delete that._i[entry.i]; - entry.r = true; - if (prev) prev.n = next; - if (next) next.p = prev; - if (that._f == entry) that._f = next; - if (that._l == entry) that._l = prev; - that[SIZE]--; - } return !!entry; - }, - // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) - // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) - forEach: function forEach(callbackfn /* , that = undefined */) { - validate(this, NAME); - var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); - var entry; - while (entry = entry ? entry.n : this._f) { - f(entry.v, entry.k, this); - // revert to the last existing entry - while (entry && entry.r) entry = entry.p; - } - }, - // 23.1.3.7 Map.prototype.has(key) - // 23.2.3.7 Set.prototype.has(value) - has: function has(key) { - return !!getEntry(validate(this, NAME), key); - } - }); - if (DESCRIPTORS) dP(C.prototype, 'size', { - get: function () { - return validate(this, NAME)[SIZE]; - } - }); - return C; - }, - def: function (that, key, value) { - var entry = getEntry(that, key); - var prev, index; - // change existing entry - if (entry) { - entry.v = value; - // create new entry - } else { - that._l = entry = { - i: index = fastKey(key, true), // <- index - k: key, // <- key - v: value, // <- value - p: prev = that._l, // <- previous entry - n: undefined, // <- next entry - r: false // <- removed - }; - if (!that._f) that._f = entry; - if (prev) prev.n = entry; - that[SIZE]++; - // add to index - if (index !== 'F') that._i[index] = entry; - } return that; - }, - getEntry: getEntry, - setStrong: function (C, NAME, IS_MAP) { - // add .keys, .values, .entries, [@@iterator] - // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 - $iterDefine(C, NAME, function (iterated, kind) { - this._t = validate(iterated, NAME); // target - this._k = kind; // kind - this._l = undefined; // previous - }, function () { - var that = this; - var kind = that._k; - var entry = that._l; - // revert to the last existing entry - while (entry && entry.r) entry = entry.p; - // get next entry - if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { - // or finish the iteration - that._t = undefined; - return step(1); - } - // return step by kind - if (kind == 'keys') return step(0, entry.k); - if (kind == 'values') return step(0, entry.v); - return step(0, [entry.k, entry.v]); - }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); - - // add [@@species], 23.1.2.2, 23.2.2.2 - setSpecies(NAME); - } - }; - - -/***/ }), -/* 218 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function (it, TYPE) { - if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); - return it; - }; - - -/***/ }), -/* 219 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var redefineAll = __webpack_require__(215); - var meta = __webpack_require__(22); - var forOf = __webpack_require__(207); - var anInstance = __webpack_require__(206); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var $iterDetect = __webpack_require__(166); - var setToStringTag = __webpack_require__(25); - var inheritIfRequired = __webpack_require__(87); - - module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { - var Base = global[NAME]; - var C = Base; - var ADDER = IS_MAP ? 'set' : 'add'; - var proto = C && C.prototype; - var O = {}; - var fixMethod = function (KEY) { - var fn = proto[KEY]; - redefine(proto, KEY, - KEY == 'delete' ? function (a) { - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'has' ? function has(a) { - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'get' ? function get(a) { - return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; } - : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; } - ); - }; - if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { - new C().entries().next(); - }))) { - // create collection constructor - C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); - redefineAll(C.prototype, methods); - meta.NEED = true; - } else { - var instance = new C(); - // early implementations not supports chaining - var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; - // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false - var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); - // most early implementations doesn't supports iterables, most modern - not close it correctly - var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new - // for early implementations -0 and +0 not the same - var BUGGY_ZERO = !IS_WEAK && fails(function () { - // V8 ~ Chromium 42- fails only with 5+ elements - var $instance = new C(); - var index = 5; - while (index--) $instance[ADDER](index, index); - return !$instance.has(-0); - }); - if (!ACCEPT_ITERABLES) { - C = wrapper(function (target, iterable) { - anInstance(target, C, NAME); - var that = inheritIfRequired(new Base(), target, C); - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - return that; - }); - C.prototype = proto; - proto.constructor = C; - } - if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { - fixMethod('delete'); - fixMethod('has'); - IS_MAP && fixMethod('get'); - } - if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); - // weak collections should not contains .clear method - if (IS_WEAK && proto.clear) delete proto.clear; - } - - setToStringTag(C, NAME); - - O[NAME] = C; - $export($export.G + $export.W + $export.F * (C != Base), O); - - if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); - - return C; - }; - - -/***/ }), -/* 220 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(217); - var validate = __webpack_require__(218); - var SET = 'Set'; - - // 23.2 Set Objects - module.exports = __webpack_require__(219)(SET, function (get) { - return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.2.3.1 Set.prototype.add(value) - add: function add(value) { - return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value); - } - }, strong); - - -/***/ }), -/* 221 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var each = __webpack_require__(173)(0); - var redefine = __webpack_require__(18); - var meta = __webpack_require__(22); - var assign = __webpack_require__(68); - var weak = __webpack_require__(222); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var validate = __webpack_require__(218); - var WEAK_MAP = 'WeakMap'; - var getWeak = meta.getWeak; - var isExtensible = Object.isExtensible; - var uncaughtFrozenStore = weak.ufstore; - var tmp = {}; - var InternalMap; - - var wrapper = function (get) { - return function WeakMap() { - return get(this, arguments.length > 0 ? arguments[0] : undefined); - }; - }; - - var methods = { - // 23.3.3.3 WeakMap.prototype.get(key) - get: function get(key) { - if (isObject(key)) { - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key); - return data ? data[this._i] : undefined; - } - }, - // 23.3.3.5 WeakMap.prototype.set(key, value) - set: function set(key, value) { - return weak.def(validate(this, WEAK_MAP), key, value); - } - }; - - // 23.3 WeakMap Objects - var $WeakMap = module.exports = __webpack_require__(219)(WEAK_MAP, wrapper, methods, weak, true, true); - - // IE11 WeakMap frozen keys fix - if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) { - InternalMap = weak.getConstructor(wrapper, WEAK_MAP); - assign(InternalMap.prototype, methods); - meta.NEED = true; - each(['delete', 'has', 'get', 'set'], function (key) { - var proto = $WeakMap.prototype; - var method = proto[key]; - redefine(proto, key, function (a, b) { - // store frozen objects on internal weakmap shim - if (isObject(a) && !isExtensible(a)) { - if (!this._f) this._f = new InternalMap(); - var result = this._f[key](a, b); - return key == 'set' ? this : result; - // store all the rest on native weakmap - } return method.call(this, a, b); - }); - }); - } - - -/***/ }), -/* 222 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var redefineAll = __webpack_require__(215); - var getWeak = __webpack_require__(22).getWeak; - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var anInstance = __webpack_require__(206); - var forOf = __webpack_require__(207); - var createArrayMethod = __webpack_require__(173); - var $has = __webpack_require__(5); - var validate = __webpack_require__(218); - var arrayFind = createArrayMethod(5); - var arrayFindIndex = createArrayMethod(6); - var id = 0; - - // fallback for uncaught frozen keys - var uncaughtFrozenStore = function (that) { - return that._l || (that._l = new UncaughtFrozenStore()); - }; - var UncaughtFrozenStore = function () { - this.a = []; - }; - var findUncaughtFrozen = function (store, key) { - return arrayFind(store.a, function (it) { - return it[0] === key; - }); - }; - UncaughtFrozenStore.prototype = { - get: function (key) { - var entry = findUncaughtFrozen(this, key); - if (entry) return entry[1]; - }, - has: function (key) { - return !!findUncaughtFrozen(this, key); - }, - set: function (key, value) { - var entry = findUncaughtFrozen(this, key); - if (entry) entry[1] = value; - else this.a.push([key, value]); - }, - 'delete': function (key) { - var index = arrayFindIndex(this.a, function (it) { - return it[0] === key; - }); - if (~index) this.a.splice(index, 1); - return !!~index; - } - }; - - module.exports = { - getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, NAME, '_i'); - that._t = NAME; // collection type - that._i = id++; // collection id - that._l = undefined; // leak store for uncaught frozen objects - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.3.3.2 WeakMap.prototype.delete(key) - // 23.4.3.3 WeakSet.prototype.delete(value) - 'delete': function (key) { - if (!isObject(key)) return false; - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key); - return data && $has(data, this._i) && delete data[this._i]; - }, - // 23.3.3.4 WeakMap.prototype.has(key) - // 23.4.3.4 WeakSet.prototype.has(value) - has: function has(key) { - if (!isObject(key)) return false; - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key); - return data && $has(data, this._i); - } - }); - return C; - }, - def: function (that, key, value) { - var data = getWeak(anObject(key), true); - if (data === true) uncaughtFrozenStore(that).set(key, value); - else data[that._i] = value; - return that; - }, - ufstore: uncaughtFrozenStore - }; - - -/***/ }), -/* 223 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var weak = __webpack_require__(222); - var validate = __webpack_require__(218); - var WEAK_SET = 'WeakSet'; - - // 23.4 WeakSet Objects - __webpack_require__(219)(WEAK_SET, function (get) { - return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.4.3.1 WeakSet.prototype.add(value) - add: function add(value) { - return weak.def(validate(this, WEAK_SET), value, true); - } - }, weak, false, true); - - -/***/ }), -/* 224 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $typed = __webpack_require__(225); - var buffer = __webpack_require__(226); - var anObject = __webpack_require__(12); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - var isObject = __webpack_require__(13); - var ArrayBuffer = __webpack_require__(4).ArrayBuffer; - var speciesConstructor = __webpack_require__(208); - var $ArrayBuffer = buffer.ArrayBuffer; - var $DataView = buffer.DataView; - var $isView = $typed.ABV && ArrayBuffer.isView; - var $slice = $ArrayBuffer.prototype.slice; - var VIEW = $typed.VIEW; - var ARRAY_BUFFER = 'ArrayBuffer'; - - $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer }); - - $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { - // 24.1.3.1 ArrayBuffer.isView(arg) - isView: function isView(it) { - return $isView && $isView(it) || isObject(it) && VIEW in it; - } - }); - - $export($export.P + $export.U + $export.F * __webpack_require__(7)(function () { - return !new $ArrayBuffer(2).slice(1, undefined).byteLength; - }), ARRAY_BUFFER, { - // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) - slice: function slice(start, end) { - if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix - var len = anObject(this).byteLength; - var first = toAbsoluteIndex(start, len); - var fin = toAbsoluteIndex(end === undefined ? len : end, len); - var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first)); - var viewS = new $DataView(this); - var viewT = new $DataView(result); - var index = 0; - while (first < fin) { - viewT.setUint8(index++, viewS.getUint8(first++)); - } return result; - } - }); - - __webpack_require__(193)(ARRAY_BUFFER); - - -/***/ }), -/* 225 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var uid = __webpack_require__(19); - var TYPED = uid('typed_array'); - var VIEW = uid('view'); - var ABV = !!(global.ArrayBuffer && global.DataView); - var CONSTR = ABV; - var i = 0; - var l = 9; - var Typed; - - var TypedArrayConstructors = ( - 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' - ).split(','); - - while (i < l) { - if (Typed = global[TypedArrayConstructors[i++]]) { - hide(Typed.prototype, TYPED, true); - hide(Typed.prototype, VIEW, true); - } else CONSTR = false; - } - - module.exports = { - ABV: ABV, - CONSTR: CONSTR, - TYPED: TYPED, - VIEW: VIEW - }; - - -/***/ }), -/* 226 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var DESCRIPTORS = __webpack_require__(6); - var LIBRARY = __webpack_require__(24); - var $typed = __webpack_require__(225); - var hide = __webpack_require__(10); - var redefineAll = __webpack_require__(215); - var fails = __webpack_require__(7); - var anInstance = __webpack_require__(206); - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - var toIndex = __webpack_require__(227); - var gOPN = __webpack_require__(49).f; - var dP = __webpack_require__(11).f; - var arrayFill = __webpack_require__(189); - var setToStringTag = __webpack_require__(25); - var ARRAY_BUFFER = 'ArrayBuffer'; - var DATA_VIEW = 'DataView'; - var PROTOTYPE = 'prototype'; - var WRONG_LENGTH = 'Wrong length!'; - var WRONG_INDEX = 'Wrong index!'; - var $ArrayBuffer = global[ARRAY_BUFFER]; - var $DataView = global[DATA_VIEW]; - var Math = global.Math; - var RangeError = global.RangeError; - // eslint-disable-next-line no-shadow-restricted-names - var Infinity = global.Infinity; - var BaseBuffer = $ArrayBuffer; - var abs = Math.abs; - var pow = Math.pow; - var floor = Math.floor; - var log = Math.log; - var LN2 = Math.LN2; - var BUFFER = 'buffer'; - var BYTE_LENGTH = 'byteLength'; - var BYTE_OFFSET = 'byteOffset'; - var $BUFFER = DESCRIPTORS ? '_b' : BUFFER; - var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH; - var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; - - // IEEE754 conversions based on https://github.com/feross/ieee754 - function packIEEE754(value, mLen, nBytes) { - var buffer = new Array(nBytes); - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0; - var i = 0; - var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - var e, m, c; - value = abs(value); - // eslint-disable-next-line no-self-compare - if (value != value || value === Infinity) { - // eslint-disable-next-line no-self-compare - m = value != value ? 1 : 0; - e = eMax; - } else { - e = floor(log(value) / LN2); - if (value * (c = pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * 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) * pow(2, mLen); - e = e + eBias; - } else { - m = value * pow(2, eBias - 1) * pow(2, mLen); - e = 0; - } - } - for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); - buffer[--i] |= s * 128; - return buffer; - } - function unpackIEEE754(buffer, mLen, nBytes) { - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = eLen - 7; - var i = nBytes - 1; - var s = buffer[i--]; - var e = s & 127; - var m; - s >>= 7; - for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : s ? -Infinity : Infinity; - } else { - m = m + pow(2, mLen); - e = e - eBias; - } return (s ? -1 : 1) * m * pow(2, e - mLen); - } - - function unpackI32(bytes) { - return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; - } - function packI8(it) { - return [it & 0xff]; - } - function packI16(it) { - return [it & 0xff, it >> 8 & 0xff]; - } - function packI32(it) { - return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; - } - function packF64(it) { - return packIEEE754(it, 52, 8); - } - function packF32(it) { - return packIEEE754(it, 23, 4); - } - - function addGetter(C, key, internal) { - dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } }); - } - - function get(view, bytes, index, isLittleEndian) { - var numIndex = +index; - var intIndex = toIndex(numIndex); - if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b; - var start = intIndex + view[$OFFSET]; - var pack = store.slice(start, start + bytes); - return isLittleEndian ? pack : pack.reverse(); - } - function set(view, bytes, index, conversion, value, isLittleEndian) { - var numIndex = +index; - var intIndex = toIndex(numIndex); - if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b; - var start = intIndex + view[$OFFSET]; - var pack = conversion(+value); - for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; - } - - if (!$typed.ABV) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer, ARRAY_BUFFER); - var byteLength = toIndex(length); - this._b = arrayFill.call(new Array(byteLength), 0); - this[$LENGTH] = byteLength; - }; - - $DataView = function DataView(buffer, byteOffset, byteLength) { - anInstance(this, $DataView, DATA_VIEW); - anInstance(buffer, $ArrayBuffer, DATA_VIEW); - var bufferLength = buffer[$LENGTH]; - var offset = toInteger(byteOffset); - if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!'); - byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); - if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); - this[$BUFFER] = buffer; - this[$OFFSET] = offset; - this[$LENGTH] = byteLength; - }; - - if (DESCRIPTORS) { - addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); - addGetter($DataView, BUFFER, '_b'); - addGetter($DataView, BYTE_LENGTH, '_l'); - addGetter($DataView, BYTE_OFFSET, '_o'); - } - - redefineAll($DataView[PROTOTYPE], { - getInt8: function getInt8(byteOffset) { - return get(this, 1, byteOffset)[0] << 24 >> 24; - }, - getUint8: function getUint8(byteOffset) { - return get(this, 1, byteOffset)[0]; - }, - getInt16: function getInt16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments[1]); - return (bytes[1] << 8 | bytes[0]) << 16 >> 16; - }, - getUint16: function getUint16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments[1]); - return bytes[1] << 8 | bytes[0]; - }, - getInt32: function getInt32(byteOffset /* , littleEndian */) { - return unpackI32(get(this, 4, byteOffset, arguments[1])); - }, - getUint32: function getUint32(byteOffset /* , littleEndian */) { - return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; - }, - getFloat32: function getFloat32(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); - }, - getFloat64: function getFloat64(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); - }, - setInt8: function setInt8(byteOffset, value) { - set(this, 1, byteOffset, packI8, value); - }, - setUint8: function setUint8(byteOffset, value) { - set(this, 1, byteOffset, packI8, value); - }, - setInt16: function setInt16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setUint16: function setUint16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setInt32: function setInt32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setUint32: function setUint32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packF32, value, arguments[2]); - }, - setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { - set(this, 8, byteOffset, packF64, value, arguments[2]); - } - }); - } else { - if (!fails(function () { - $ArrayBuffer(1); - }) || !fails(function () { - new $ArrayBuffer(-1); // eslint-disable-line no-new - }) || fails(function () { - new $ArrayBuffer(); // eslint-disable-line no-new - new $ArrayBuffer(1.5); // eslint-disable-line no-new - new $ArrayBuffer(NaN); // eslint-disable-line no-new - return $ArrayBuffer.name != ARRAY_BUFFER; - })) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer); - return new BaseBuffer(toIndex(length)); - }; - var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; - for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) { - if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]); - } - if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer; - } - // iOS Safari 7.x bug - var view = new $DataView(new $ArrayBuffer(2)); - var $setInt8 = $DataView[PROTOTYPE].setInt8; - view.setInt8(0, 2147483648); - view.setInt8(1, 2147483649); - if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], { - setInt8: function setInt8(byteOffset, value) { - $setInt8.call(this, byteOffset, value << 24 >> 24); - }, - setUint8: function setUint8(byteOffset, value) { - $setInt8.call(this, byteOffset, value << 24 >> 24); - } - }, true); - } - setToStringTag($ArrayBuffer, ARRAY_BUFFER); - setToStringTag($DataView, DATA_VIEW); - hide($DataView[PROTOTYPE], $typed.VIEW, true); - exports[ARRAY_BUFFER] = $ArrayBuffer; - exports[DATA_VIEW] = $DataView; - - -/***/ }), -/* 227 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/ecma262/#sec-toindex - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - module.exports = function (it) { - if (it === undefined) return 0; - var number = toInteger(it); - var length = toLength(number); - if (number !== length) throw RangeError('Wrong length!'); - return length; - }; - - -/***/ }), -/* 228 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - $export($export.G + $export.W + $export.F * !__webpack_require__(225).ABV, { - DataView: __webpack_require__(226).DataView - }); - - -/***/ }), -/* 229 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Int8', 1, function (init) { - return function Int8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 230 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - if (__webpack_require__(6)) { - var LIBRARY = __webpack_require__(24); - var global = __webpack_require__(4); - var fails = __webpack_require__(7); - var $export = __webpack_require__(8); - var $typed = __webpack_require__(225); - var $buffer = __webpack_require__(226); - var ctx = __webpack_require__(20); - var anInstance = __webpack_require__(206); - var propertyDesc = __webpack_require__(17); - var hide = __webpack_require__(10); - var redefineAll = __webpack_require__(215); - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - var toIndex = __webpack_require__(227); - var toAbsoluteIndex = __webpack_require__(39); - var toPrimitive = __webpack_require__(16); - var has = __webpack_require__(5); - var classof = __webpack_require__(74); - var isObject = __webpack_require__(13); - var toObject = __webpack_require__(57); - var isArrayIter = __webpack_require__(163); - var create = __webpack_require__(45); - var getPrototypeOf = __webpack_require__(58); - var gOPN = __webpack_require__(49).f; - var getIterFn = __webpack_require__(165); - var uid = __webpack_require__(19); - var wks = __webpack_require__(26); - var createArrayMethod = __webpack_require__(173); - var createArrayIncludes = __webpack_require__(36); - var speciesConstructor = __webpack_require__(208); - var ArrayIterators = __webpack_require__(194); - var Iterators = __webpack_require__(129); - var $iterDetect = __webpack_require__(166); - var setSpecies = __webpack_require__(193); - var arrayFill = __webpack_require__(189); - var arrayCopyWithin = __webpack_require__(186); - var $DP = __webpack_require__(11); - var $GOPD = __webpack_require__(50); - var dP = $DP.f; - var gOPD = $GOPD.f; - var RangeError = global.RangeError; - var TypeError = global.TypeError; - var Uint8Array = global.Uint8Array; - var ARRAY_BUFFER = 'ArrayBuffer'; - var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER; - var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; - var PROTOTYPE = 'prototype'; - var ArrayProto = Array[PROTOTYPE]; - var $ArrayBuffer = $buffer.ArrayBuffer; - var $DataView = $buffer.DataView; - var arrayForEach = createArrayMethod(0); - var arrayFilter = createArrayMethod(2); - var arraySome = createArrayMethod(3); - var arrayEvery = createArrayMethod(4); - var arrayFind = createArrayMethod(5); - var arrayFindIndex = createArrayMethod(6); - var arrayIncludes = createArrayIncludes(true); - var arrayIndexOf = createArrayIncludes(false); - var arrayValues = ArrayIterators.values; - var arrayKeys = ArrayIterators.keys; - var arrayEntries = ArrayIterators.entries; - var arrayLastIndexOf = ArrayProto.lastIndexOf; - var arrayReduce = ArrayProto.reduce; - var arrayReduceRight = ArrayProto.reduceRight; - var arrayJoin = ArrayProto.join; - var arraySort = ArrayProto.sort; - var arraySlice = ArrayProto.slice; - var arrayToString = ArrayProto.toString; - var arrayToLocaleString = ArrayProto.toLocaleString; - var ITERATOR = wks('iterator'); - var TAG = wks('toStringTag'); - var TYPED_CONSTRUCTOR = uid('typed_constructor'); - var DEF_CONSTRUCTOR = uid('def_constructor'); - var ALL_CONSTRUCTORS = $typed.CONSTR; - var TYPED_ARRAY = $typed.TYPED; - var VIEW = $typed.VIEW; - var WRONG_LENGTH = 'Wrong length!'; - - var $map = createArrayMethod(1, function (O, length) { - return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); - }); - - var LITTLE_ENDIAN = fails(function () { - // eslint-disable-next-line no-undef - return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; - }); - - var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () { - new Uint8Array(1).set({}); - }); - - var toOffset = function (it, BYTES) { - var offset = toInteger(it); - if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!'); - return offset; - }; - - var validate = function (it) { - if (isObject(it) && TYPED_ARRAY in it) return it; - throw TypeError(it + ' is not a typed array!'); - }; - - var allocate = function (C, length) { - if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) { - throw TypeError('It is not a typed array constructor!'); - } return new C(length); - }; - - var speciesFromList = function (O, list) { - return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); - }; - - var fromList = function (C, list) { - var index = 0; - var length = list.length; - var result = allocate(C, length); - while (length > index) result[index] = list[index++]; - return result; - }; - - var addGetter = function (it, key, internal) { - dP(it, key, { get: function () { return this._d[internal]; } }); - }; - - var $from = function from(source /* , mapfn, thisArg */) { - var O = toObject(source); - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var iterFn = getIterFn(O); - var i, length, values, result, step, iterator; - if (iterFn != undefined && !isArrayIter(iterFn)) { - for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) { - values.push(step.value); - } O = values; - } - if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2); - for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) { - result[i] = mapping ? mapfn(O[i], i) : O[i]; - } - return result; - }; - - var $of = function of(/* ...items */) { - var index = 0; - var length = arguments.length; - var result = allocate(this, length); - while (length > index) result[index] = arguments[index++]; - return result; - }; - - // iOS Safari 6.x fails here - var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); }); - - var $toLocaleString = function toLocaleString() { - return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); - }; - - var proto = { - copyWithin: function copyWithin(target, start /* , end */) { - return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); - }, - every: function every(callbackfn /* , thisArg */) { - return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars - return arrayFill.apply(validate(this), arguments); - }, - filter: function filter(callbackfn /* , thisArg */) { - return speciesFromList(this, arrayFilter(validate(this), callbackfn, - arguments.length > 1 ? arguments[1] : undefined)); - }, - find: function find(predicate /* , thisArg */) { - return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - findIndex: function findIndex(predicate /* , thisArg */) { - return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - forEach: function forEach(callbackfn /* , thisArg */) { - arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - indexOf: function indexOf(searchElement /* , fromIndex */) { - return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - includes: function includes(searchElement /* , fromIndex */) { - return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - join: function join(separator) { // eslint-disable-line no-unused-vars - return arrayJoin.apply(validate(this), arguments); - }, - lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars - return arrayLastIndexOf.apply(validate(this), arguments); - }, - map: function map(mapfn /* , thisArg */) { - return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); - }, - reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars - return arrayReduce.apply(validate(this), arguments); - }, - reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars - return arrayReduceRight.apply(validate(this), arguments); - }, - reverse: function reverse() { - var that = this; - var length = validate(that).length; - var middle = Math.floor(length / 2); - var index = 0; - var value; - while (index < middle) { - value = that[index]; - that[index++] = that[--length]; - that[length] = value; - } return that; - }, - some: function some(callbackfn /* , thisArg */) { - return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - sort: function sort(comparefn) { - return arraySort.call(validate(this), comparefn); - }, - subarray: function subarray(begin, end) { - var O = validate(this); - var length = O.length; - var $begin = toAbsoluteIndex(begin, length); - return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( - O.buffer, - O.byteOffset + $begin * O.BYTES_PER_ELEMENT, - toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin) - ); - } - }; - - var $slice = function slice(start, end) { - return speciesFromList(this, arraySlice.call(validate(this), start, end)); - }; - - var $set = function set(arrayLike /* , offset */) { - validate(this); - var offset = toOffset(arguments[1], 1); - var length = this.length; - var src = toObject(arrayLike); - var len = toLength(src.length); - var index = 0; - if (len + offset > length) throw RangeError(WRONG_LENGTH); - while (index < len) this[offset + index] = src[index++]; - }; - - var $iterators = { - entries: function entries() { - return arrayEntries.call(validate(this)); - }, - keys: function keys() { - return arrayKeys.call(validate(this)); - }, - values: function values() { - return arrayValues.call(validate(this)); - } - }; - - var isTAIndex = function (target, key) { - return isObject(target) - && target[TYPED_ARRAY] - && typeof key != 'symbol' - && key in target - && String(+key) == String(key); - }; - var $getDesc = function getOwnPropertyDescriptor(target, key) { - return isTAIndex(target, key = toPrimitive(key, true)) - ? propertyDesc(2, target[key]) - : gOPD(target, key); - }; - var $setDesc = function defineProperty(target, key, desc) { - if (isTAIndex(target, key = toPrimitive(key, true)) - && isObject(desc) - && has(desc, 'value') - && !has(desc, 'get') - && !has(desc, 'set') - // TODO: add validation descriptor w/o calling accessors - && !desc.configurable - && (!has(desc, 'writable') || desc.writable) - && (!has(desc, 'enumerable') || desc.enumerable) - ) { - target[key] = desc.value; - return target; - } return dP(target, key, desc); - }; - - if (!ALL_CONSTRUCTORS) { - $GOPD.f = $getDesc; - $DP.f = $setDesc; - } - - $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { - getOwnPropertyDescriptor: $getDesc, - defineProperty: $setDesc - }); - - if (fails(function () { arrayToString.call({}); })) { - arrayToString = arrayToLocaleString = function toString() { - return arrayJoin.call(this); - }; - } - - var $TypedArrayPrototype$ = redefineAll({}, proto); - redefineAll($TypedArrayPrototype$, $iterators); - hide($TypedArrayPrototype$, ITERATOR, $iterators.values); - redefineAll($TypedArrayPrototype$, { - slice: $slice, - set: $set, - constructor: function () { /* noop */ }, - toString: arrayToString, - toLocaleString: $toLocaleString - }); - addGetter($TypedArrayPrototype$, 'buffer', 'b'); - addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); - addGetter($TypedArrayPrototype$, 'byteLength', 'l'); - addGetter($TypedArrayPrototype$, 'length', 'e'); - dP($TypedArrayPrototype$, TAG, { - get: function () { return this[TYPED_ARRAY]; } - }); - - // eslint-disable-next-line max-statements - module.exports = function (KEY, BYTES, wrapper, CLAMPED) { - CLAMPED = !!CLAMPED; - var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'; - var GETTER = 'get' + KEY; - var SETTER = 'set' + KEY; - var TypedArray = global[NAME]; - var Base = TypedArray || {}; - var TAC = TypedArray && getPrototypeOf(TypedArray); - var FORCED = !TypedArray || !$typed.ABV; - var O = {}; - var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; - var getter = function (that, index) { - var data = that._d; - return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); - }; - var setter = function (that, index, value) { - var data = that._d; - if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; - data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); - }; - var addElement = function (that, index) { - dP(that, index, { - get: function () { - return getter(this, index); - }, - set: function (value) { - return setter(this, index, value); - }, - enumerable: true - }); - }; - if (FORCED) { - TypedArray = wrapper(function (that, data, $offset, $length) { - anInstance(that, TypedArray, NAME, '_d'); - var index = 0; - var offset = 0; - var buffer, byteLength, length, klass; - if (!isObject(data)) { - length = toIndex(data); - byteLength = length * BYTES; - buffer = new $ArrayBuffer(byteLength); - } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { - buffer = data; - offset = toOffset($offset, BYTES); - var $len = data.byteLength; - if ($length === undefined) { - if ($len % BYTES) throw RangeError(WRONG_LENGTH); - byteLength = $len - offset; - if (byteLength < 0) throw RangeError(WRONG_LENGTH); - } else { - byteLength = toLength($length) * BYTES; - if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH); - } - length = byteLength / BYTES; - } else if (TYPED_ARRAY in data) { - return fromList(TypedArray, data); - } else { - return $from.call(TypedArray, data); - } - hide(that, '_d', { - b: buffer, - o: offset, - l: byteLength, - e: length, - v: new $DataView(buffer) - }); - while (index < length) addElement(that, index++); - }); - TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); - hide(TypedArrayPrototype, 'constructor', TypedArray); - } else if (!fails(function () { - TypedArray(1); - }) || !fails(function () { - new TypedArray(-1); // eslint-disable-line no-new - }) || !$iterDetect(function (iter) { - new TypedArray(); // eslint-disable-line no-new - new TypedArray(null); // eslint-disable-line no-new - new TypedArray(1.5); // eslint-disable-line no-new - new TypedArray(iter); // eslint-disable-line no-new - }, true)) { - TypedArray = wrapper(function (that, data, $offset, $length) { - anInstance(that, TypedArray, NAME); - var klass; - // `ws` module bug, temporarily remove validation length for Uint8Array - // https://github.com/websockets/ws/pull/645 - if (!isObject(data)) return new Base(toIndex(data)); - if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { - return $length !== undefined - ? new Base(data, toOffset($offset, BYTES), $length) - : $offset !== undefined - ? new Base(data, toOffset($offset, BYTES)) - : new Base(data); - } - if (TYPED_ARRAY in data) return fromList(TypedArray, data); - return $from.call(TypedArray, data); - }); - arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) { - if (!(key in TypedArray)) hide(TypedArray, key, Base[key]); - }); - TypedArray[PROTOTYPE] = TypedArrayPrototype; - if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray; - } - var $nativeIterator = TypedArrayPrototype[ITERATOR]; - var CORRECT_ITER_NAME = !!$nativeIterator - && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined); - var $iterator = $iterators.values; - hide(TypedArray, TYPED_CONSTRUCTOR, true); - hide(TypedArrayPrototype, TYPED_ARRAY, NAME); - hide(TypedArrayPrototype, VIEW, true); - hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); - - if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) { - dP(TypedArrayPrototype, TAG, { - get: function () { return NAME; } - }); - } - - O[NAME] = TypedArray; - - $export($export.G + $export.W + $export.F * (TypedArray != Base), O); - - $export($export.S, NAME, { - BYTES_PER_ELEMENT: BYTES - }); - - $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, { - from: $from, - of: $of - }); - - if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); - - $export($export.P, NAME, proto); - - setSpecies(NAME); - - $export($export.P + $export.F * FORCED_SET, NAME, { set: $set }); - - $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); - - if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString; - - $export($export.P + $export.F * fails(function () { - new TypedArray(1).slice(); - }), NAME, { slice: $slice }); - - $export($export.P + $export.F * (fails(function () { - return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString(); - }) || !fails(function () { - TypedArrayPrototype.toLocaleString.call([1, 2]); - })), NAME, { toLocaleString: $toLocaleString }); - - Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; - if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator); - }; - } else module.exports = function () { /* empty */ }; - - -/***/ }), -/* 231 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint8', 1, function (init) { - return function Uint8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 232 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint8', 1, function (init) { - return function Uint8ClampedArray(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }, true); - - -/***/ }), -/* 233 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Int16', 2, function (init) { - return function Int16Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 234 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint16', 2, function (init) { - return function Uint16Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 235 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Int32', 4, function (init) { - return function Int32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 236 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint32', 4, function (init) { - return function Uint32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 237 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Float32', 4, function (init) { - return function Float32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 238 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Float64', 8, function (init) { - return function Float64Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 239 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(21); - var anObject = __webpack_require__(12); - var rApply = (__webpack_require__(4).Reflect || {}).apply; - var fApply = Function.apply; - // MS Edge argumentsList argument is optional - $export($export.S + $export.F * !__webpack_require__(7)(function () { - rApply(function () { /* empty */ }); - }), 'Reflect', { - apply: function apply(target, thisArgument, argumentsList) { - var T = aFunction(target); - var L = anObject(argumentsList); - return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); - } - }); - - -/***/ }), -/* 240 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) - var $export = __webpack_require__(8); - var create = __webpack_require__(45); - var aFunction = __webpack_require__(21); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var bind = __webpack_require__(76); - var rConstruct = (__webpack_require__(4).Reflect || {}).construct; - - // MS Edge supports only 2 arguments and argumentsList argument is optional - // FF Nightly sets third argument as `new.target`, but does not create `this` from it - var NEW_TARGET_BUG = fails(function () { - function F() { /* empty */ } - return !(rConstruct(function () { /* empty */ }, [], F) instanceof F); - }); - var ARGS_BUG = !fails(function () { - rConstruct(function () { /* empty */ }); - }); - - $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { - construct: function construct(Target, args /* , newTarget */) { - aFunction(Target); - anObject(args); - var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); - if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget); - if (Target == newTarget) { - // w/o altered newTarget, optimization for 0-4 arguments - switch (args.length) { - case 0: return new Target(); - case 1: return new Target(args[0]); - case 2: return new Target(args[0], args[1]); - case 3: return new Target(args[0], args[1], args[2]); - case 4: return new Target(args[0], args[1], args[2], args[3]); - } - // w/o altered newTarget, lot of arguments case - var $args = [null]; - $args.push.apply($args, args); - return new (bind.apply(Target, $args))(); - } - // with altered newTarget, not support built-in constructors - var proto = newTarget.prototype; - var instance = create(isObject(proto) ? proto : Object.prototype); - var result = Function.apply.call(Target, instance, args); - return isObject(result) ? result : instance; - } - }); - - -/***/ }), -/* 241 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) - var dP = __webpack_require__(11); - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var toPrimitive = __webpack_require__(16); - - // MS Edge has broken Reflect.defineProperty - throwing instead of returning false - $export($export.S + $export.F * __webpack_require__(7)(function () { - // eslint-disable-next-line no-undef - Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 }); - }), 'Reflect', { - defineProperty: function defineProperty(target, propertyKey, attributes) { - anObject(target); - propertyKey = toPrimitive(propertyKey, true); - anObject(attributes); - try { - dP.f(target, propertyKey, attributes); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 242 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.4 Reflect.deleteProperty(target, propertyKey) - var $export = __webpack_require__(8); - var gOPD = __webpack_require__(50).f; - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - deleteProperty: function deleteProperty(target, propertyKey) { - var desc = gOPD(anObject(target), propertyKey); - return desc && !desc.configurable ? false : delete target[propertyKey]; - } - }); - - -/***/ }), -/* 243 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 26.1.5 Reflect.enumerate(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var Enumerate = function (iterated) { - this._t = anObject(iterated); // target - this._i = 0; // next index - var keys = this._k = []; // keys - var key; - for (key in iterated) keys.push(key); - }; - __webpack_require__(130)(Enumerate, 'Object', function () { - var that = this; - var keys = that._k; - var key; - do { - if (that._i >= keys.length) return { value: undefined, done: true }; - } while (!((key = keys[that._i++]) in that._t)); - return { value: key, done: false }; - }); - - $export($export.S, 'Reflect', { - enumerate: function enumerate(target) { - return new Enumerate(target); - } - }); - - -/***/ }), -/* 244 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.6 Reflect.get(target, propertyKey [, receiver]) - var gOPD = __webpack_require__(50); - var getPrototypeOf = __webpack_require__(58); - var has = __webpack_require__(5); - var $export = __webpack_require__(8); - var isObject = __webpack_require__(13); - var anObject = __webpack_require__(12); - - function get(target, propertyKey /* , receiver */) { - var receiver = arguments.length < 3 ? target : arguments[2]; - var desc, proto; - if (anObject(target) === receiver) return target[propertyKey]; - if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value') - ? desc.value - : desc.get !== undefined - ? desc.get.call(receiver) - : undefined; - if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver); - } - - $export($export.S, 'Reflect', { get: get }); - - -/***/ }), -/* 245 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) - var gOPD = __webpack_require__(50); - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { - return gOPD.f(anObject(target), propertyKey); - } - }); - - -/***/ }), -/* 246 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.8 Reflect.getPrototypeOf(target) - var $export = __webpack_require__(8); - var getProto = __webpack_require__(58); - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getPrototypeOf: function getPrototypeOf(target) { - return getProto(anObject(target)); - } - }); - - -/***/ }), -/* 247 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.9 Reflect.has(target, propertyKey) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { - has: function has(target, propertyKey) { - return propertyKey in target; - } - }); - - -/***/ }), -/* 248 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.10 Reflect.isExtensible(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var $isExtensible = Object.isExtensible; - - $export($export.S, 'Reflect', { - isExtensible: function isExtensible(target) { - anObject(target); - return $isExtensible ? $isExtensible(target) : true; - } - }); - - -/***/ }), -/* 249 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.11 Reflect.ownKeys(target) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { ownKeys: __webpack_require__(250) }); - - -/***/ }), -/* 250 */ -/***/ (function(module, exports, __webpack_require__) { - - // all object keys, includes non-enumerable and symbols - var gOPN = __webpack_require__(49); - var gOPS = __webpack_require__(42); - var anObject = __webpack_require__(12); - var Reflect = __webpack_require__(4).Reflect; - module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { - var keys = gOPN.f(anObject(it)); - var getSymbols = gOPS.f; - return getSymbols ? keys.concat(getSymbols(it)) : keys; - }; - - -/***/ }), -/* 251 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.12 Reflect.preventExtensions(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var $preventExtensions = Object.preventExtensions; - - $export($export.S, 'Reflect', { - preventExtensions: function preventExtensions(target) { - anObject(target); - try { - if ($preventExtensions) $preventExtensions(target); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 252 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) - var dP = __webpack_require__(11); - var gOPD = __webpack_require__(50); - var getPrototypeOf = __webpack_require__(58); - var has = __webpack_require__(5); - var $export = __webpack_require__(8); - var createDesc = __webpack_require__(17); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - - function set(target, propertyKey, V /* , receiver */) { - var receiver = arguments.length < 4 ? target : arguments[3]; - var ownDesc = gOPD.f(anObject(target), propertyKey); - var existingDescriptor, proto; - if (!ownDesc) { - if (isObject(proto = getPrototypeOf(target))) { - return set(proto, propertyKey, V, receiver); - } - ownDesc = createDesc(0); - } - if (has(ownDesc, 'value')) { - if (ownDesc.writable === false || !isObject(receiver)) return false; - if (existingDescriptor = gOPD.f(receiver, propertyKey)) { - if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; - existingDescriptor.value = V; - dP.f(receiver, propertyKey, existingDescriptor); - } else dP.f(receiver, propertyKey, createDesc(0, V)); - return true; - } - return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); - } - - $export($export.S, 'Reflect', { set: set }); - - -/***/ }), -/* 253 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.14 Reflect.setPrototypeOf(target, proto) - var $export = __webpack_require__(8); - var setProto = __webpack_require__(72); - - if (setProto) $export($export.S, 'Reflect', { - setPrototypeOf: function setPrototypeOf(target, proto) { - setProto.check(target, proto); - try { - setProto.set(target, proto); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 254 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/Array.prototype.includes - var $export = __webpack_require__(8); - var $includes = __webpack_require__(36)(true); - - $export($export.P, 'Array', { - includes: function includes(el /* , fromIndex = 0 */) { - return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - __webpack_require__(187)('includes'); - - -/***/ }), -/* 255 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap - var $export = __webpack_require__(8); - var flattenIntoArray = __webpack_require__(256); - var toObject = __webpack_require__(57); - var toLength = __webpack_require__(37); - var aFunction = __webpack_require__(21); - var arraySpeciesCreate = __webpack_require__(174); - - $export($export.P, 'Array', { - flatMap: function flatMap(callbackfn /* , thisArg */) { - var O = toObject(this); - var sourceLen, A; - aFunction(callbackfn); - sourceLen = toLength(O.length); - A = arraySpeciesCreate(O, 0); - flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]); - return A; - } - }); - - __webpack_require__(187)('flatMap'); - - -/***/ }), -/* 256 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray - var isArray = __webpack_require__(44); - var isObject = __webpack_require__(13); - var toLength = __webpack_require__(37); - var ctx = __webpack_require__(20); - var IS_CONCAT_SPREADABLE = __webpack_require__(26)('isConcatSpreadable'); - - function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) { - var targetIndex = start; - var sourceIndex = 0; - var mapFn = mapper ? ctx(mapper, thisArg, 3) : false; - var element, spreadable; - - while (sourceIndex < sourceLen) { - if (sourceIndex in source) { - element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; - - spreadable = false; - if (isObject(element)) { - spreadable = element[IS_CONCAT_SPREADABLE]; - spreadable = spreadable !== undefined ? !!spreadable : isArray(element); - } - - if (spreadable && depth > 0) { - targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; - } else { - if (targetIndex >= 0x1fffffffffffff) throw TypeError(); - target[targetIndex] = element; - } - - targetIndex++; - } - sourceIndex++; - } - return targetIndex; - } - - module.exports = flattenIntoArray; - - -/***/ }), -/* 257 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten - var $export = __webpack_require__(8); - var flattenIntoArray = __webpack_require__(256); - var toObject = __webpack_require__(57); - var toLength = __webpack_require__(37); - var toInteger = __webpack_require__(38); - var arraySpeciesCreate = __webpack_require__(174); - - $export($export.P, 'Array', { - flatten: function flatten(/* depthArg = 1 */) { - var depthArg = arguments[0]; - var O = toObject(this); - var sourceLen = toLength(O.length); - var A = arraySpeciesCreate(O, 0); - flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); - return A; - } - }); - - __webpack_require__(187)('flatten'); - - -/***/ }), -/* 258 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/mathiasbynens/String.prototype.at - var $export = __webpack_require__(8); - var $at = __webpack_require__(127)(true); - - $export($export.P, 'String', { - at: function at(pos) { - return $at(this, pos); - } - }); - - -/***/ }), -/* 259 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8); - var $pad = __webpack_require__(260); - var userAgent = __webpack_require__(213); - - // https://github.com/zloirock/core-js/issues/280 - $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { - padStart: function padStart(maxLength /* , fillString = ' ' */) { - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); - } - }); - - -/***/ }), -/* 260 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-string-pad-start-end - var toLength = __webpack_require__(37); - var repeat = __webpack_require__(90); - var defined = __webpack_require__(35); - - module.exports = function (that, maxLength, fillString, left) { - var S = String(defined(that)); - var stringLength = S.length; - var fillStr = fillString === undefined ? ' ' : String(fillString); - var intMaxLength = toLength(maxLength); - if (intMaxLength <= stringLength || fillStr == '') return S; - var fillLen = intMaxLength - stringLength; - var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); - if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); - return left ? stringFiller + S : S + stringFiller; - }; - - -/***/ }), -/* 261 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8); - var $pad = __webpack_require__(260); - var userAgent = __webpack_require__(213); - - // https://github.com/zloirock/core-js/issues/280 - $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { - padEnd: function padEnd(maxLength /* , fillString = ' ' */) { - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); - } - }); - - -/***/ }), -/* 262 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(82)('trimLeft', function ($trim) { - return function trimLeft() { - return $trim(this, 1); - }; - }, 'trimStart'); - - -/***/ }), -/* 263 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(82)('trimRight', function ($trim) { - return function trimRight() { - return $trim(this, 2); - }; - }, 'trimEnd'); - - -/***/ }), -/* 264 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/String.prototype.matchAll/ - var $export = __webpack_require__(8); - var defined = __webpack_require__(35); - var toLength = __webpack_require__(37); - var isRegExp = __webpack_require__(134); - var getFlags = __webpack_require__(197); - var RegExpProto = RegExp.prototype; - - var $RegExpStringIterator = function (regexp, string) { - this._r = regexp; - this._s = string; - }; - - __webpack_require__(130)($RegExpStringIterator, 'RegExp String', function next() { - var match = this._r.exec(this._s); - return { value: match, done: match === null }; - }); - - $export($export.P, 'String', { - matchAll: function matchAll(regexp) { - defined(this); - if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!'); - var S = String(this); - var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp); - var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); - rx.lastIndex = toLength(regexp.lastIndex); - return new $RegExpStringIterator(rx, S); - } - }); - - -/***/ }), -/* 265 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(28)('asyncIterator'); - - -/***/ }), -/* 266 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(28)('observable'); - - -/***/ }), -/* 267 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-getownpropertydescriptors - var $export = __webpack_require__(8); - var ownKeys = __webpack_require__(250); - var toIObject = __webpack_require__(32); - var gOPD = __webpack_require__(50); - var createProperty = __webpack_require__(164); - - $export($export.S, 'Object', { - getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { - var O = toIObject(object); - var getDesc = gOPD.f; - var keys = ownKeys(O); - var result = {}; - var i = 0; - var key, desc; - while (keys.length > i) { - desc = getDesc(O, key = keys[i++]); - if (desc !== undefined) createProperty(result, key, desc); - } - return result; - } - }); - - -/***/ }), -/* 268 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8); - var $values = __webpack_require__(269)(false); - - $export($export.S, 'Object', { - values: function values(it) { - return $values(it); - } - }); - - -/***/ }), -/* 269 */ -/***/ (function(module, exports, __webpack_require__) { - - var getKeys = __webpack_require__(30); - var toIObject = __webpack_require__(32); - var isEnum = __webpack_require__(43).f; - module.exports = function (isEntries) { - return function (it) { - var O = toIObject(it); - var keys = getKeys(O); - var length = keys.length; - var i = 0; - var result = []; - var key; - while (length > i) if (isEnum.call(O, key = keys[i++])) { - result.push(isEntries ? [key, O[key]] : O[key]); - } return result; - }; - }; - - -/***/ }), -/* 270 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8); - var $entries = __webpack_require__(269)(true); - - $export($export.S, 'Object', { - entries: function entries(it) { - return $entries(it); - } - }); - - -/***/ }), -/* 271 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var aFunction = __webpack_require__(21); - var $defineProperty = __webpack_require__(11); - - // B.2.2.2 Object.prototype.__defineGetter__(P, getter) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __defineGetter__: function __defineGetter__(P, getter) { - $defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true }); - } - }); - - -/***/ }), -/* 272 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // Forced replacement prototype accessors methods - module.exports = __webpack_require__(24) || !__webpack_require__(7)(function () { - var K = Math.random(); - // In FF throws only define methods - // eslint-disable-next-line no-undef, no-useless-call - __defineSetter__.call(null, K, function () { /* empty */ }); - delete __webpack_require__(4)[K]; - }); - - -/***/ }), -/* 273 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var aFunction = __webpack_require__(21); - var $defineProperty = __webpack_require__(11); - - // B.2.2.3 Object.prototype.__defineSetter__(P, setter) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __defineSetter__: function __defineSetter__(P, setter) { - $defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true }); - } - }); - - -/***/ }), -/* 274 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var toPrimitive = __webpack_require__(16); - var getPrototypeOf = __webpack_require__(58); - var getOwnPropertyDescriptor = __webpack_require__(50).f; - - // B.2.2.4 Object.prototype.__lookupGetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __lookupGetter__: function __lookupGetter__(P) { - var O = toObject(this); - var K = toPrimitive(P, true); - var D; - do { - if (D = getOwnPropertyDescriptor(O, K)) return D.get; - } while (O = getPrototypeOf(O)); - } - }); - - -/***/ }), -/* 275 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var toPrimitive = __webpack_require__(16); - var getPrototypeOf = __webpack_require__(58); - var getOwnPropertyDescriptor = __webpack_require__(50).f; - - // B.2.2.5 Object.prototype.__lookupSetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __lookupSetter__: function __lookupSetter__(P) { - var O = toObject(this); - var K = toPrimitive(P, true); - var D; - do { - if (D = getOwnPropertyDescriptor(O, K)) return D.set; - } while (O = getPrototypeOf(O)); - } - }); - - -/***/ }), -/* 276 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(277)('Map') }); - - -/***/ }), -/* 277 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var classof = __webpack_require__(74); - var from = __webpack_require__(278); - module.exports = function (NAME) { - return function toJSON() { - if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); - return from(this); - }; - }; - - -/***/ }), -/* 278 */ -/***/ (function(module, exports, __webpack_require__) { - - var forOf = __webpack_require__(207); - - module.exports = function (iter, ITERATOR) { - var result = []; - forOf(iter, false, result.push, result, ITERATOR); - return result; - }; - - -/***/ }), -/* 279 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(277)('Set') }); - - -/***/ }), -/* 280 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of - __webpack_require__(281)('Map'); - - -/***/ }), -/* 281 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-setmap-offrom/ - var $export = __webpack_require__(8); - - module.exports = function (COLLECTION) { - $export($export.S, COLLECTION, { of: function of() { - var length = arguments.length; - var A = new Array(length); - while (length--) A[length] = arguments[length]; - return new this(A); - } }); - }; - - -/***/ }), -/* 282 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of - __webpack_require__(281)('Set'); - - -/***/ }), -/* 283 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of - __webpack_require__(281)('WeakMap'); - - -/***/ }), -/* 284 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of - __webpack_require__(281)('WeakSet'); - - -/***/ }), -/* 285 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from - __webpack_require__(286)('Map'); - - -/***/ }), -/* 286 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-setmap-offrom/ - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(21); - var ctx = __webpack_require__(20); - var forOf = __webpack_require__(207); - - module.exports = function (COLLECTION) { - $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { - var mapFn = arguments[1]; - var mapping, A, n, cb; - aFunction(this); - mapping = mapFn !== undefined; - if (mapping) aFunction(mapFn); - if (source == undefined) return new this(); - A = []; - if (mapping) { - n = 0; - cb = ctx(mapFn, arguments[2], 2); - forOf(source, false, function (nextItem) { - A.push(cb(nextItem, n++)); - }); - } else { - forOf(source, false, A.push, A); - } - return new this(A); - } }); - }; - - -/***/ }), -/* 287 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from - __webpack_require__(286)('Set'); - - -/***/ }), -/* 288 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from - __webpack_require__(286)('WeakMap'); - - -/***/ }), -/* 289 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from - __webpack_require__(286)('WeakSet'); - - -/***/ }), -/* 290 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-global - var $export = __webpack_require__(8); - - $export($export.G, { global: __webpack_require__(4) }); - - -/***/ }), -/* 291 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-global - var $export = __webpack_require__(8); - - $export($export.S, 'System', { global: __webpack_require__(4) }); - - -/***/ }), -/* 292 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/ljharb/proposal-is-error - var $export = __webpack_require__(8); - var cof = __webpack_require__(34); - - $export($export.S, 'Error', { - isError: function isError(it) { - return cof(it) === 'Error'; - } - }); - - -/***/ }), -/* 293 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clamp: function clamp(x, lower, upper) { - return Math.min(upper, Math.max(lower, x)); - } - }); - - -/***/ }), -/* 294 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 }); - - -/***/ }), -/* 295 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var RAD_PER_DEG = 180 / Math.PI; - - $export($export.S, 'Math', { - degrees: function degrees(radians) { - return radians * RAD_PER_DEG; - } - }); - - -/***/ }), -/* 296 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var scale = __webpack_require__(297); - var fround = __webpack_require__(113); - - $export($export.S, 'Math', { - fscale: function fscale(x, inLow, inHigh, outLow, outHigh) { - return fround(scale(x, inLow, inHigh, outLow, outHigh)); - } - }); - - -/***/ }), -/* 297 */ -/***/ (function(module, exports) { - - // https://rwaldron.github.io/proposal-math-extensions/ - module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) { - if ( - arguments.length === 0 - // eslint-disable-next-line no-self-compare - || x != x - // eslint-disable-next-line no-self-compare - || inLow != inLow - // eslint-disable-next-line no-self-compare - || inHigh != inHigh - // eslint-disable-next-line no-self-compare - || outLow != outLow - // eslint-disable-next-line no-self-compare - || outHigh != outHigh - ) return NaN; - if (x === Infinity || x === -Infinity) return x; - return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow; - }; - - -/***/ }), -/* 298 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - iaddh: function iaddh(x0, x1, y0, y1) { - var $x0 = x0 >>> 0; - var $x1 = x1 >>> 0; - var $y0 = y0 >>> 0; - return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; - } - }); - - -/***/ }), -/* 299 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - isubh: function isubh(x0, x1, y0, y1) { - var $x0 = x0 >>> 0; - var $x1 = x1 >>> 0; - var $y0 = y0 >>> 0; - return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; - } - }); - - -/***/ }), -/* 300 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - imulh: function imulh(u, v) { - var UINT16 = 0xffff; - var $u = +u; - var $v = +v; - var u0 = $u & UINT16; - var v0 = $v & UINT16; - var u1 = $u >> 16; - var v1 = $v >> 16; - var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); - } - }); - - -/***/ }), -/* 301 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI }); - - -/***/ }), -/* 302 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var DEG_PER_RAD = Math.PI / 180; - - $export($export.S, 'Math', { - radians: function radians(degrees) { - return degrees * DEG_PER_RAD; - } - }); - - -/***/ }), -/* 303 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { scale: __webpack_require__(297) }); - - -/***/ }), -/* 304 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - umulh: function umulh(u, v) { - var UINT16 = 0xffff; - var $u = +u; - var $v = +v; - var u0 = $u & UINT16; - var v0 = $v & UINT16; - var u1 = $u >>> 16; - var v1 = $v >>> 16; - var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); - } - }); - - -/***/ }), -/* 305 */ -/***/ (function(module, exports, __webpack_require__) { - - // http://jfbastien.github.io/papers/Math.signbit.html - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { signbit: function signbit(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0; - } }); - - -/***/ }), -/* 306 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-promise-finally - 'use strict'; - var $export = __webpack_require__(8); - var core = __webpack_require__(9); - var global = __webpack_require__(4); - var speciesConstructor = __webpack_require__(208); - var promiseResolve = __webpack_require__(214); - - $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { - var C = speciesConstructor(this, core.Promise || global.Promise); - var isFunction = typeof onFinally == 'function'; - return this.then( - isFunction ? function (x) { - return promiseResolve(C, onFinally()).then(function () { return x; }); - } : onFinally, - isFunction ? function (e) { - return promiseResolve(C, onFinally()).then(function () { throw e; }); - } : onFinally - ); - } }); - - -/***/ }), -/* 307 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-promise-try - var $export = __webpack_require__(8); - var newPromiseCapability = __webpack_require__(211); - var perform = __webpack_require__(212); - - $export($export.S, 'Promise', { 'try': function (callbackfn) { - var promiseCapability = newPromiseCapability.f(this); - var result = perform(callbackfn); - (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); - return promiseCapability.promise; - } }); - - -/***/ }), -/* 308 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var toMetaKey = metadata.key; - var ordinaryDefineOwnMetadata = metadata.set; - - metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) { - ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); - } }); - - -/***/ }), -/* 309 */ -/***/ (function(module, exports, __webpack_require__) { - - var Map = __webpack_require__(216); - var $export = __webpack_require__(8); - var shared = __webpack_require__(23)('metadata'); - var store = shared.store || (shared.store = new (__webpack_require__(221))()); - - var getOrCreateMetadataMap = function (target, targetKey, create) { - var targetMetadata = store.get(target); - if (!targetMetadata) { - if (!create) return undefined; - store.set(target, targetMetadata = new Map()); - } - var keyMetadata = targetMetadata.get(targetKey); - if (!keyMetadata) { - if (!create) return undefined; - targetMetadata.set(targetKey, keyMetadata = new Map()); - } return keyMetadata; - }; - var ordinaryHasOwnMetadata = function (MetadataKey, O, P) { - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? false : metadataMap.has(MetadataKey); - }; - var ordinaryGetOwnMetadata = function (MetadataKey, O, P) { - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); - }; - var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) { - getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); - }; - var ordinaryOwnMetadataKeys = function (target, targetKey) { - var metadataMap = getOrCreateMetadataMap(target, targetKey, false); - var keys = []; - if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); }); - return keys; - }; - var toMetaKey = function (it) { - return it === undefined || typeof it == 'symbol' ? it : String(it); - }; - var exp = function (O) { - $export($export.S, 'Reflect', O); - }; - - module.exports = { - store: store, - map: getOrCreateMetadataMap, - has: ordinaryHasOwnMetadata, - get: ordinaryGetOwnMetadata, - set: ordinaryDefineOwnMetadata, - keys: ordinaryOwnMetadataKeys, - key: toMetaKey, - exp: exp - }; - - -/***/ }), -/* 310 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var toMetaKey = metadata.key; - var getOrCreateMetadataMap = metadata.map; - var store = metadata.store; - - metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) { - var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]); - var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); - if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false; - if (metadataMap.size) return true; - var targetMetadata = store.get(target); - targetMetadata['delete'](targetKey); - return !!targetMetadata.size || store['delete'](target); - } }); - - -/***/ }), -/* 311 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(58); - var ordinaryHasOwnMetadata = metadata.has; - var ordinaryGetOwnMetadata = metadata.get; - var toMetaKey = metadata.key; - - var ordinaryGetMetadata = function (MetadataKey, O, P) { - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P); - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; - }; - - metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) { - return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 312 */ -/***/ (function(module, exports, __webpack_require__) { - - var Set = __webpack_require__(220); - var from = __webpack_require__(278); - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(58); - var ordinaryOwnMetadataKeys = metadata.keys; - var toMetaKey = metadata.key; - - var ordinaryMetadataKeys = function (O, P) { - var oKeys = ordinaryOwnMetadataKeys(O, P); - var parent = getPrototypeOf(O); - if (parent === null) return oKeys; - var pKeys = ordinaryMetadataKeys(parent, P); - return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; - }; - - metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) { - return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - } }); - - -/***/ }), -/* 313 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var ordinaryGetOwnMetadata = metadata.get; - var toMetaKey = metadata.key; - - metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) { - return ordinaryGetOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 314 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var ordinaryOwnMetadataKeys = metadata.keys; - var toMetaKey = metadata.key; - - metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) { - return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - } }); - - -/***/ }), -/* 315 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(58); - var ordinaryHasOwnMetadata = metadata.has; - var toMetaKey = metadata.key; - - var ordinaryHasMetadata = function (MetadataKey, O, P) { - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) return true; - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; - }; - - metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) { - return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 316 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var ordinaryHasOwnMetadata = metadata.has; - var toMetaKey = metadata.key; - - metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) { - return ordinaryHasOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 317 */ -/***/ (function(module, exports, __webpack_require__) { - - var $metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var aFunction = __webpack_require__(21); - var toMetaKey = $metadata.key; - var ordinaryDefineOwnMetadata = $metadata.set; - - $metadata.exp({ metadata: function metadata(metadataKey, metadataValue) { - return function decorator(target, targetKey) { - ordinaryDefineOwnMetadata( - metadataKey, metadataValue, - (targetKey !== undefined ? anObject : aFunction)(target), - toMetaKey(targetKey) - ); - }; - } }); - - -/***/ }), -/* 318 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask - var $export = __webpack_require__(8); - var microtask = __webpack_require__(210)(); - var process = __webpack_require__(4).process; - var isNode = __webpack_require__(34)(process) == 'process'; - - $export($export.G, { - asap: function asap(fn) { - var domain = isNode && process.domain; - microtask(domain ? domain.bind(fn) : fn); - } - }); - - -/***/ }), -/* 319 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/zenparsing/es-observable - var $export = __webpack_require__(8); - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var microtask = __webpack_require__(210)(); - var OBSERVABLE = __webpack_require__(26)('observable'); - var aFunction = __webpack_require__(21); - var anObject = __webpack_require__(12); - var anInstance = __webpack_require__(206); - var redefineAll = __webpack_require__(215); - var hide = __webpack_require__(10); - var forOf = __webpack_require__(207); - var RETURN = forOf.RETURN; - - var getMethod = function (fn) { - return fn == null ? undefined : aFunction(fn); - }; - - var cleanupSubscription = function (subscription) { - var cleanup = subscription._c; - if (cleanup) { - subscription._c = undefined; - cleanup(); - } - }; - - var subscriptionClosed = function (subscription) { - return subscription._o === undefined; - }; - - var closeSubscription = function (subscription) { - if (!subscriptionClosed(subscription)) { - subscription._o = undefined; - cleanupSubscription(subscription); - } - }; - - var Subscription = function (observer, subscriber) { - anObject(observer); - this._c = undefined; - this._o = observer; - observer = new SubscriptionObserver(this); - try { - var cleanup = subscriber(observer); - var subscription = cleanup; - if (cleanup != null) { - if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); }; - else aFunction(cleanup); - this._c = cleanup; - } - } catch (e) { - observer.error(e); - return; - } if (subscriptionClosed(this)) cleanupSubscription(this); - }; - - Subscription.prototype = redefineAll({}, { - unsubscribe: function unsubscribe() { closeSubscription(this); } - }); - - var SubscriptionObserver = function (subscription) { - this._s = subscription; - }; - - SubscriptionObserver.prototype = redefineAll({}, { - next: function next(value) { - var subscription = this._s; - if (!subscriptionClosed(subscription)) { - var observer = subscription._o; - try { - var m = getMethod(observer.next); - if (m) return m.call(observer, value); - } catch (e) { - try { - closeSubscription(subscription); - } finally { - throw e; - } - } - } - }, - error: function error(value) { - var subscription = this._s; - if (subscriptionClosed(subscription)) throw value; - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.error); - if (!m) throw value; - value = m.call(observer, value); - } catch (e) { - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - }, - complete: function complete(value) { - var subscription = this._s; - if (!subscriptionClosed(subscription)) { - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.complete); - value = m ? m.call(observer, value) : undefined; - } catch (e) { - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - } - } - }); - - var $Observable = function Observable(subscriber) { - anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); - }; - - redefineAll($Observable.prototype, { - subscribe: function subscribe(observer) { - return new Subscription(observer, this._f); - }, - forEach: function forEach(fn) { - var that = this; - return new (core.Promise || global.Promise)(function (resolve, reject) { - aFunction(fn); - var subscription = that.subscribe({ - next: function (value) { - try { - return fn(value); - } catch (e) { - reject(e); - subscription.unsubscribe(); - } - }, - error: reject, - complete: resolve - }); - }); - } - }); - - redefineAll($Observable, { - from: function from(x) { - var C = typeof this === 'function' ? this : $Observable; - var method = getMethod(anObject(x)[OBSERVABLE]); - if (method) { - var observable = anObject(method.call(x)); - return observable.constructor === C ? observable : new C(function (observer) { - return observable.subscribe(observer); - }); - } - return new C(function (observer) { - var done = false; - microtask(function () { - if (!done) { - try { - if (forOf(x, false, function (it) { - observer.next(it); - if (done) return RETURN; - }) === RETURN) return; - } catch (e) { - if (done) throw e; - observer.error(e); - return; - } observer.complete(); - } - }); - return function () { done = true; }; - }); - }, - of: function of() { - for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++]; - return new (typeof this === 'function' ? this : $Observable)(function (observer) { - var done = false; - microtask(function () { - if (!done) { - for (var j = 0; j < items.length; ++j) { - observer.next(items[j]); - if (done) return; - } observer.complete(); - } - }); - return function () { done = true; }; - }); - } - }); - - hide($Observable.prototype, OBSERVABLE, function () { return this; }); - - $export($export.G, { Observable: $Observable }); - - __webpack_require__(193)('Observable'); - - -/***/ }), -/* 320 */ -/***/ (function(module, exports, __webpack_require__) { - - // ie9- setTimeout & setInterval additional parameters fix - var global = __webpack_require__(4); - var $export = __webpack_require__(8); - var userAgent = __webpack_require__(213); - var slice = [].slice; - var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check - var wrap = function (set) { - return function (fn, time /* , ...args */) { - var boundArgs = arguments.length > 2; - var args = boundArgs ? slice.call(arguments, 2) : false; - return set(boundArgs ? function () { - // eslint-disable-next-line no-new-func - (typeof fn == 'function' ? fn : Function(fn)).apply(this, args); - } : fn, time); - }; - }; - $export($export.G + $export.B + $export.F * MSIE, { - setTimeout: wrap(global.setTimeout), - setInterval: wrap(global.setInterval) - }); - - -/***/ }), -/* 321 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $task = __webpack_require__(209); - $export($export.G + $export.B, { - setImmediate: $task.set, - clearImmediate: $task.clear - }); - - -/***/ }), -/* 322 */ -/***/ (function(module, exports, __webpack_require__) { - - var $iterators = __webpack_require__(194); - var getKeys = __webpack_require__(30); - var redefine = __webpack_require__(18); - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var Iterators = __webpack_require__(129); - var wks = __webpack_require__(26); - var ITERATOR = wks('iterator'); - var TO_STRING_TAG = wks('toStringTag'); - var ArrayValues = Iterators.Array; - - var DOMIterables = { - CSSRuleList: true, // TODO: Not spec compliant, should be false. - CSSStyleDeclaration: false, - CSSValueList: false, - ClientRectList: false, - DOMRectList: false, - DOMStringList: false, - DOMTokenList: true, - DataTransferItemList: false, - FileList: false, - HTMLAllCollection: false, - HTMLCollection: false, - HTMLFormElement: false, - HTMLSelectElement: false, - MediaList: true, // TODO: Not spec compliant, should be false. - MimeTypeArray: false, - NamedNodeMap: false, - NodeList: true, - PaintRequestList: false, - Plugin: false, - PluginArray: false, - SVGLengthList: false, - SVGNumberList: false, - SVGPathSegList: false, - SVGPointList: false, - SVGStringList: false, - SVGTransformList: false, - SourceBufferList: false, - StyleSheetList: true, // TODO: Not spec compliant, should be false. - TextTrackCueList: false, - TextTrackList: false, - TouchList: false - }; - - for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { - var NAME = collections[i]; - var explicit = DOMIterables[NAME]; - var Collection = global[NAME]; - var proto = Collection && Collection.prototype; - var key; - if (proto) { - if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); - if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); - Iterators[NAME] = ArrayValues; - if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); - } - } - - -/***/ }), -/* 323 */ -/***/ (function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - - !(function(global) { - "use strict"; - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - var inModule = typeof module === "object"; - var runtime = global.regeneratorRuntime; - if (runtime) { - if (inModule) { - // If regeneratorRuntime is defined globally and we're in a module, - // make the exports object identical to regeneratorRuntime. - module.exports = runtime; - } - // Don't bother evaluating the rest of this file if the runtime was - // already defined globally. - return; - } - - // Define the runtime globally (as expected by generated code) as either - // module.exports (if we're in a module) or a new, empty object. - runtime = global.regeneratorRuntime = inModule ? module.exports : {}; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - runtime.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } - - runtime.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - runtime.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - runtime.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. If the Promise is rejected, however, the - // result for this iteration will be rejected with the same - // reason. Note that rejections of yielded Promises are not - // thrown back into the generator function, as is the case - // when an awaited Promise is rejected. This difference in - // behavior between yield and await is important, because it - // allows the consumer to decide what to do with the yielded - // rejection (swallow it and continue, manually .throw it back - // into the generator, abandon iteration, whatever). With - // await, by contrast, there is no opportunity to examine the - // rejection reason outside the generator function, so the - // only option is to throw it from the await expression, and - // let the generator function handle the exception. - result.value = unwrapped; - resolve(result); - }, reject); - } - } - - if (typeof global.process === "object" && global.process.domain) { - invoke = global.process.domain.bind(invoke); - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - runtime.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - runtime.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); - - return runtime.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - if (delegate.iterator.return) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[toStringTagSymbol] = "Generator"; - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - runtime.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - runtime.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } - - return ContinueSentinel; - } - }; - })( - // Among the various tricks for obtaining a reference to the global - // object, this seems to be the most reliable technique that does not - // use indirect eval (which violates Content Security Policy). - typeof global === "object" ? global : - typeof window === "object" ? window : - typeof self === "object" ? self : this - ); - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 324 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(325); - module.exports = __webpack_require__(9).RegExp.escape; - - -/***/ }), -/* 325 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/benjamingr/RexExp.escape - var $export = __webpack_require__(8); - var $re = __webpack_require__(326)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); - - $export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } }); - - -/***/ }), -/* 326 */ -/***/ (function(module, exports) { - - module.exports = function (regExp, replace) { - var replacer = replace === Object(replace) ? function (part) { - return replace[part]; - } : replace; - return function (it) { - return String(it).replace(regExp, replacer); - }; - }; - - -/***/ }), -/* 327 */ -/***/ (function(module, exports, __webpack_require__) { - - var BSON = __webpack_require__(328), - Binary = __webpack_require__(350), - Code = __webpack_require__(345), - DBRef = __webpack_require__(349), - Decimal128 = __webpack_require__(346), - Double = __webpack_require__(335), - Int32 = __webpack_require__(344), - Long = __webpack_require__(334), - Map = __webpack_require__(333), - MaxKey = __webpack_require__(348), - MinKey = __webpack_require__(347), - ObjectId = __webpack_require__(337), - BSONRegExp = __webpack_require__(342), - Symbol = __webpack_require__(343), - Timestamp = __webpack_require__(336); - - // 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. - - // Add BSON types to function creation - BSON.Binary = Binary; - BSON.Code = Code; - BSON.DBRef = DBRef; - BSON.Decimal128 = Decimal128; - BSON.Double = Double; - BSON.Int32 = Int32; - BSON.Long = Long; - BSON.Map = Map; - BSON.MaxKey = MaxKey; - BSON.MinKey = MinKey; - BSON.ObjectId = ObjectId; - BSON.ObjectID = ObjectId; - BSON.BSONRegExp = BSONRegExp; - BSON.Symbol = Symbol; - BSON.Timestamp = Timestamp; - - // Return the BSON - module.exports = BSON; - -/***/ }), -/* 328 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var Map = __webpack_require__(333), - Long = __webpack_require__(334), - Double = __webpack_require__(335), - Timestamp = __webpack_require__(336), - ObjectID = __webpack_require__(337), - BSONRegExp = __webpack_require__(342), - Symbol = __webpack_require__(343), - Int32 = __webpack_require__(344), - Code = __webpack_require__(345), - Decimal128 = __webpack_require__(346), - MinKey = __webpack_require__(347), - MaxKey = __webpack_require__(348), - DBRef = __webpack_require__(349), - Binary = __webpack_require__(350); - - // Parts of the parser - var deserialize = __webpack_require__(351), - serializer = __webpack_require__(352), - calculateObjectSize = __webpack_require__(355); - - /** - * @ignore - * @api private - */ - // Default Max Size - var MAXSIZE = 1024 * 1024 * 17; - - // Current Internal Temporary Serialization Buffer - var buffer = new Buffer(MAXSIZE); - - var BSON = function () {}; - - /** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ - BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = new Buffer(minInternalBufferSize); - } - - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = new Buffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; - }; - - /** - * 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 {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ - BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer(finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); - - // Return the index - return serializationIndex - 1; - }; - - /** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ - BSON.prototype.deserialize = function (buffer, options) { - return deserialize(buffer, options); - }; - - /** - * 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} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ - BSON.prototype.calculateObjectSize = function (object, options) { - options = options || {}; - - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); - }; - - /** - * Deserialize stream data as BSON documents. - * - * @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. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @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) { - 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] = this.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; - }; - - /** - * @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 - module.exports = BSON; - module.exports.Code = Code; - module.exports.Map = Map; - module.exports.Symbol = Symbol; - module.exports.BSON = BSON; - module.exports.DBRef = DBRef; - module.exports.Binary = Binary; - module.exports.ObjectID = ObjectID; - module.exports.Long = Long; - module.exports.Timestamp = Timestamp; - module.exports.Double = Double; - module.exports.Int32 = Int32; - module.exports.MinKey = MinKey; - module.exports.MaxKey = MaxKey; - module.exports.BSONRegExp = BSONRegExp; - module.exports.Decimal128 = Decimal128; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) - -/***/ }), -/* 329 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> - * @license MIT - */ - /* eslint-disable no-proto */ - - 'use strict' - - var base64 = __webpack_require__(330) - var ieee754 = __webpack_require__(331) - var isArray = __webpack_require__(332) - - exports.Buffer = Buffer - exports.SlowBuffer = SlowBuffer - exports.INSPECT_MAX_BYTES = 50 - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - - /* - * Export kMaxLength after typed array support is determined. - */ - exports.kMaxLength = kMaxLength() - - function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } - } - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer.poolSize = 8192 // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr - } - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - } - - function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) - } - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - } - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } - - return that - } - - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that - } - - function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) - } - - Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - } - - Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer - } - - function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - Buffer.byteLength = byteLength - - function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true - - function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i - } - - Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this - } - - Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this - } - - Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this - } - - Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - } - - Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 - } - - Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '<Buffer ' + str + '>' - } - - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') - } - - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - } - - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - } - - Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - } - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i - } - - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - } - - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000 - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res - } - - Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } - - return newBuf - } - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } - - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val - } - - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val - } - - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] - } - - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) - } - - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] - } - - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - } - - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - } - - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - } - - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - } - - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - } - - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) - } - - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) - } - - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) - } - - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) - } - - function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 - } - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 - } - - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } - - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 - } - - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - } - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - } - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len - } - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this - } - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str - } - - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray - } - - function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray - } - - function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 330 */ -/***/ (function(module, exports) { - - 'use strict' - - exports.byteLength = byteLength - exports.toByteArray = toByteArray - exports.fromByteArray = fromByteArray - - var lookup = [] - var revLookup = [] - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i - } - - // Support decoding URL-safe base64 strings, as Node.js does. - // See: https://en.wikipedia.org/wiki/Base64#URL_applications - revLookup['-'.charCodeAt(0)] = 62 - revLookup['_'.charCodeAt(0)] = 63 - - function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] - } - - // base64 is 4/3 + up to two characters of the original data - function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen - } - - function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen - } - - function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - for (var i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr - } - - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] - } - - function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') - } - - function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk( - uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) - )) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') - } - - -/***/ }), -/* 331 */ -/***/ (function(module, exports) { - - exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) - } - - exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var 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 - } - - -/***/ }), -/* 332 */ -/***/ (function(module, exports) { - - var toString = {}.toString; - - module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - -/***/ }), -/* 333 */ -/***/ (function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {'use strict'; - - // We have an ES6 Map available, return the native instance - - if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; - } else { - // We will return a polyfill - var Map = function (array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function (callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function () { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; - } - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 334 */ -/***/ (function(module, exports) { - - // 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)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - 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; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - 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; - -/***/ }), -/* 335 */ -/***/ (function(module, exports) { - - /** - * 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; - -/***/ }), -/* 336 */ -/***/ (function(module, exports) { - - // 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)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - 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; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - 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; - -/***/ }), -/* 337 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer, process) {// Custom inspect property name / symbol. - var inspect = 'inspect'; - - /** - * 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}$'); - - // Check if buffer exists - try { - if (Buffer && Buffer.from) { - var hasBufferType = true; - inspect = __webpack_require__(339).inspect.custom || 'inspect'; - } - } catch (err) { - hasBufferType = false; - } - - /** - * 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) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if (id == null || typeof id === 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - 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 && hasBufferType) { - return new ObjectID(new Buffer(id, 'hex')); - } else if (valid && typeof id === 'string' && id.length === 24) { - return ObjectID.createFromHexString(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - }; - - // 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 = ''; - if (!this.id || !this.id.length) { - throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return 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 buffer used in ObjectID's - * - * @method - * @param {number} [time] optional parameter allowing to pass in a second based timestamp. - * @return {Buffer} return the 12 byte id buffer string. - */ - ObjectID.prototype.generate = function (time) { - if ('number' !== typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; - var inc = this.get_inc(); - // Buffer used - var buffer = new Buffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = MACHINE_ID >> 8 & 0xff; - buffer[4] = MACHINE_ID >> 16 & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = pid >> 8 & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = inc >> 8 & 0xff; - buffer[9] = inc >> 16 & 0xff; - // Return the buffer - return buffer; - }; - - /** - * Converts the id into a 24 byte hex string for printing - * - * @param {String} format The Buffer toString format parameter. - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toString = function (format) { - // Is the id a buffer then use the buffer toString method to return the format - if (this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - 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) { - // var id; - - if (otherId instanceof ObjectID) { - return this.toString() === otherId.toString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } - }; - - /** - * 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(); - var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - - /** - * @ignore - */ - ObjectID.index = ~~(Math.random() * 0xffffff); - - /** - * @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 buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Return the new objectId - return new ObjectID(buffer); - }; - - // Lookup tables - //var encodeLookup = '0123456789abcdef'.split(''); - var decodeLookup = []; - i = 0; - while (i < 10) decodeLookup[0x30 + i] = i++; - while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - - var _Buffer = Buffer; - var convertToHex = function (bytes) { - return bytes.toString('hex'); - }; - - /** - * 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(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || string != null && string.length !== 24) { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - - // Use Buffer.from method if available - if (hasBufferType) return new ObjectID(new Buffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); - }; - - /** - * 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 (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (id.toHexString) { - return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id); - } - - return false; - }; - - /** - * @ignore - */ - Object.defineProperty(ObjectID.prototype, 'generationTime', { - enumerable: true, - get: function () { - return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - }, - set: function (value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = value >> 8 & 0xff; - this.id[1] = value >> 16 & 0xff; - this.id[0] = value >> 24 & 0xff; - } - }); - - /** - * Expose. - */ - module.exports = ObjectID; - module.exports.ObjectID = ObjectID; - module.exports.ObjectId = ObjectID; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer, __webpack_require__(338))) - -/***/ }), -/* 338 */ -/***/ (function(module, exports) { - - // shim for using process in browser - var process = module.exports = {}; - - // cached from whatever global is present so that test runners that stub it - // don't break things. But we need to wrap it in a try catch in case it is - // wrapped in strict mode code which doesn't define any globals. It's inside a - // function because try/catches deoptimize in certain engines. - - var cachedSetTimeout; - var cachedClearTimeout; - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - (function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } - } ()) - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - process.prependListener = noop; - process.prependOnceListener = noop; - - process.listeners = function (name) { return [] } - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - -/***/ }), -/* 339 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var 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); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } - - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - 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) { - 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; - - exports.isBuffer = __webpack_require__(340); - - 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 = __webpack_require__(341); - - 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); - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(338))) - -/***/ }), -/* 340 */ -/***/ (function(module, exports) { - - module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; - } - -/***/ }), -/* 341 */ -/***/ (function(module, exports) { - - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } - - -/***/ }), -/* 342 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) { - throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); - } - } - } - - module.exports = BSONRegExp; - module.exports.BSONRegExp = BSONRegExp; - -/***/ }), -/* 343 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {// Custom inspect property name / symbol. - var inspect = Buffer ? __webpack_require__(339).inspect.custom || 'inspect' : 'inspect'; - - /** - * 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; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) - -/***/ }), -/* 344 */ -/***/ (function(module, exports) { - - /** - * A class representation of a BSON Int32 type. - * - * @class - * @param {number} value the number we want to represent as an int32. - * @return {Int32} - */ - var Int32 = function (value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; - }; - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Int32.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Int32; - module.exports.Int32 = Int32; - -/***/ }), -/* 345 */ -/***/ (function(module, exports) { - - /** - * 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; - }; - - /** - * @ignore - */ - Code.prototype.toJSON = function () { - return { scope: this.scope, code: this.code }; - }; - - module.exports = Code; - module.exports.Code = Code; - -/***/ }), -/* 346 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var Long = __webpack_require__(334); - - var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; - var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; - var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - - var EXPONENT_MAX = 6111; - var EXPONENT_MIN = -6176; - var EXPONENT_BIAS = 6176; - var MAX_DIGITS = 34; - - // Nan value bits as 32 bit values (due to lack of longs) - var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - // Infinity value bits 32 bit values (due to lack of longs) - var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - - var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - - // Detect if the value is a digit - var isDigit = function (value) { - return !isNaN(parseInt(value, 10)); - }; - - // Divide two uint128 values - var divideu128 = function (value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; - }; - - // Multiply two Long values and return the 128 bit value - var multiply64x2 = function (left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; - }; - - var lessThan = function (left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; - }; - - // var longtoHex = function(value) { - // var buffer = new Buffer(8); - // var index = 0; - // // Encode the low 64 bits of the decimal - // // Encode low bits - // buffer[index++] = value.low_ & 0xff; - // buffer[index++] = (value.low_ >> 8) & 0xff; - // buffer[index++] = (value.low_ >> 16) & 0xff; - // buffer[index++] = (value.low_ >> 24) & 0xff; - // // Encode high bits - // buffer[index++] = value.high_ & 0xff; - // buffer[index++] = (value.high_ >> 8) & 0xff; - // buffer[index++] = (value.high_ >> 16) & 0xff; - // buffer[index++] = (value.high_ >> 24) & 0xff; - // return buffer.reverse().toString('hex'); - // }; - - // var int32toHex = function(value) { - // var buffer = new Buffer(4); - // var index = 0; - // // Encode the low 64 bits of the decimal - // // Encode low bits - // buffer[index++] = value & 0xff; - // buffer[index++] = (value >> 8) & 0xff; - // buffer[index++] = (value >> 16) & 0xff; - // buffer[index++] = (value >> 24) & 0xff; - // return buffer.reverse().toString('hex'); - // }; - - /** - * A class representation of the BSON Decimal128 type. - * - * @class - * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. - * @return {Double} - */ - var Decimal128 = function (bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; - }; - - /** - * Create a Decimal128 instance from a string representation - * - * @method - * @param {string} string a numeric string representation. - * @return {Decimal128} returns a Decimal128 instance. - */ - Decimal128.fromString = function (string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (string.length >= 7000) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if (!stringMatch && !infMatch && !nanMatch || string.length === 0) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Get the negative or positive sign - if (string[index] === '+' || string[index] === '-') { - isNegative = string[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] !== '.') { - if (string[index] === 'i' || string[index] === 'I') { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] === 'N') { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] === '.') { - if (string[index] === '.') { - if (sawRadix) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Read exponent if exists - if (string[index] === 'e' || string[index] === 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent !== 0 && significantDigits !== 1) { - while (string[firstNonZero + significantDigits - 1] === '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit === 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent === EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1; - - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = new Buffer(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = dec.low.low_ >> 8 & 0xff; - buffer[index++] = dec.low.low_ >> 16 & 0xff; - buffer[index++] = dec.low.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = dec.low.high_ >> 8 & 0xff; - buffer[index++] = dec.low.high_ >> 16 & 0xff; - buffer[index++] = dec.low.high_ >> 24 & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = dec.high.low_ >> 8 & 0xff; - buffer[index++] = dec.high.low_ >> 16 & 0xff; - buffer[index++] = dec.high.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = dec.high.high_ >> 8 & 0xff; - buffer[index++] = dec.high.high_ >> 16 & 0xff; - buffer[index++] = dec.high.high_ >> 24 & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); - }; - - // Extract least significant 5 bits - var COMBINATION_MASK = 0x1f; - // Extract least significant 14 bits - var EXPONENT_MASK = 0x3fff; - // Value of combination field for Inf - var COMBINATION_INFINITY = 30; - // Value of combination field for NaN - var COMBINATION_NAN = 31; - // Value of combination field for NaN - // var COMBINATION_SNAN = 32; - // decimal128 exponent bias - EXPONENT_BIAS = 6176; - - /** - * Create a string representation of the raw Decimal128 value - * - * @method - * @return {string} returns a Decimal128 string representation. - */ - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - i; - var j, k; - - // Output string - var string = []; - - // Unpack index - index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack the high 64bits into a long - midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack index - index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = high >> 26 & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = high >> 15 & EXPONENT_MASK; - significand_msb = 0x08 + (high >> 14 & 0x01); - } - } else { - significand_msb = high >> 14 & 0x07; - biased_exponent = high >> 17 & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); - }; - - Decimal128.prototype.toJSON = function () { - return { $numberDecimal: this.toString() }; - }; - - module.exports = Decimal128; - module.exports.Decimal128 = Decimal128; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) - -/***/ }), -/* 347 */ -/***/ (function(module, exports) { - - /** - * 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; - -/***/ }), -/* 348 */ -/***/ (function(module, exports) { - - /** - * 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; - -/***/ }), -/* 349 */ -/***/ (function(module, exports) { - - /** - * 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; - -/***/ }), -/* 350 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - * @ignore - */ - - // Test if we're in Node via presence of "global" not absence of "window" - // to support hybrid environments like Electron - if (typeof global !== 'undefined') { - var Buffer = __webpack_require__(329).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); - - if (buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer)) { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - - 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 { - 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, offset, 'binary'); - 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 (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 (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; - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 351 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var Long = __webpack_require__(334).Long, - Double = __webpack_require__(335).Double, - Timestamp = __webpack_require__(336).Timestamp, - ObjectID = __webpack_require__(337).ObjectID, - Symbol = __webpack_require__(343).Symbol, - Code = __webpack_require__(345).Code, - MinKey = __webpack_require__(347).MinKey, - MaxKey = __webpack_require__(348).MaxKey, - Decimal128 = __webpack_require__(346), - Int32 = __webpack_require__(344), - DBRef = __webpack_require__(349).DBRef, - BSONRegExp = __webpack_require__(342).BSONRegExp, - Binary = __webpack_require__(350).Binary; - - var deserialize = function (buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error('corrupt bson message'); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); - }; - - var deserializeObject = function (buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - - if (!cacheFunctionsCrc32) var crc32 = null; - - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); - - // 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'); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - var done = false; - - // While we have more left data left keep parsing - // while (buffer[index + 1] !== 0) { - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // 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'); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType === BSON.BSON_DATA_STRING) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = new Buffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { - object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); - } else if (elementType === BSON.BSON_DATA_INT) { - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_DATE) { - 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; - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] === 1; - } else if (elementType === BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType === BSON.BSON_DATA_ARRAY) { - _index = index; - objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); - if (index !== stopIndex) throw new Error('corrupted array bson'); - } else if (elementType === BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType === BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType === BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = new Buffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType === BSON.BSON_DATA_BINARY) { - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // 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; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - 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; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - 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'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - 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'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (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('')); - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - 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'); - // Return the C string - source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - 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'); - // Return the C string - regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON.BSON_DATA_SYMBOL) { - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { - lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType === BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType === BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType === BSON.BSON_DATA_CODE) { - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - // 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 { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - - // Javascript function - functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - _index = index; - // Decode the size of the object document - objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - 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 { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = new Buffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser'); - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; - }; - - /** - * 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; - }; - - var BSON = {}; - - /** - * 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 = {}; - - /** - * 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_DBPOINTER - **/ - BSON.BSON_DATA_DBPOINTER = 12; - /** - * 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; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * 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; - - // 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. - - module.exports = deserialize; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) - -/***/ }), -/* 352 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var writeIEEE754 = __webpack_require__(353).writeIEEE754, - Long = __webpack_require__(334).Long, - MinKey = __webpack_require__(347).MinKey, - Map = __webpack_require__(333), - Binary = __webpack_require__(350).Binary; - - const normalizedFunctionString = __webpack_require__(354).normalizedFunctionString; - - // try { - // var _Buffer = Uint8Array; - // } catch (e) { - // _Buffer = Buffer; - // } - - var regexp = /\x00/; // eslint-disable-line no-control-regex - - // 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]'; - }; - - var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; - }; - - var serializeString = function (buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = size + 1 >> 24 & 0xff; - buffer[index + 2] = size + 1 >> 16 & 0xff; - buffer[index + 1] = size + 1 >> 8 & 0xff; - buffer[index] = size + 1 & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeNumber = function (buffer, key, value, index, isArray) { - // 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 = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // 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 - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // 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 - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // 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 - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // 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 serializeNull = function (buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeBoolean = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - }; - - var serializeDate = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // 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 (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // 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 serializeBSONRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeMinMax = function (buffer, key, value, index, isArray) { - // 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 = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeObjectId = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Ajust index - return index + 12; - }; - - var serializeBuffer = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // 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 (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - // Write size - return endIndex; - }; - - var serializeDecimal128 = function (buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; - }; - - var serializeLong = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // 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 serializeInt32 = function (buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // 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; - return index; - }; - - var serializeDouble = function (buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // 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 serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // 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(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // 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 end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - 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 - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; - }; - - var serializeBinary = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // 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) { - size = size - 4; - 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 (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - }; - - var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto(buffer, { - $ref: value.namespace, - $id: value.oid, - $db: value.db - }, false, index, depth + 1, serializeFunctions); - } else { - endIndex = serializeInto(buffer, { - $ref: value.namespace, - $id: value.oid - }, false, index, depth + 1, serializeFunctions); - } - - // 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 serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // 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 value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - var type = typeof value; - if (type === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (key !== '$db' && key !== '$ref' && key !== '$id') { - if (key.match(regexp) != null) { - // 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 (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - // } else if (value === undefined && ignoreUndefined === true) { - } else if (value === null || value === undefined && ignoreUndefined === false) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else { - // Did we provide a custom serialization method - 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'); - } - - // Iterate over all the keys - for (key in object) { - value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (key !== '$db' && key !== '$ref' && key !== '$id') { - if (key.match(regexp) != null) { - // 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 (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } - - // Remove the path - path.pop(); - - // 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; - }; - - var BSON = {}; - - /** - * 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 = {}); - - /** - * 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, deprecated - * - * @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; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * 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; - - // 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. - - module.exports = serializeInto; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) - -/***/ }), -/* 353 */ -/***/ (function(module, exports) { - - // 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; - -/***/ }), -/* 354 */ -/***/ (function(module, exports) { - - 'use strict'; - - /** - * Normalizes our expected stringified form of a function across versions of node - * @param {Function} fn The function to stringify - */ - - function normalizedFunctionString(fn) { - return fn.toString().replace(/function *\(/, 'function ('); - } - - module.exports = { - normalizedFunctionString: normalizedFunctionString - }; - -/***/ }), -/* 355 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var Long = __webpack_require__(334).Long, - Double = __webpack_require__(335).Double, - Timestamp = __webpack_require__(336).Timestamp, - ObjectID = __webpack_require__(337).ObjectID, - Symbol = __webpack_require__(343).Symbol, - BSONRegExp = __webpack_require__(342).BSONRegExp, - Code = __webpack_require__(345).Code, - Decimal128 = __webpack_require__(346), - MinKey = __webpack_require__(347).MinKey, - MaxKey = __webpack_require__(348).MaxKey, - DBRef = __webpack_require__(349).DBRef, - Binary = __webpack_require__(350).Binary; - - var normalizedFunctionString = __webpack_require__(354).normalizedFunctionString; - - // 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]'; - }; - - var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } 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, false, ignoreUndefined); - } - } - - return totalLength; - }; - - /** - * @ignore - * @api private - */ - function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); - } - } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); - } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else if (serializeFunctions) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1; - } - } - } - - return 0; - } - - var BSON = {}; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - // 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 = calculateObjectSize; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) - -/***/ }) -/******/ ]) -}); -; \ No newline at end of file diff --git a/node_modules/bson/browser_build/package.json b/node_modules/bson/browser_build/package.json deleted file mode 100644 index 980db7f95c43fbcd346a6655ab5197c66d5d0bad..0000000000000000000000000000000000000000 --- a/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../" -, "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/bson/index.js b/node_modules/bson/index.js deleted file mode 100644 index 6502552dbe7f46f96779db3910f0d7f07fce15b0..0000000000000000000000000000000000000000 --- a/node_modules/bson/index.js +++ /dev/null @@ -1,46 +0,0 @@ -var BSON = require('./lib/bson/bson'), - Binary = require('./lib/bson/binary'), - Code = require('./lib/bson/code'), - DBRef = require('./lib/bson/db_ref'), - Decimal128 = require('./lib/bson/decimal128'), - Double = require('./lib/bson/double'), - Int32 = require('./lib/bson/int_32'), - Long = require('./lib/bson/long'), - Map = require('./lib/bson/map'), - MaxKey = require('./lib/bson/max_key'), - MinKey = require('./lib/bson/min_key'), - ObjectId = require('./lib/bson/objectid'), - BSONRegExp = require('./lib/bson/regexp'), - Symbol = require('./lib/bson/symbol'), - Timestamp = require('./lib/bson/timestamp'); - -// 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. - -// Add BSON types to function creation -BSON.Binary = Binary; -BSON.Code = Code; -BSON.DBRef = DBRef; -BSON.Decimal128 = Decimal128; -BSON.Double = Double; -BSON.Int32 = Int32; -BSON.Long = Long; -BSON.Map = Map; -BSON.MaxKey = MaxKey; -BSON.MinKey = MinKey; -BSON.ObjectId = ObjectId; -BSON.ObjectID = ObjectId; -BSON.BSONRegExp = BSONRegExp; -BSON.Symbol = Symbol; -BSON.Timestamp = Timestamp; - -// Return the BSON -module.exports = BSON; diff --git a/node_modules/bson/lib/bson/binary.js b/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index f3f695dad5af9681adba04aaa8f36cab494b4989..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,382 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ - -// Test if we're in Node via presence of "global" not absence of "window" -// to support hybrid environments like Electron -if (typeof global !== '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); - - if ( - buffer != null && - !(typeof buffer === 'string') && - !Buffer.isBuffer(buffer) && - !(buffer instanceof Uint8Array) && - !Array.isArray(buffer) - ) { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - - 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 { - 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, offset, 'binary'); - 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 (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 (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; diff --git a/node_modules/bson/lib/bson/bson.js b/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 956f152240f4f645546d8e39267cdaee69040813..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,385 +0,0 @@ -'use strict'; - -var Map = require('./map'), - Long = require('./long'), - Double = require('./double'), - Timestamp = require('./timestamp'), - ObjectID = require('./objectid'), - BSONRegExp = require('./regexp'), - Symbol = require('./symbol'), - Int32 = require('./int_32'), - Code = require('./code'), - Decimal128 = require('./decimal128'), - MinKey = require('./min_key'), - MaxKey = require('./max_key'), - DBRef = require('./db_ref'), - Binary = require('./binary'); - -// Parts of the parser -var deserialize = require('./parser/deserializer'), - serializer = require('./parser/serializer'), - calculateObjectSize = require('./parser/calculate_size'); - -/** - * @ignore - * @api private - */ -// Default Max Size -var MAXSIZE = 1024 * 1024 * 17; - -// Current Internal Temporary Serialization Buffer -var buffer = new Buffer(MAXSIZE); - -var BSON = function() {}; - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = - typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = new Buffer(minInternalBufferSize); - } - - // Attempt to serialize - var serializationIndex = serializer( - buffer, - object, - checkKeys, - 0, - 0, - serializeFunctions, - ignoreUndefined, - [] - ); - // Create the final buffer - var finishedBuffer = new Buffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -}; - -/** - * 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 {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer( - finalBuffer, - object, - checkKeys, - startIndex || 0, - 0, - serializeFunctions, - ignoreUndefined - ); - - // Return the index - return serializationIndex - 1; -}; - -/** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(buffer, options) { - return deserialize(buffer, options); -}; - -/** - * 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} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, options) { - options = options || {}; - - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); -}; - -/** - * Deserialize stream data as BSON documents. - * - * @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. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @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 -) { - 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] = this.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; -}; - -/** - * @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 -module.exports = BSON; -module.exports.Code = Code; -module.exports.Map = Map; -module.exports.Symbol = Symbol; -module.exports.BSON = BSON; -module.exports.DBRef = DBRef; -module.exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.Long = Long; -module.exports.Timestamp = Timestamp; -module.exports.Double = Double; -module.exports.Int32 = Int32; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; -module.exports.BSONRegExp = BSONRegExp; -module.exports.Decimal128 = Decimal128; diff --git a/node_modules/bson/lib/bson/code.js b/node_modules/bson/lib/bson/code.js deleted file mode 100644 index c2984cd5ab8852c1c7fc6e7c19598305142a2a91..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 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; -}; - -/** - * @ignore - */ -Code.prototype.toJSON = function() { - return { scope: this.scope, code: this.code }; -}; - -module.exports = Code; -module.exports.Code = Code; diff --git a/node_modules/bson/lib/bson/db_ref.js b/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index f95795b1cf3d90a634b65e459261f044fd4408b4..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 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; diff --git a/node_modules/bson/lib/bson/decimal128.js b/node_modules/bson/lib/bson/decimal128.js deleted file mode 100644 index 1dc2f00365e5007126d1a6c45dc00f23b51a6dfb..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/decimal128.js +++ /dev/null @@ -1,818 +0,0 @@ -'use strict'; - -var Long = require('./long'); - -var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - -var EXPONENT_MAX = 6111; -var EXPONENT_MIN = -6176; -var EXPONENT_BIAS = 6176; -var MAX_DIGITS = 34; - -// Nan value bits as 32 bit values (due to lack of longs) -var NAN_BUFFER = [ - 0x7c, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); -// Infinity value bits 32 bit values (due to lack of longs) -var INF_NEGATIVE_BUFFER = [ - 0xf8, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); -var INF_POSITIVE_BUFFER = [ - 0x78, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); - -var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - -// Detect if the value is a digit -var isDigit = function(value) { - return !isNaN(parseInt(value, 10)); -}; - -// Divide two uint128 values -var divideu128 = function(value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; -}; - -// Multiply two Long values and return the 128 bit value -var multiply64x2 = function(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; -}; - -var lessThan = function(left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; -}; - -// var longtoHex = function(value) { -// var buffer = new Buffer(8); -// var index = 0; -// // Encode the low 64 bits of the decimal -// // Encode low bits -// buffer[index++] = value.low_ & 0xff; -// buffer[index++] = (value.low_ >> 8) & 0xff; -// buffer[index++] = (value.low_ >> 16) & 0xff; -// buffer[index++] = (value.low_ >> 24) & 0xff; -// // Encode high bits -// buffer[index++] = value.high_ & 0xff; -// buffer[index++] = (value.high_ >> 8) & 0xff; -// buffer[index++] = (value.high_ >> 16) & 0xff; -// buffer[index++] = (value.high_ >> 24) & 0xff; -// return buffer.reverse().toString('hex'); -// }; - -// var int32toHex = function(value) { -// var buffer = new Buffer(4); -// var index = 0; -// // Encode the low 64 bits of the decimal -// // Encode low bits -// buffer[index++] = value & 0xff; -// buffer[index++] = (value >> 8) & 0xff; -// buffer[index++] = (value >> 16) & 0xff; -// buffer[index++] = (value >> 24) & 0xff; -// return buffer.reverse().toString('hex'); -// }; - -/** - * A class representation of the BSON Decimal128 type. - * - * @class - * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. - * @return {Double} - */ -var Decimal128 = function(bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; -}; - -/** - * Create a Decimal128 instance from a string representation - * - * @method - * @param {string} string a numeric string representation. - * @return {Decimal128} returns a Decimal128 instance. - */ -Decimal128.fromString = function(string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (string.length >= 7000) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Get the negative or positive sign - if (string[index] === '+' || string[index] === '-') { - isNegative = string[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] !== '.') { - if (string[index] === 'i' || string[index] === 'I') { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] === 'N') { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] === '.') { - if (string[index] === '.') { - if (sawRadix) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Read exponent if exists - if (string[index] === 'e' || string[index] === 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(new Buffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent !== 0 && significantDigits !== 1) { - while (string[firstNonZero + significantDigits - 1] === '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit === 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent === EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1; - - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128( - new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) - ); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if ( - significand.high - .shiftRightUnsigned(49) - .and(Long.fromNumber(1)) - .equals(Long.fromNumber) - ) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or( - Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) - ); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = new Buffer(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = (dec.low.low_ >> 8) & 0xff; - buffer[index++] = (dec.low.low_ >> 16) & 0xff; - buffer[index++] = (dec.low.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = (dec.low.high_ >> 8) & 0xff; - buffer[index++] = (dec.low.high_ >> 16) & 0xff; - buffer[index++] = (dec.low.high_ >> 24) & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = (dec.high.low_ >> 8) & 0xff; - buffer[index++] = (dec.high.low_ >> 16) & 0xff; - buffer[index++] = (dec.high.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = (dec.high.high_ >> 8) & 0xff; - buffer[index++] = (dec.high.high_ >> 16) & 0xff; - buffer[index++] = (dec.high.high_ >> 24) & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); -}; - -// Extract least significant 5 bits -var COMBINATION_MASK = 0x1f; -// Extract least significant 14 bits -var EXPONENT_MASK = 0x3fff; -// Value of combination field for Inf -var COMBINATION_INFINITY = 30; -// Value of combination field for NaN -var COMBINATION_NAN = 31; -// Value of combination field for NaN -// var COMBINATION_SNAN = 32; -// decimal128 exponent bias -EXPONENT_BIAS = 6176; - -/** - * Create a string representation of the raw Decimal128 value - * - * @method - * @return {string} returns a Decimal128 string representation. - */ -Decimal128.prototype.toString = function() { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - i; - var j, k; - - // Output string - var string = []; - - // Unpack index - index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - midl = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack the high 64bits into a long - midh = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - high = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack index - index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = (high >> 26) & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if ( - significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0 - ) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); -}; - -Decimal128.prototype.toJSON = function() { - return { $numberDecimal: this.toString() }; -}; - -module.exports = Decimal128; -module.exports.Decimal128 = Decimal128; diff --git a/node_modules/bson/lib/bson/double.js b/node_modules/bson/lib/bson/double.js deleted file mode 100644 index 523c21f88f0d51d9061568d34de4a5cbf9811bdf..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 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; diff --git a/node_modules/bson/lib/bson/float_parser.js b/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 0054a2f66507e756944ec484c2bc11a5a51c2b32..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,124 +0,0 @@ -// 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; diff --git a/node_modules/bson/lib/bson/int_32.js b/node_modules/bson/lib/bson/int_32.js deleted file mode 100644 index 85dbdec61e24d6a9b8763b47cbdb65ca0881100b..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/int_32.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of a BSON Int32 type. - * - * @class - * @param {number} value the number we want to represent as an int32. - * @return {Int32} - */ -var Int32 = function(value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; -}; - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ -Int32.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Int32.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Int32; -module.exports.Int32 = Int32; diff --git a/node_modules/bson/lib/bson/long.js b/node_modules/bson/lib/bson/long.js deleted file mode 100644 index 78215aa34f565fbaf2554a5a4c1c564655149091..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,851 +0,0 @@ -// 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)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - 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; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - 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; diff --git a/node_modules/bson/lib/bson/map.js b/node_modules/bson/lib/bson/map.js deleted file mode 100644 index 7edb4f2a1f35baf149e2512291ca6715754d7cd9..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/map.js +++ /dev/null @@ -1,128 +0,0 @@ -'use strict'; - -// We have an ES6 Map available, return the native instance -if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; -} else { - // We will return a polyfill - var Map = function(array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function() { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function(key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function(callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function(key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function(key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function(key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function() { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; -} diff --git a/node_modules/bson/lib/bson/max_key.js b/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index eebca7bc6104dad80ae78fc274cd0ab6b1200d3e..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * 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; diff --git a/node_modules/bson/lib/bson/min_key.js b/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 15f45228d371998a091a7b77834f560a2bc41522..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * 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; diff --git a/node_modules/bson/lib/bson/objectid.js b/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index f76ecbb883726987053397892f229edeef4b5165..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,387 +0,0 @@ -// Custom inspect property name / symbol. -var inspect = 'inspect'; - -/** - * 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}$'); - -// Check if buffer exists -try { - if (Buffer && Buffer.from) { - var hasBufferType = true; - inspect = require('util').inspect.custom || 'inspect'; - } -} catch (err) { - hasBufferType = false; -} - -/** -* 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) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if (id == null || typeof id === 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - 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 && hasBufferType) { - return new ObjectID(new Buffer(id, 'hex')); - } else if (valid && typeof id === 'string' && id.length === 24) { - return ObjectID.createFromHexString(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); -}; - -// 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 = ''; - if (!this.id || !this.id.length) { - throw new Error( - 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + - JSON.stringify(this.id) + - ']' - ); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return 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 buffer used in ObjectID's -* -* @method -* @param {number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {Buffer} return the 12 byte id buffer string. -*/ -ObjectID.prototype.generate = function(time) { - if ('number' !== typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = - (typeof process === 'undefined' || process.pid === 1 - ? Math.floor(Math.random() * 100000) - : process.pid) % 0xffff; - var inc = this.get_inc(); - // Buffer used - var buffer = new Buffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = (MACHINE_ID >> 8) & 0xff; - buffer[4] = (MACHINE_ID >> 16) & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = (pid >> 8) & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - // Return the buffer - return buffer; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @param {String} format The Buffer toString format parameter. -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toString = function(format) { - // Is the id a buffer then use the buffer toString method to return the format - if (this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - 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) { - // var id; - - if (otherId instanceof ObjectID) { - return this.toString() === otherId.toString(); - } else if ( - typeof otherId === 'string' && - ObjectID.isValid(otherId) && - otherId.length === 12 && - this.id instanceof _Buffer - ) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } -}; - -/** -* 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(); - var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; -}; - -/** -* @ignore -*/ -ObjectID.index = ~~(Math.random() * 0xffffff); - -/** -* @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 buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Return the new objectId - return new ObjectID(buffer); -}; - -// Lookup tables -//var encodeLookup = '0123456789abcdef'.split(''); -var decodeLookup = []; -i = 0; -while (i < 10) decodeLookup[0x30 + i] = i++; -while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - -var _Buffer = Buffer; -var convertToHex = function(bytes) { - return bytes.toString('hex'); -}; - -/** -* 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(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || (string != null && string.length !== 24)) { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - // Use Buffer.from method if available - if (hasBufferType) return new ObjectID(new Buffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); -}; - -/** -* 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 (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (id.toHexString) { - return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); - } - - return false; -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, 'generationTime', { - enumerable: true, - get: function() { - return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); - }, - set: function(value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = (value >> 8) & 0xff; - this.id[1] = (value >> 16) & 0xff; - this.id[0] = (value >> 24) & 0xff; - } -}); - -/** - * Expose. - */ -module.exports = ObjectID; -module.exports.ObjectID = ObjectID; -module.exports.ObjectId = ObjectID; diff --git a/node_modules/bson/lib/bson/parser/calculate_size.js b/node_modules/bson/lib/bson/parser/calculate_size.js deleted file mode 100644 index f174519daa92f9863d2132bb24c4df6022aaf5ae..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/parser/calculate_size.js +++ /dev/null @@ -1,255 +0,0 @@ -'use strict'; - -var Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - BSONRegExp = require('../regexp').BSONRegExp, - Code = require('../code').Code, - Decimal128 = require('../decimal128'), - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - DBRef = require('../db_ref').DBRef, - Binary = require('../binary').Binary; - -var normalizedFunctionString = require('./utils').normalizedFunctionString; - -// 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]'; -}; - -var calculateObjectSize = function calculateObjectSize( - object, - serializeFunctions, - ignoreUndefined -) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement( - i.toString(), - object[i], - serializeFunctions, - true, - ignoreUndefined - ); - } - } 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, false, ignoreUndefined); - } - } - - return totalLength; -}; - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return ( - (name != null ? 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) - ); - } - } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) - ); - } else if ( - value instanceof RegExp || - Object.prototype.toString.call(value) === '[object RegExp]' - ) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.pattern, 'utf8') + - 1 + - Buffer.byteLength(value.options, 'utf8') + - 1 - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize(value, serializeFunctions, ignoreUndefined) + - 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 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 ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else if (serializeFunctions) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 - ); - } - } - } - - return 0; -} - -var BSON = {}; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -// 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 = calculateObjectSize; diff --git a/node_modules/bson/lib/bson/parser/deserializer.js b/node_modules/bson/lib/bson/parser/deserializer.js deleted file mode 100644 index b7f45d7694e0889a46da8522826dd87f6f6b0303..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/parser/deserializer.js +++ /dev/null @@ -1,780 +0,0 @@ -'use strict'; - -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, - Decimal128 = require('../decimal128'), - Int32 = require('../int_32'), - DBRef = require('../db_ref').DBRef, - BSONRegExp = require('../regexp').BSONRegExp, - Binary = require('../binary').Binary; - -var deserialize = function(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error('corrupt bson message'); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); -}; - -var deserializeObject = function(buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = - options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - - if (!cacheFunctionsCrc32) var crc32 = null; - - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); - - // 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'); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - var done = false; - - // While we have more left data left keep parsing - // while (buffer[index + 1] !== 0) { - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // 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'); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType === BSON.BSON_DATA_STRING) { - var stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = new Buffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { - object[name] = new Int32( - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) - ); - } else if (elementType === BSON.BSON_DATA_INT) { - object[name] = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_DATE) { - 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); - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] === 1; - } else if (elementType === BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new Error('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType === BSON.BSON_DATA_ARRAY) { - _index = index; - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); - if (index !== stopIndex) throw new Error('corrupted array bson'); - } else if (elementType === BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType === BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType === BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - object[name] = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } else { - object[name] = long; - } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = new Buffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType === BSON.BSON_DATA_BINARY) { - var binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // 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); - if (binarySize < 0) - throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - 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); - if (binarySize < 0) - throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - 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'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - 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'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (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('')); - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - 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'); - // Return the C string - source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - 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'); - // Return the C string - regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON.BSON_DATA_SYMBOL) { - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { - lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType === BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType === BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType === BSON.BSON_DATA_CODE) { - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - // 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 { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - - // Javascript function - functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - _index = index; - // Decode the size of the object document - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - 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 { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = new Buffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error( - 'Detected unknown BSON type ' + - elementType.toString(16) + - ' for fieldname "' + - name + - '", are you using the latest BSON parser' - ); - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; -}; - -/** - * 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; -}; - -var BSON = {}; - -/** - * 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 = {}); - -/** - * 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_DBPOINTER - **/ -BSON.BSON_DATA_DBPOINTER = 12; -/** - * 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; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * 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; - -// 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. - -module.exports = deserialize; diff --git a/node_modules/bson/lib/bson/parser/serializer.js b/node_modules/bson/lib/bson/parser/serializer.js deleted file mode 100644 index bd3e12a51596aab249a6f9c0b2c45e092091c111..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/parser/serializer.js +++ /dev/null @@ -1,1183 +0,0 @@ -'use strict'; - -var writeIEEE754 = require('../float_parser').writeIEEE754, - Long = require('../long').Long, - MinKey = require('../min_key').MinKey, - Map = require('../map'), - Binary = require('../binary').Binary; - -var normalizedFunctionString = require('./utils').normalizedFunctionString; - -// try { -// var _Buffer = Uint8Array; -// } catch (e) { -// _Buffer = Buffer; -// } - -var regexp = /\x00/; // eslint-disable-line no-control-regex -var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; - -// 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]'; -}; - -var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -}; - -var serializeString = function(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -}; - -var serializeNumber = function(buffer, key, value, index, isArray) { - // 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 = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // 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 - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // 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 - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // 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 - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // 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 serializeNull = function(buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -}; - -var serializeBoolean = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -}; - -var serializeDate = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // 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(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // 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 serializeBSONRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = - index + - buffer.write( - value.options - .split('') - .sort() - .join(''), - index, - 'utf8' - ); - // Add ending zero - buffer[index++] = 0x00; - return index; -}; - -var serializeMinMax = function(buffer, key, value, index, isArray) { - // 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 = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -}; - -var serializeObjectId = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Ajust index - return index + 12; -}; - -var serializeBuffer = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // 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( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - isArray, - path -) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto( - buffer, - value, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined, - path - ); - // Pop stack - path.pop(); - // Write size - return endIndex; -}; - -var serializeDecimal128 = function(buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; -}; - -var serializeLong = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // 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 serializeInt32 = function(buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // 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; - return index; -}; - -var serializeDouble = function(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // 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 serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -}; - -var serializeCode = function( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - isArray -) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // 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(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // 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 end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto( - buffer, - value.scope, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined - ); - 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 - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; -}; - -var serializeBinary = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // 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) { - size = size - 4; - 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(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -}; - -var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto( - buffer, - { - $ref: value.namespace, - $id: value.oid, - $db: value.db - }, - false, - index, - depth + 1, - serializeFunctions - ); - } else { - endIndex = serializeInto( - buffer, - { - $ref: value.namespace, - $id: value.oid - }, - false, - index, - depth + 1, - serializeFunctions - ); - } - - // 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 serializeInto = function serializeInto( - buffer, - object, - checkKeys, - startingIndex, - depth, - serializeFunctions, - ignoreUndefined, - path -) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // 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 value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - var type = typeof value; - if (type === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - true - ); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true - ); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // 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 (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - // } else if (value === undefined && ignoreUndefined === true) { - } else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else { - // Did we provide a custom serialization method - 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'); - } - - // Iterate over all the keys - for (key in object) { - value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // 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 (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } - - // Remove the path - path.pop(); - - // 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; -}; - -var BSON = {}; - -/** - * 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 = {}); - -/** - * 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, deprecated - * - * @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; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * 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; - -// 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. - -module.exports = serializeInto; diff --git a/node_modules/bson/lib/bson/parser/utils.js b/node_modules/bson/lib/bson/parser/utils.js deleted file mode 100644 index 6b8395f2383a99af78dc32ae9ea2163866ed17ae..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/parser/utils.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -/** - * Normalizes our expected stringified form of a function across versions of node - * @param {Function} fn The function to stringify - */ -function normalizedFunctionString(fn) { - return fn.toString().replace(/function *\(/, 'function ('); -} - -module.exports = { - normalizedFunctionString: normalizedFunctionString -}; - diff --git a/node_modules/bson/lib/bson/regexp.js b/node_modules/bson/lib/bson/regexp.js deleted file mode 100644 index 108f016665d5ed283d143528d8cfd111a835061b..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/regexp.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ -function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if ( - !( - this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u' - ) - ) { - throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); - } - } -} - -module.exports = BSONRegExp; -module.exports.BSONRegExp = BSONRegExp; diff --git a/node_modules/bson/lib/bson/symbol.js b/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index ba20cabea0350660ed650981e758d9c2e278e041..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,50 +0,0 @@ -// Custom inspect property name / symbol. -var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; - -/** - * 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; diff --git a/node_modules/bson/lib/bson/timestamp.js b/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index dc61a6ccdb4cf570ebfbe6d511722e0565aa60a2..0000000000000000000000000000000000000000 --- a/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,854 +0,0 @@ -// 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)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - 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; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - 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; diff --git a/node_modules/bson/package.json b/node_modules/bson/package.json deleted file mode 100644 index 11e3badb203b6a9ebd930a0850566d4d6db7482c..0000000000000000000000000000000000000000 --- a/node_modules/bson/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "_from": "bson@~1.1.0", - "_id": "bson@1.1.0", - "_inBundle": false, - "_integrity": "sha512-9Aeai9TacfNtWXOYarkFJRW2CWo+dRon+fuLZYJmvLV3+MiUp0bEI6IAZfXEIg7/Pl/7IWlLaDnhzTsD81etQA==", - "_location": "/bson", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "bson@~1.1.0", - "name": "bson", - "escapedName": "bson", - "rawSpec": "~1.1.0", - "saveSpec": null, - "fetchSpec": "~1.1.0" - }, - "_requiredBy": [ - "/mongodb-core", - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/bson/-/bson-1.1.0.tgz", - "_shasum": "bee57d1fb6a87713471af4e32bcae36de814b5b0", - "_spec": "bson@~1.1.0", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongoose", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "browser": "lib/bson/bson.js", - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "bundleDependencies": false, - "config": { - "native": false - }, - "contributors": [], - "deprecated": false, - "description": "A bson parser for node.js and the browser", - "devDependencies": { - "babel-core": "^6.14.0", - "babel-loader": "^6.2.5", - "babel-polyfill": "^6.13.0", - "babel-preset-es2015": "^6.14.0", - "babel-preset-stage-0": "^6.5.0", - "babel-register": "^6.14.0", - "benchmark": "1.0.0", - "colors": "1.1.0", - "conventional-changelog-cli": "^1.3.5", - "nodeunit": "0.9.0", - "webpack": "^1.13.2", - "webpack-polyfills-plugin": "0.0.9" - }, - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "files": [ - "lib", - "index.js", - "browser_build", - "bower.json" - ], - "homepage": "https://github.com/mongodb/js-bson#readme", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "license": "Apache-2.0", - "main": "./index", - "name": "bson", - "repository": { - "type": "git", - "url": "git+https://github.com/mongodb/js-bson.git" - }, - "scripts": { - "build": "webpack --config ./webpack.dist.config.js", - "changelog": "conventional-changelog -p angular -i HISTORY.md -s", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", - "lint": "eslint lib test", - "test": "nodeunit ./test/node" - }, - "version": "1.1.0" -} diff --git a/node_modules/kareem/.travis.yml b/node_modules/kareem/.travis.yml deleted file mode 100644 index 39ddea7af3e77c42d2552752431e09d448b90a73..0000000000000000000000000000000000000000 --- a/node_modules/kareem/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: node_js -node_js: - - "9" - - "8" - - "7" - - "6" - - "5" - - "4" -script: "npm run-script test-travis" -after_script: "npm install coveralls@2.10.0 && cat ./coverage/lcov.info | coveralls" diff --git a/node_modules/kareem/CHANGELOG.md b/node_modules/kareem/CHANGELOG.md deleted file mode 100644 index aa011f40d2a80833c3b4a591970ce3fa3fcf3926..0000000000000000000000000000000000000000 --- a/node_modules/kareem/CHANGELOG.md +++ /dev/null @@ -1,790 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -<a name="2.3.0"></a> -## 2.3.0 (2018-09-24) - -* chore(release): 2.2.3 ([c8f2695](https://github.com/vkarpov15/kareem/commit/c8f2695)) -* chore(release): 2.2.4 ([a377a4f](https://github.com/vkarpov15/kareem/commit/a377a4f)) -* chore(release): 2.2.5 ([5a495e3](https://github.com/vkarpov15/kareem/commit/5a495e3)) -* fix(filter): copy async pres correctly with `filter()` ([1b1ed8a](https://github.com/vkarpov15/kareem/commit/1b1ed8a)), closes [Automattic/mongoose#3054](https://github.com/Automattic/mongoose/issues/3054) -* feat: add filter() function ([1f641f4](https://github.com/vkarpov15/kareem/commit/1f641f4)) -* feat: support storing options on pre and post hooks ([59220b9](https://github.com/vkarpov15/kareem/commit/59220b9)) - - - -<a name="2.2.3"></a> -## <small>2.2.3 (2018-09-10)</small> - -* chore: release 2.2.3 ([af653a3](https://github.com/vkarpov15/kareem/commit/af653a3)) - - - -<a name="2.2.2"></a> -## <small>2.2.2 (2018-09-10)</small> - -* chore: release 2.2.2 ([3f0144d](https://github.com/vkarpov15/kareem/commit/3f0144d)) -* fix: allow merge() to not clone ([e628d65](https://github.com/vkarpov15/kareem/commit/e628d65)) - - - -<a name="2.2.1"></a> -## <small>2.2.1 (2018-06-05)</small> - -* chore: release 2.2.1 ([4625a64](https://github.com/vkarpov15/kareem/commit/4625a64)) -* chore: remove lockfile from git ([7f3e4e6](https://github.com/vkarpov15/kareem/commit/7f3e4e6)) -* fix: handle numAsync correctly when merging ([fef8e7e](https://github.com/vkarpov15/kareem/commit/fef8e7e)) -* test: repro issue with not copying numAsync ([952d9db](https://github.com/vkarpov15/kareem/commit/952d9db)) - - - -<a name="2.2.0"></a> -## 2.2.0 (2018-06-05) - -* chore: release 2.2.0 ([ff9ad03](https://github.com/vkarpov15/kareem/commit/ff9ad03)) -* fix: use maps instead of objects for _pres and _posts so `toString()` doesn't get reported as having ([55df303](https://github.com/vkarpov15/kareem/commit/55df303)), closes [Automattic/mongoose#6538](https://github.com/Automattic/mongoose/issues/6538) - - - -<a name="2.1.0"></a> -## 2.1.0 (2018-05-16) - -* chore: release 2.1.0 ([ba5f1bc](https://github.com/vkarpov15/kareem/commit/ba5f1bc)) -* feat: add option to check wrapped function return value for promises ([c9d7dd1](https://github.com/vkarpov15/kareem/commit/c9d7dd1)) -* refactor: use const in wrap() ([0fc21f9](https://github.com/vkarpov15/kareem/commit/0fc21f9)) - - - -<a name="2.0.7"></a> -## <small>2.0.7 (2018-04-28)</small> - -* chore: release 2.0.7 ([0bf91e6](https://github.com/vkarpov15/kareem/commit/0bf91e6)) -* feat: add `hasHooks()` ([225f18d](https://github.com/vkarpov15/kareem/commit/225f18d)), closes [Automattic/mongoose#6385](https://github.com/Automattic/mongoose/issues/6385) - - - -<a name="2.0.6"></a> -## <small>2.0.6 (2018-03-22)</small> - -* chore: release 2.0.6 ([f3d406b](https://github.com/vkarpov15/kareem/commit/f3d406b)) -* fix(wrap): ensure fast path still wraps function in `nextTick()` for chaining ([7000494](https://github.com/vkarpov15/kareem/commit/7000494)), closes [Automattic/mongoose#6250](https://github.com/Automattic/mongoose/issues/6250) [dsanel/mongoose-delete#36](https://github.com/dsanel/mongoose-delete/issues/36) - - - -<a name="2.0.5"></a> -## <small>2.0.5 (2018-02-22)</small> - -* chore: release 2.0.5 ([3286612](https://github.com/vkarpov15/kareem/commit/3286612)) -* perf(createWrapper): don't create wrapper if there are no hooks ([5afc5b9](https://github.com/vkarpov15/kareem/commit/5afc5b9)), closes [Automattic/mongoose#6126](https://github.com/Automattic/mongoose/issues/6126) - - - -<a name="2.0.4"></a> -## <small>2.0.4 (2018-02-08)</small> - -* chore: release 2.0.4 ([2ab0293](https://github.com/vkarpov15/kareem/commit/2ab0293)) - - - -<a name="2.0.3"></a> -## <small>2.0.3 (2018-02-01)</small> - -* chore: release 2.0.3 ([3c1abe5](https://github.com/vkarpov15/kareem/commit/3c1abe5)) -* fix: use process.nextTick() re: Automattic/mongoose#6074 ([e5bfe33](https://github.com/vkarpov15/kareem/commit/e5bfe33)), closes [Automattic/mongoose#6074](https://github.com/Automattic/mongoose/issues/6074) - - - -<a name="2.0.2"></a> -## <small>2.0.2 (2018-01-24)</small> - -* chore: fix license ([a9d755c](https://github.com/vkarpov15/kareem/commit/a9d755c)), closes [#10](https://github.com/vkarpov15/kareem/issues/10) -* chore: release 2.0.2 ([fe87ab6](https://github.com/vkarpov15/kareem/commit/fe87ab6)) - - - -<a name="2.0.1"></a> -## <small>2.0.1 (2018-01-09)</small> - -* chore: release 2.0.1 with lockfile bump ([09c44fb](https://github.com/vkarpov15/kareem/commit/09c44fb)) - - - -<a name="2.0.0"></a> -## 2.0.0 (2018-01-09) - -* chore: bump marked re: security ([cc564a9](https://github.com/vkarpov15/kareem/commit/cc564a9)) -* chore: release 2.0.0 ([f511d1c](https://github.com/vkarpov15/kareem/commit/f511d1c)) - - - -<a name="2.0.0-rc5"></a> -## 2.0.0-rc5 (2017-12-23) - -* chore: fix build on node 4+5 ([6dac5a4](https://github.com/vkarpov15/kareem/commit/6dac5a4)) -* chore: fix built on node 4 + 5 again ([434ef0a](https://github.com/vkarpov15/kareem/commit/434ef0a)) -* chore: release 2.0.0-rc5 ([25a32ee](https://github.com/vkarpov15/kareem/commit/25a32ee)) - - - -<a name="2.0.0-rc4"></a> -## 2.0.0-rc4 (2017-12-22) - -* chore: release 2.0.0-rc4 ([49fc083](https://github.com/vkarpov15/kareem/commit/49fc083)) -* BREAKING CHANGE: deduplicate when merging hooks re: Automattic/mongoose#2945 ([d458573](https://github.com/vkarpov15/kareem/commit/d458573)), closes [Automattic/mongoose#2945](https://github.com/Automattic/mongoose/issues/2945) - - - -<a name="2.0.0-rc3"></a> -## 2.0.0-rc3 (2017-12-22) - -* chore: release 2.0.0-rc3 ([adaaa00](https://github.com/vkarpov15/kareem/commit/adaaa00)) -* feat: support returning promises from middleware functions ([05b4480](https://github.com/vkarpov15/kareem/commit/05b4480)), closes [Automattic/mongoose#3779](https://github.com/Automattic/mongoose/issues/3779) - - - -<a name="2.0.0-rc2"></a> -## 2.0.0-rc2 (2017-12-21) - -* chore: release 2.0.0-rc2 ([76325fa](https://github.com/vkarpov15/kareem/commit/76325fa)) -* fix: ensure next() and done() run in next tick ([6c20684](https://github.com/vkarpov15/kareem/commit/6c20684)) - - - -<a name="2.0.0-rc1"></a> -## 2.0.0-rc1 (2017-12-21) - -* chore: improve test coverage re: Automattic/mongoose#3232 ([7b45cf0](https://github.com/vkarpov15/kareem/commit/7b45cf0)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) -* chore: release 2.0.0-rc1 ([9b83f52](https://github.com/vkarpov15/kareem/commit/9b83f52)) -* BREAKING CHANGE: report sync exceptions as errors, only allow calling next() and done() once ([674adcc](https://github.com/vkarpov15/kareem/commit/674adcc)), closes [Automattic/mongoose#3483](https://github.com/Automattic/mongoose/issues/3483) - - - -<a name="2.0.0-rc0"></a> -## 2.0.0-rc0 (2017-12-17) - -* chore: release 2.0.0-rc0 ([16b44b5](https://github.com/vkarpov15/kareem/commit/16b44b5)) -* BREAKING CHANGE: drop support for node < 4 ([9cbb8c7](https://github.com/vkarpov15/kareem/commit/9cbb8c7)) -* BREAKING CHANGE: remove useLegacyPost and add several new features ([6dd8531](https://github.com/vkarpov15/kareem/commit/6dd8531)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) - - - -<a name="1.5.0"></a> -## 1.5.0 (2017-07-20) - -* chore: release 1.5.0 ([9c491a0](https://github.com/vkarpov15/kareem/commit/9c491a0)) -* fix: improve post error handlers results ([9928dd5](https://github.com/vkarpov15/kareem/commit/9928dd5)), closes [Automattic/mongoose#5466](https://github.com/Automattic/mongoose/issues/5466) - - - -<a name="1.4.2"></a> -## <small>1.4.2 (2017-07-06)</small> - -* chore: release 1.4.2 ([8d14ac5](https://github.com/vkarpov15/kareem/commit/8d14ac5)) -* fix: correct args re: Automattic/mongoose#5405 ([3f28ae6](https://github.com/vkarpov15/kareem/commit/3f28ae6)), closes [Automattic/mongoose#5405](https://github.com/Automattic/mongoose/issues/5405) - - - -<a name="1.4.1"></a> -## <small>1.4.1 (2017-04-25)</small> - -* chore: release 1.4.1 ([5ecf0c2](https://github.com/vkarpov15/kareem/commit/5ecf0c2)) -* fix: handle numAsyncPres with clone() ([c72e857](https://github.com/vkarpov15/kareem/commit/c72e857)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) -* test: repro #8 ([9b4d6b2](https://github.com/vkarpov15/kareem/commit/9b4d6b2)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) - - - -<a name="1.4.0"></a> -## 1.4.0 (2017-04-19) - -* chore: release 1.4.0 ([101c5f5](https://github.com/vkarpov15/kareem/commit/101c5f5)) -* feat: add merge() function ([285325e](https://github.com/vkarpov15/kareem/commit/285325e)) - - - -<a name="1.3.0"></a> -## 1.3.0 (2017-03-26) - -* chore: release 1.3.0 ([f3a9e50](https://github.com/vkarpov15/kareem/commit/f3a9e50)) -* feat: pass function args to execPre ([4dd466d](https://github.com/vkarpov15/kareem/commit/4dd466d)) - - - -<a name="1.2.1"></a> -## <small>1.2.1 (2017-02-03)</small> - -* chore: release 1.2.1 ([d97081f](https://github.com/vkarpov15/kareem/commit/d97081f)) -* fix: filter out _kareemIgnored args for error handlers re: Automattic/mongoose#4925 ([ddc7aeb](https://github.com/vkarpov15/kareem/commit/ddc7aeb)), closes [Automattic/mongoose#4925](https://github.com/Automattic/mongoose/issues/4925) -* fix: make error handlers handle errors in pre hooks ([af38033](https://github.com/vkarpov15/kareem/commit/af38033)), closes [Automattic/mongoose#4927](https://github.com/Automattic/mongoose/issues/4927) - - - -<a name="1.2.0"></a> -## 1.2.0 (2017-01-02) - -* chore: release 1.2.0 ([033225c](https://github.com/vkarpov15/kareem/commit/033225c)) -* chore: upgrade deps ([f9e9a09](https://github.com/vkarpov15/kareem/commit/f9e9a09)) -* feat: add _kareemIgnore re: Automattic/mongoose#4836 ([7957771](https://github.com/vkarpov15/kareem/commit/7957771)), closes [Automattic/mongoose#4836](https://github.com/Automattic/mongoose/issues/4836) - - - -<a name="1.1.5"></a> -## <small>1.1.5 (2016-12-13)</small> - -* chore: release 1.1.5 ([1a9f684](https://github.com/vkarpov15/kareem/commit/1a9f684)) -* fix: correct field name ([04a0e9d](https://github.com/vkarpov15/kareem/commit/04a0e9d)) - - - -<a name="1.1.4"></a> -## <small>1.1.4 (2016-12-09)</small> - -* chore: release 1.1.4 ([ece401c](https://github.com/vkarpov15/kareem/commit/ece401c)) -* chore: run tests on node 6 ([e0cb1cb](https://github.com/vkarpov15/kareem/commit/e0cb1cb)) -* fix: only copy own properties in clone() ([dfe28ce](https://github.com/vkarpov15/kareem/commit/dfe28ce)), closes [#7](https://github.com/vkarpov15/kareem/issues/7) - - - -<a name="1.1.3"></a> -## <small>1.1.3 (2016-06-27)</small> - -* chore: release 1.1.3 ([87171c8](https://github.com/vkarpov15/kareem/commit/87171c8)) -* fix: couple more issues with arg processing ([c65f523](https://github.com/vkarpov15/kareem/commit/c65f523)) - - - -<a name="1.1.2"></a> -## <small>1.1.2 (2016-06-27)</small> - -* chore: release 1.1.2 ([8e102b6](https://github.com/vkarpov15/kareem/commit/8e102b6)) -* fix: add early return ([4feda4e](https://github.com/vkarpov15/kareem/commit/4feda4e)) - - - -<a name="1.1.1"></a> -## <small>1.1.1 (2016-06-27)</small> - -* chore: release 1.1.1 ([8bb3050](https://github.com/vkarpov15/kareem/commit/8bb3050)) -* fix: skip error handlers if no error ([0eb3a44](https://github.com/vkarpov15/kareem/commit/0eb3a44)) - - - -<a name="1.1.0"></a> -## 1.1.0 (2016-05-11) - -* chore: release 1.1.0 ([85332d9](https://github.com/vkarpov15/kareem/commit/85332d9)) -* chore: test on node 4 and node 5 ([1faefa1](https://github.com/vkarpov15/kareem/commit/1faefa1)) -* 100% coverage again ([c9aee4e](https://github.com/vkarpov15/kareem/commit/c9aee4e)) -* add support for error post hooks ([d378113](https://github.com/vkarpov15/kareem/commit/d378113)) -* basic setup for sync hooks #4 ([55aa081](https://github.com/vkarpov15/kareem/commit/55aa081)), closes [#4](https://github.com/vkarpov15/kareem/issues/4) -* proof of concept for error handlers ([e4a07d9](https://github.com/vkarpov15/kareem/commit/e4a07d9)) -* refactor out handleWrapError helper ([b19af38](https://github.com/vkarpov15/kareem/commit/b19af38)) - - - -<a name="1.0.1"></a> -## <small>1.0.1 (2015-05-10)</small> - -* Fix #1 ([de60dc6](https://github.com/vkarpov15/kareem/commit/de60dc6)), closes [#1](https://github.com/vkarpov15/kareem/issues/1) -* release 1.0.1 ([6971088](https://github.com/vkarpov15/kareem/commit/6971088)) -* Run tests on iojs in travis ([adcd201](https://github.com/vkarpov15/kareem/commit/adcd201)) -* support legacy post hook behavior in wrap() ([23fa74c](https://github.com/vkarpov15/kareem/commit/23fa74c)) -* Use node 0.12 in travis ([834689d](https://github.com/vkarpov15/kareem/commit/834689d)) - - - -<a name="1.0.0"></a> -## 1.0.0 (2015-01-28) - -* Tag 1.0.0 ([4c5a35a](https://github.com/vkarpov15/kareem/commit/4c5a35a)) - - - -<a name="0.0.8"></a> -## <small>0.0.8 (2015-01-27)</small> - -* Add clone function ([688bba7](https://github.com/vkarpov15/kareem/commit/688bba7)) -* Add jscs for style checking ([5c93149](https://github.com/vkarpov15/kareem/commit/5c93149)) -* Bump 0.0.8 ([03c0d2f](https://github.com/vkarpov15/kareem/commit/03c0d2f)) -* Fix jscs config, add gulp rules ([9989abf](https://github.com/vkarpov15/kareem/commit/9989abf)) -* fix Makefile typo ([1f7e61a](https://github.com/vkarpov15/kareem/commit/1f7e61a)) - - - -<a name="0.0.7"></a> -## <small>0.0.7 (2015-01-04)</small> - -* Bump 0.0.7 ([98ef173](https://github.com/vkarpov15/kareem/commit/98ef173)) -* fix LearnBoost/mongoose#2553 - use null instead of undefined for err ([9157b48](https://github.com/vkarpov15/kareem/commit/9157b48)), closes [LearnBoost/mongoose#2553](https://github.com/LearnBoost/mongoose/issues/2553) -* Regenerate docs ([2331cdf](https://github.com/vkarpov15/kareem/commit/2331cdf)) - - - -<a name="0.0.6"></a> -## <small>0.0.6 (2015-01-01)</small> - -* Update docs and bump 0.0.6 ([92c12a7](https://github.com/vkarpov15/kareem/commit/92c12a7)) - - - -<a name="0.0.5"></a> -## <small>0.0.5 (2015-01-01)</small> - -* Add coverage rule to Makefile ([825a91c](https://github.com/vkarpov15/kareem/commit/825a91c)) -* Add coveralls to README ([fb52369](https://github.com/vkarpov15/kareem/commit/fb52369)) -* Add coveralls to travis ([93f6f15](https://github.com/vkarpov15/kareem/commit/93f6f15)) -* Add createWrapper() function ([ea77741](https://github.com/vkarpov15/kareem/commit/ea77741)) -* Add istanbul code coverage ([6eceeef](https://github.com/vkarpov15/kareem/commit/6eceeef)) -* Add some more comments for examples ([c5b0c6f](https://github.com/vkarpov15/kareem/commit/c5b0c6f)) -* Add travis ([e6dcb06](https://github.com/vkarpov15/kareem/commit/e6dcb06)) -* Add travis badge to docs ([ad8c9b3](https://github.com/vkarpov15/kareem/commit/ad8c9b3)) -* Add wrap() tests, 100% coverage ([6945be4](https://github.com/vkarpov15/kareem/commit/6945be4)) -* Better test coverage for execPost ([d9ad539](https://github.com/vkarpov15/kareem/commit/d9ad539)) -* Bump 0.0.5 ([69875b1](https://github.com/vkarpov15/kareem/commit/69875b1)) -* Docs fix ([15b7098](https://github.com/vkarpov15/kareem/commit/15b7098)) -* Fix silly mistake in docs generation ([50373eb](https://github.com/vkarpov15/kareem/commit/50373eb)) -* Fix typo in readme ([fec4925](https://github.com/vkarpov15/kareem/commit/fec4925)) -* Linkify travis badge ([92b25fe](https://github.com/vkarpov15/kareem/commit/92b25fe)) -* Make travis run coverage ([747157b](https://github.com/vkarpov15/kareem/commit/747157b)) -* Move travis status badge ([d52e89b](https://github.com/vkarpov15/kareem/commit/d52e89b)) -* Quick fix for coverage ([50bbddb](https://github.com/vkarpov15/kareem/commit/50bbddb)) -* Typo fix ([adea794](https://github.com/vkarpov15/kareem/commit/adea794)) - - - -<a name="0.0.4"></a> -## <small>0.0.4 (2014-12-13)</small> - -* Bump 0.0.4, run docs generation ([51a15fe](https://github.com/vkarpov15/kareem/commit/51a15fe)) -* Use correct post parameters in wrap() ([9bb5da3](https://github.com/vkarpov15/kareem/commit/9bb5da3)) - - - -<a name="0.0.3"></a> -## <small>0.0.3 (2014-12-12)</small> - -* Add npm test script, fix small bug with args not getting passed through post ([49e3e68](https://github.com/vkarpov15/kareem/commit/49e3e68)) -* Bump 0.0.3 ([65621d8](https://github.com/vkarpov15/kareem/commit/65621d8)) -* Update readme ([901388b](https://github.com/vkarpov15/kareem/commit/901388b)) - - - -<a name="0.0.2"></a> -## <small>0.0.2 (2014-12-12)</small> - -* Add github repo and bump 0.0.2 ([59db8be](https://github.com/vkarpov15/kareem/commit/59db8be)) - - - -<a name="0.0.1"></a> -## <small>0.0.1 (2014-12-12)</small> - -* Add basic docs ([ad29ea4](https://github.com/vkarpov15/kareem/commit/ad29ea4)) -* Add pre hooks ([2ffc356](https://github.com/vkarpov15/kareem/commit/2ffc356)) -* Add wrap function ([68c540c](https://github.com/vkarpov15/kareem/commit/68c540c)) -* Bump to version 0.0.1 ([a4bfd68](https://github.com/vkarpov15/kareem/commit/a4bfd68)) -* Initial commit ([4002458](https://github.com/vkarpov15/kareem/commit/4002458)) -* Initial deposit ([98fc489](https://github.com/vkarpov15/kareem/commit/98fc489)) -* Post hooks ([395b67c](https://github.com/vkarpov15/kareem/commit/395b67c)) -* Some basic setup work ([82df75e](https://github.com/vkarpov15/kareem/commit/82df75e)) -* Support sync pre hooks ([1cc1b9f](https://github.com/vkarpov15/kareem/commit/1cc1b9f)) -* Update package.json description ([978da18](https://github.com/vkarpov15/kareem/commit/978da18)) - - - -<a name="2.2.5"></a> -## <small>2.2.5 (2018-09-24)</small> - - - - -<a name="2.2.4"></a> -## <small>2.2.4 (2018-09-24)</small> - - - - -<a name="2.2.3"></a> -## <small>2.2.3 (2018-09-24)</small> - -* fix(filter): copy async pres correctly with `filter()` ([1b1ed8a](https://github.com/vkarpov15/kareem/commit/1b1ed8a)), closes [Automattic/mongoose#3054](https://github.com/Automattic/mongoose/issues/3054) -* feat: add filter() function ([1f641f4](https://github.com/vkarpov15/kareem/commit/1f641f4)) -* feat: support storing options on pre and post hooks ([59220b9](https://github.com/vkarpov15/kareem/commit/59220b9)) - - - -<a name="2.2.3"></a> -## <small>2.2.3 (2018-09-10)</small> - -* chore: release 2.2.3 ([af653a3](https://github.com/vkarpov15/kareem/commit/af653a3)) - - - -<a name="2.2.2"></a> -## <small>2.2.2 (2018-09-10)</small> - -* chore: release 2.2.2 ([3f0144d](https://github.com/vkarpov15/kareem/commit/3f0144d)) -* fix: allow merge() to not clone ([e628d65](https://github.com/vkarpov15/kareem/commit/e628d65)) - - - -<a name="2.2.1"></a> -## <small>2.2.1 (2018-06-05)</small> - -* chore: release 2.2.1 ([4625a64](https://github.com/vkarpov15/kareem/commit/4625a64)) -* chore: remove lockfile from git ([7f3e4e6](https://github.com/vkarpov15/kareem/commit/7f3e4e6)) -* fix: handle numAsync correctly when merging ([fef8e7e](https://github.com/vkarpov15/kareem/commit/fef8e7e)) -* test: repro issue with not copying numAsync ([952d9db](https://github.com/vkarpov15/kareem/commit/952d9db)) - - - -<a name="2.2.0"></a> -## 2.2.0 (2018-06-05) - -* chore: release 2.2.0 ([ff9ad03](https://github.com/vkarpov15/kareem/commit/ff9ad03)) -* fix: use maps instead of objects for _pres and _posts so `toString()` doesn't get reported as having ([55df303](https://github.com/vkarpov15/kareem/commit/55df303)), closes [Automattic/mongoose#6538](https://github.com/Automattic/mongoose/issues/6538) - - - -<a name="2.1.0"></a> -## 2.1.0 (2018-05-16) - -* chore: release 2.1.0 ([ba5f1bc](https://github.com/vkarpov15/kareem/commit/ba5f1bc)) -* feat: add option to check wrapped function return value for promises ([c9d7dd1](https://github.com/vkarpov15/kareem/commit/c9d7dd1)) -* refactor: use const in wrap() ([0fc21f9](https://github.com/vkarpov15/kareem/commit/0fc21f9)) - - - -<a name="2.0.7"></a> -## <small>2.0.7 (2018-04-28)</small> - -* chore: release 2.0.7 ([0bf91e6](https://github.com/vkarpov15/kareem/commit/0bf91e6)) -* feat: add `hasHooks()` ([225f18d](https://github.com/vkarpov15/kareem/commit/225f18d)), closes [Automattic/mongoose#6385](https://github.com/Automattic/mongoose/issues/6385) - - - -<a name="2.0.6"></a> -## <small>2.0.6 (2018-03-22)</small> - -* chore: release 2.0.6 ([f3d406b](https://github.com/vkarpov15/kareem/commit/f3d406b)) -* fix(wrap): ensure fast path still wraps function in `nextTick()` for chaining ([7000494](https://github.com/vkarpov15/kareem/commit/7000494)), closes [Automattic/mongoose#6250](https://github.com/Automattic/mongoose/issues/6250) [dsanel/mongoose-delete#36](https://github.com/dsanel/mongoose-delete/issues/36) - - - -<a name="2.0.5"></a> -## <small>2.0.5 (2018-02-22)</small> - -* chore: release 2.0.5 ([3286612](https://github.com/vkarpov15/kareem/commit/3286612)) -* perf(createWrapper): don't create wrapper if there are no hooks ([5afc5b9](https://github.com/vkarpov15/kareem/commit/5afc5b9)), closes [Automattic/mongoose#6126](https://github.com/Automattic/mongoose/issues/6126) - - - -<a name="2.0.4"></a> -## <small>2.0.4 (2018-02-08)</small> - -* chore: release 2.0.4 ([2ab0293](https://github.com/vkarpov15/kareem/commit/2ab0293)) - - - -<a name="2.0.3"></a> -## <small>2.0.3 (2018-02-01)</small> - -* chore: release 2.0.3 ([3c1abe5](https://github.com/vkarpov15/kareem/commit/3c1abe5)) -* fix: use process.nextTick() re: Automattic/mongoose#6074 ([e5bfe33](https://github.com/vkarpov15/kareem/commit/e5bfe33)), closes [Automattic/mongoose#6074](https://github.com/Automattic/mongoose/issues/6074) - - - -<a name="2.0.2"></a> -## <small>2.0.2 (2018-01-24)</small> - -* chore: fix license ([a9d755c](https://github.com/vkarpov15/kareem/commit/a9d755c)), closes [#10](https://github.com/vkarpov15/kareem/issues/10) -* chore: release 2.0.2 ([fe87ab6](https://github.com/vkarpov15/kareem/commit/fe87ab6)) - - - -<a name="2.0.1"></a> -## <small>2.0.1 (2018-01-09)</small> - -* chore: release 2.0.1 with lockfile bump ([09c44fb](https://github.com/vkarpov15/kareem/commit/09c44fb)) - - - -<a name="2.0.0"></a> -## 2.0.0 (2018-01-09) - -* chore: bump marked re: security ([cc564a9](https://github.com/vkarpov15/kareem/commit/cc564a9)) -* chore: release 2.0.0 ([f511d1c](https://github.com/vkarpov15/kareem/commit/f511d1c)) - - - -<a name="2.0.0-rc5"></a> -## 2.0.0-rc5 (2017-12-23) - -* chore: fix build on node 4+5 ([6dac5a4](https://github.com/vkarpov15/kareem/commit/6dac5a4)) -* chore: fix built on node 4 + 5 again ([434ef0a](https://github.com/vkarpov15/kareem/commit/434ef0a)) -* chore: release 2.0.0-rc5 ([25a32ee](https://github.com/vkarpov15/kareem/commit/25a32ee)) - - - -<a name="2.0.0-rc4"></a> -## 2.0.0-rc4 (2017-12-22) - -* chore: release 2.0.0-rc4 ([49fc083](https://github.com/vkarpov15/kareem/commit/49fc083)) -* BREAKING CHANGE: deduplicate when merging hooks re: Automattic/mongoose#2945 ([d458573](https://github.com/vkarpov15/kareem/commit/d458573)), closes [Automattic/mongoose#2945](https://github.com/Automattic/mongoose/issues/2945) - - - -<a name="2.0.0-rc3"></a> -## 2.0.0-rc3 (2017-12-22) - -* chore: release 2.0.0-rc3 ([adaaa00](https://github.com/vkarpov15/kareem/commit/adaaa00)) -* feat: support returning promises from middleware functions ([05b4480](https://github.com/vkarpov15/kareem/commit/05b4480)), closes [Automattic/mongoose#3779](https://github.com/Automattic/mongoose/issues/3779) - - - -<a name="2.0.0-rc2"></a> -## 2.0.0-rc2 (2017-12-21) - -* chore: release 2.0.0-rc2 ([76325fa](https://github.com/vkarpov15/kareem/commit/76325fa)) -* fix: ensure next() and done() run in next tick ([6c20684](https://github.com/vkarpov15/kareem/commit/6c20684)) - - - -<a name="2.0.0-rc1"></a> -## 2.0.0-rc1 (2017-12-21) - -* chore: improve test coverage re: Automattic/mongoose#3232 ([7b45cf0](https://github.com/vkarpov15/kareem/commit/7b45cf0)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) -* chore: release 2.0.0-rc1 ([9b83f52](https://github.com/vkarpov15/kareem/commit/9b83f52)) -* BREAKING CHANGE: report sync exceptions as errors, only allow calling next() and done() once ([674adcc](https://github.com/vkarpov15/kareem/commit/674adcc)), closes [Automattic/mongoose#3483](https://github.com/Automattic/mongoose/issues/3483) - - - -<a name="2.0.0-rc0"></a> -## 2.0.0-rc0 (2017-12-17) - -* chore: release 2.0.0-rc0 ([16b44b5](https://github.com/vkarpov15/kareem/commit/16b44b5)) -* BREAKING CHANGE: drop support for node < 4 ([9cbb8c7](https://github.com/vkarpov15/kareem/commit/9cbb8c7)) -* BREAKING CHANGE: remove useLegacyPost and add several new features ([6dd8531](https://github.com/vkarpov15/kareem/commit/6dd8531)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) - - - -<a name="1.5.0"></a> -## 1.5.0 (2017-07-20) - -* chore: release 1.5.0 ([9c491a0](https://github.com/vkarpov15/kareem/commit/9c491a0)) -* fix: improve post error handlers results ([9928dd5](https://github.com/vkarpov15/kareem/commit/9928dd5)), closes [Automattic/mongoose#5466](https://github.com/Automattic/mongoose/issues/5466) - - - -<a name="1.4.2"></a> -## <small>1.4.2 (2017-07-06)</small> - -* chore: release 1.4.2 ([8d14ac5](https://github.com/vkarpov15/kareem/commit/8d14ac5)) -* fix: correct args re: Automattic/mongoose#5405 ([3f28ae6](https://github.com/vkarpov15/kareem/commit/3f28ae6)), closes [Automattic/mongoose#5405](https://github.com/Automattic/mongoose/issues/5405) - - - -<a name="1.4.1"></a> -## <small>1.4.1 (2017-04-25)</small> - -* chore: release 1.4.1 ([5ecf0c2](https://github.com/vkarpov15/kareem/commit/5ecf0c2)) -* fix: handle numAsyncPres with clone() ([c72e857](https://github.com/vkarpov15/kareem/commit/c72e857)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) -* test: repro #8 ([9b4d6b2](https://github.com/vkarpov15/kareem/commit/9b4d6b2)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) - - - -<a name="1.4.0"></a> -## 1.4.0 (2017-04-19) - -* chore: release 1.4.0 ([101c5f5](https://github.com/vkarpov15/kareem/commit/101c5f5)) -* feat: add merge() function ([285325e](https://github.com/vkarpov15/kareem/commit/285325e)) - - - -<a name="1.3.0"></a> -## 1.3.0 (2017-03-26) - -* chore: release 1.3.0 ([f3a9e50](https://github.com/vkarpov15/kareem/commit/f3a9e50)) -* feat: pass function args to execPre ([4dd466d](https://github.com/vkarpov15/kareem/commit/4dd466d)) - - - -<a name="1.2.1"></a> -## <small>1.2.1 (2017-02-03)</small> - -* chore: release 1.2.1 ([d97081f](https://github.com/vkarpov15/kareem/commit/d97081f)) -* fix: filter out _kareemIgnored args for error handlers re: Automattic/mongoose#4925 ([ddc7aeb](https://github.com/vkarpov15/kareem/commit/ddc7aeb)), closes [Automattic/mongoose#4925](https://github.com/Automattic/mongoose/issues/4925) -* fix: make error handlers handle errors in pre hooks ([af38033](https://github.com/vkarpov15/kareem/commit/af38033)), closes [Automattic/mongoose#4927](https://github.com/Automattic/mongoose/issues/4927) - - - -<a name="1.2.0"></a> -## 1.2.0 (2017-01-02) - -* chore: release 1.2.0 ([033225c](https://github.com/vkarpov15/kareem/commit/033225c)) -* chore: upgrade deps ([f9e9a09](https://github.com/vkarpov15/kareem/commit/f9e9a09)) -* feat: add _kareemIgnore re: Automattic/mongoose#4836 ([7957771](https://github.com/vkarpov15/kareem/commit/7957771)), closes [Automattic/mongoose#4836](https://github.com/Automattic/mongoose/issues/4836) - - - -<a name="1.1.5"></a> -## <small>1.1.5 (2016-12-13)</small> - -* chore: release 1.1.5 ([1a9f684](https://github.com/vkarpov15/kareem/commit/1a9f684)) -* fix: correct field name ([04a0e9d](https://github.com/vkarpov15/kareem/commit/04a0e9d)) - - - -<a name="1.1.4"></a> -## <small>1.1.4 (2016-12-09)</small> - -* chore: release 1.1.4 ([ece401c](https://github.com/vkarpov15/kareem/commit/ece401c)) -* chore: run tests on node 6 ([e0cb1cb](https://github.com/vkarpov15/kareem/commit/e0cb1cb)) -* fix: only copy own properties in clone() ([dfe28ce](https://github.com/vkarpov15/kareem/commit/dfe28ce)), closes [#7](https://github.com/vkarpov15/kareem/issues/7) - - - -<a name="1.1.3"></a> -## <small>1.1.3 (2016-06-27)</small> - -* chore: release 1.1.3 ([87171c8](https://github.com/vkarpov15/kareem/commit/87171c8)) -* fix: couple more issues with arg processing ([c65f523](https://github.com/vkarpov15/kareem/commit/c65f523)) - - - -<a name="1.1.2"></a> -## <small>1.1.2 (2016-06-27)</small> - -* chore: release 1.1.2 ([8e102b6](https://github.com/vkarpov15/kareem/commit/8e102b6)) -* fix: add early return ([4feda4e](https://github.com/vkarpov15/kareem/commit/4feda4e)) - - - -<a name="1.1.1"></a> -## <small>1.1.1 (2016-06-27)</small> - -* chore: release 1.1.1 ([8bb3050](https://github.com/vkarpov15/kareem/commit/8bb3050)) -* fix: skip error handlers if no error ([0eb3a44](https://github.com/vkarpov15/kareem/commit/0eb3a44)) - - - -<a name="1.1.0"></a> -## 1.1.0 (2016-05-11) - -* chore: release 1.1.0 ([85332d9](https://github.com/vkarpov15/kareem/commit/85332d9)) -* chore: test on node 4 and node 5 ([1faefa1](https://github.com/vkarpov15/kareem/commit/1faefa1)) -* 100% coverage again ([c9aee4e](https://github.com/vkarpov15/kareem/commit/c9aee4e)) -* add support for error post hooks ([d378113](https://github.com/vkarpov15/kareem/commit/d378113)) -* basic setup for sync hooks #4 ([55aa081](https://github.com/vkarpov15/kareem/commit/55aa081)), closes [#4](https://github.com/vkarpov15/kareem/issues/4) -* proof of concept for error handlers ([e4a07d9](https://github.com/vkarpov15/kareem/commit/e4a07d9)) -* refactor out handleWrapError helper ([b19af38](https://github.com/vkarpov15/kareem/commit/b19af38)) - - - -<a name="1.0.1"></a> -## <small>1.0.1 (2015-05-10)</small> - -* Fix #1 ([de60dc6](https://github.com/vkarpov15/kareem/commit/de60dc6)), closes [#1](https://github.com/vkarpov15/kareem/issues/1) -* release 1.0.1 ([6971088](https://github.com/vkarpov15/kareem/commit/6971088)) -* Run tests on iojs in travis ([adcd201](https://github.com/vkarpov15/kareem/commit/adcd201)) -* support legacy post hook behavior in wrap() ([23fa74c](https://github.com/vkarpov15/kareem/commit/23fa74c)) -* Use node 0.12 in travis ([834689d](https://github.com/vkarpov15/kareem/commit/834689d)) - - - -<a name="1.0.0"></a> -## 1.0.0 (2015-01-28) - -* Tag 1.0.0 ([4c5a35a](https://github.com/vkarpov15/kareem/commit/4c5a35a)) - - - -<a name="0.0.8"></a> -## <small>0.0.8 (2015-01-27)</small> - -* Add clone function ([688bba7](https://github.com/vkarpov15/kareem/commit/688bba7)) -* Add jscs for style checking ([5c93149](https://github.com/vkarpov15/kareem/commit/5c93149)) -* Bump 0.0.8 ([03c0d2f](https://github.com/vkarpov15/kareem/commit/03c0d2f)) -* Fix jscs config, add gulp rules ([9989abf](https://github.com/vkarpov15/kareem/commit/9989abf)) -* fix Makefile typo ([1f7e61a](https://github.com/vkarpov15/kareem/commit/1f7e61a)) - - - -<a name="0.0.7"></a> -## <small>0.0.7 (2015-01-04)</small> - -* Bump 0.0.7 ([98ef173](https://github.com/vkarpov15/kareem/commit/98ef173)) -* fix LearnBoost/mongoose#2553 - use null instead of undefined for err ([9157b48](https://github.com/vkarpov15/kareem/commit/9157b48)), closes [LearnBoost/mongoose#2553](https://github.com/LearnBoost/mongoose/issues/2553) -* Regenerate docs ([2331cdf](https://github.com/vkarpov15/kareem/commit/2331cdf)) - - - -<a name="0.0.6"></a> -## <small>0.0.6 (2015-01-01)</small> - -* Update docs and bump 0.0.6 ([92c12a7](https://github.com/vkarpov15/kareem/commit/92c12a7)) - - - -<a name="0.0.5"></a> -## <small>0.0.5 (2015-01-01)</small> - -* Add coverage rule to Makefile ([825a91c](https://github.com/vkarpov15/kareem/commit/825a91c)) -* Add coveralls to README ([fb52369](https://github.com/vkarpov15/kareem/commit/fb52369)) -* Add coveralls to travis ([93f6f15](https://github.com/vkarpov15/kareem/commit/93f6f15)) -* Add createWrapper() function ([ea77741](https://github.com/vkarpov15/kareem/commit/ea77741)) -* Add istanbul code coverage ([6eceeef](https://github.com/vkarpov15/kareem/commit/6eceeef)) -* Add some more comments for examples ([c5b0c6f](https://github.com/vkarpov15/kareem/commit/c5b0c6f)) -* Add travis ([e6dcb06](https://github.com/vkarpov15/kareem/commit/e6dcb06)) -* Add travis badge to docs ([ad8c9b3](https://github.com/vkarpov15/kareem/commit/ad8c9b3)) -* Add wrap() tests, 100% coverage ([6945be4](https://github.com/vkarpov15/kareem/commit/6945be4)) -* Better test coverage for execPost ([d9ad539](https://github.com/vkarpov15/kareem/commit/d9ad539)) -* Bump 0.0.5 ([69875b1](https://github.com/vkarpov15/kareem/commit/69875b1)) -* Docs fix ([15b7098](https://github.com/vkarpov15/kareem/commit/15b7098)) -* Fix silly mistake in docs generation ([50373eb](https://github.com/vkarpov15/kareem/commit/50373eb)) -* Fix typo in readme ([fec4925](https://github.com/vkarpov15/kareem/commit/fec4925)) -* Linkify travis badge ([92b25fe](https://github.com/vkarpov15/kareem/commit/92b25fe)) -* Make travis run coverage ([747157b](https://github.com/vkarpov15/kareem/commit/747157b)) -* Move travis status badge ([d52e89b](https://github.com/vkarpov15/kareem/commit/d52e89b)) -* Quick fix for coverage ([50bbddb](https://github.com/vkarpov15/kareem/commit/50bbddb)) -* Typo fix ([adea794](https://github.com/vkarpov15/kareem/commit/adea794)) - - - -<a name="0.0.4"></a> -## <small>0.0.4 (2014-12-13)</small> - -* Bump 0.0.4, run docs generation ([51a15fe](https://github.com/vkarpov15/kareem/commit/51a15fe)) -* Use correct post parameters in wrap() ([9bb5da3](https://github.com/vkarpov15/kareem/commit/9bb5da3)) - - - -<a name="0.0.3"></a> -## <small>0.0.3 (2014-12-12)</small> - -* Add npm test script, fix small bug with args not getting passed through post ([49e3e68](https://github.com/vkarpov15/kareem/commit/49e3e68)) -* Bump 0.0.3 ([65621d8](https://github.com/vkarpov15/kareem/commit/65621d8)) -* Update readme ([901388b](https://github.com/vkarpov15/kareem/commit/901388b)) - - - -<a name="0.0.2"></a> -## <small>0.0.2 (2014-12-12)</small> - -* Add github repo and bump 0.0.2 ([59db8be](https://github.com/vkarpov15/kareem/commit/59db8be)) - - - -<a name="0.0.1"></a> -## <small>0.0.1 (2014-12-12)</small> - -* Add basic docs ([ad29ea4](https://github.com/vkarpov15/kareem/commit/ad29ea4)) -* Add pre hooks ([2ffc356](https://github.com/vkarpov15/kareem/commit/2ffc356)) -* Add wrap function ([68c540c](https://github.com/vkarpov15/kareem/commit/68c540c)) -* Bump to version 0.0.1 ([a4bfd68](https://github.com/vkarpov15/kareem/commit/a4bfd68)) -* Initial commit ([4002458](https://github.com/vkarpov15/kareem/commit/4002458)) -* Initial deposit ([98fc489](https://github.com/vkarpov15/kareem/commit/98fc489)) -* Post hooks ([395b67c](https://github.com/vkarpov15/kareem/commit/395b67c)) -* Some basic setup work ([82df75e](https://github.com/vkarpov15/kareem/commit/82df75e)) -* Support sync pre hooks ([1cc1b9f](https://github.com/vkarpov15/kareem/commit/1cc1b9f)) -* Update package.json description ([978da18](https://github.com/vkarpov15/kareem/commit/978da18)) diff --git a/node_modules/kareem/LICENSE b/node_modules/kareem/LICENSE deleted file mode 100644 index e06d2081865a766a8668acc12878f98b27fc9ea0..0000000000000000000000000000000000000000 --- a/node_modules/kareem/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ -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/kareem/Makefile b/node_modules/kareem/Makefile deleted file mode 100644 index f71ba900895bb9079f6c39a8f47dd1342720fe9b..0000000000000000000000000000000000000000 --- a/node_modules/kareem/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -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/kareem/README.md b/node_modules/kareem/README.md deleted file mode 100644 index 49a4abc141c17bb4e3412b2c6845155d3690388b..0000000000000000000000000000000000000000 --- a/node_modules/kareem/README.md +++ /dev/null @@ -1,428 +0,0 @@ -# kareem - - [](https://travis-ci.org/vkarpov15/kareem) - [](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) - -<img src="http://upload.wikimedia.org/wikipedia/commons/0/00/Kareem-Abdul-Jabbar_Lipofsky.jpg" width="220"> - -# 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(); - }); - -``` - -#### It supports returning a promise - -You can also return a promise from your pre hooks instead of calling -`next()`. When the returned promise resolves, kareem will kick off the -next middleware. - - -```javascript - - hooks.pre('cook', function() { - return new Promise(resolve => { - setTimeout(() => { - this.bacon = 3; - resolve(); - }, 100); - }); - }); - - var obj = { bacon: 0 }; - - hooks.execPre('cook', obj, function() { - assert.equal(3, obj.bacon); - 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)); - -``` - -## merge() - -#### It pulls hooks from another Kareem object - -```javascript - - var k1 = new Kareem(); - var test1 = function() {}; - k1.pre('cook', test1); - k1.post('cook', function() {}); - - var k2 = new Kareem(); - var test2 = function() {}; - k2.pre('cook', test2); - var k3 = k2.merge(k1); - assert.equal(k3._pres['cook'].length, 2); - assert.equal(k3._pres['cook'][0].fn, test2); - assert.equal(k3._pres['cook'][1].fn, test1); - assert.equal(k3._posts['cook'].length, 1); - -``` - diff --git a/node_modules/kareem/docs.js b/node_modules/kareem/docs.js deleted file mode 100644 index 4a8d4c89f462a283f6befdc3120e032b8553049b..0000000000000000000000000000000000000000 --- a/node_modules/kareem/docs.js +++ /dev/null @@ -1,37 +0,0 @@ -var acquit = require('acquit'); - -var content = require('fs').readFileSync('./test/examples.test.js').toString(); -var blocks = acquit.parse(content); - -var mdOutput = - '# kareem\n\n' + - ' [](https://travis-ci.org/vkarpov15/kareem)\n' + - ' [](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' + - '<img src="http://upload.wikimedia.org/wikipedia/commons/0/00/Kareem-Abdul-Jabbar_Lipofsky.jpg" width="220">\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/kareem/gulpfile.js b/node_modules/kareem/gulpfile.js deleted file mode 100644 index 635bfc75f7b964240f5e36f3265fdb1f3a093d83..0000000000000000000000000000000000000000 --- a/node_modules/kareem/gulpfile.js +++ /dev/null @@ -1,18 +0,0 @@ -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/kareem/index.js b/node_modules/kareem/index.js deleted file mode 100644 index 0e60e0395cce3f10f1ad3411e8c2ade5fc3bc923..0000000000000000000000000000000000000000 --- a/node_modules/kareem/index.js +++ /dev/null @@ -1,503 +0,0 @@ -'use strict'; - -function Kareem() { - this._pres = new Map(); - this._posts = new Map(); -} - -Kareem.prototype.execPre = function(name, context, args, callback) { - if (arguments.length === 3) { - callback = args; - args = []; - } - var pres = get(this._pres, name, []); - var numPres = pres.length; - var numAsyncPres = pres.numAsync || 0; - var currentPre = 0; - var asyncPresLeft = numAsyncPres; - var done = false; - var $args = args; - - if (!numPres) { - return process.nextTick(function() { - callback(null); - }); - } - - var next = function() { - if (currentPre >= numPres) { - return; - } - var pre = pres[currentPre]; - - if (pre.isAsync) { - var args = [ - decorateNextFn(_next), - decorateNextFn(function(error) { - if (error) { - if (done) { - return; - } - done = true; - return callback(error); - } - if (--asyncPresLeft === 0 && currentPre >= numPres) { - return callback(null); - } - }) - ]; - - callMiddlewareFunction(pre.fn, context, args, args[0]); - } else if (pre.fn.length > 0) { - var args = [decorateNextFn(_next)]; - var _args = arguments.length >= 2 ? arguments : [null].concat($args); - for (var i = 1; i < _args.length; ++i) { - args.push(_args[i]); - } - - callMiddlewareFunction(pre.fn, context, args, args[0]); - } else { - let error = null; - let maybePromise = null; - try { - maybePromise = pre.fn.call(context); - } catch (err) { - error = err; - } - - if (isPromise(maybePromise)) { - maybePromise.then(() => _next(), err => _next(err)); - } else { - if (++currentPre >= numPres) { - if (asyncPresLeft > 0) { - // Leave parallel hooks to run - return; - } else { - return process.nextTick(function() { - callback(error); - }); - } - } - next(error); - } - } - }; - - next.apply(null, [null].concat(args)); - - function _next(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); - } -}; - -Kareem.prototype.execPreSync = function(name, context, args) { - var pres = get(this._pres, name, []); - var numPres = pres.length; - - for (var i = 0; i < numPres; ++i) { - pres[i].fn.apply(context, args || []); - } -}; - -Kareem.prototype.execPost = function(name, context, args, options, callback) { - if (arguments.length < 5) { - callback = options; - options = null; - } - var posts = get(this._posts, name, []); - var numPosts = posts.length; - var currentPost = 0; - - var firstError = null; - if (options && options.error) { - firstError = options.error; - } - - if (!numPosts) { - return process.nextTick(function() { - callback.apply(null, [firstError].concat(args)); - }); - } - - var next = function() { - var post = posts[currentPost].fn; - var numArgs = 0; - var argLength = args.length; - var newArgs = []; - for (var i = 0; i < argLength; ++i) { - numArgs += args[i] && args[i]._kareemIgnore ? 0 : 1; - if (!args[i] || !args[i]._kareemIgnore) { - newArgs.push(args[i]); - } - } - - if (firstError) { - if (post.length === numArgs + 2) { - var _cb = decorateNextFn(function(error) { - if (error) { - firstError = error; - } - if (++currentPost >= numPosts) { - return callback.call(null, firstError); - } - next(); - }); - - callMiddlewareFunction(post, context, - [firstError].concat(newArgs).concat([_cb]), _cb); - } else { - if (++currentPost >= numPosts) { - return callback.call(null, firstError); - } - next(); - } - } else { - const _cb = decorateNextFn(function(error) { - if (error) { - firstError = error; - return next(); - } - - if (++currentPost >= numPosts) { - return callback.apply(null, [null].concat(args)); - } - - next(); - }); - - if (post.length === numArgs + 2) { - // Skip error handlers if no error - if (++currentPost >= numPosts) { - return callback.apply(null, [null].concat(args)); - } - return next(); - } - if (post.length === numArgs + 1) { - callMiddlewareFunction(post, context, newArgs.concat([_cb]), _cb); - } else { - let error; - let maybePromise; - try { - maybePromise = post.apply(context, newArgs); - } catch (err) { - error = err; - firstError = err; - } - - if (isPromise(maybePromise)) { - return maybePromise.then(() => _cb(), err => _cb(err)); - } - - if (++currentPost >= numPosts) { - return callback.apply(null, [error].concat(args)); - } - - next(error); - } - } - }; - - next(); -}; - -Kareem.prototype.execPostSync = function(name, context, args) { - const posts = get(this._posts, name, []); - const numPosts = posts.length; - - for (let i = 0; i < numPosts; ++i) { - posts[i].fn.apply(context, args || []); - } -}; - -Kareem.prototype.createWrapperSync = function(name, fn) { - var kareem = this; - return function syncWrapper() { - kareem.execPreSync(name, this, arguments); - - var toReturn = fn.apply(this, arguments); - - kareem.execPostSync(name, this, [toReturn]); - - return toReturn; - }; -} - -function _handleWrapError(instance, error, name, context, args, options, callback) { - if (options.useErrorHandlers) { - var _options = { error: error }; - return instance.execPost(name, context, args, _options, function(error) { - return typeof callback === 'function' && callback(error); - }); - } else { - return typeof callback === 'function' ? - callback(error) : - undefined; - } -} - -Kareem.prototype.wrap = function(name, fn, context, args, options) { - const lastArg = (args.length > 0 ? args[args.length - 1] : null); - const argsWithoutCb = typeof lastArg === 'function' ? - args.slice(0, args.length - 1) : - args; - const _this = this; - - options = options || {}; - const checkForPromise = options.checkForPromise; - - this.execPre(name, context, args, function(error) { - if (error) { - const numCallbackParams = options.numCallbackParams || 0; - const errorArgs = options.contextParameter ? [context] : []; - for (var i = errorArgs.length; i < numCallbackParams; ++i) { - errorArgs.push(null); - } - return _handleWrapError(_this, error, name, context, errorArgs, - options, lastArg); - } - - const end = (typeof lastArg === 'function' ? args.length - 1 : args.length); - const numParameters = fn.length; - const ret = fn.apply(context, args.slice(0, end).concat(_cb)); - - if (checkForPromise) { - if (ret != null && typeof ret.then === 'function') { - // Thenable, use it - return ret.then( - res => _cb(null, res), - err => _cb(err) - ); - } - - // If `fn()` doesn't have a callback argument and doesn't return a - // promise, assume it is sync - if (numParameters < end + 1) { - return _cb(null, ret); - } - } - - function _cb() { - const args = arguments; - const argsWithoutError = Array.prototype.slice.call(arguments, 1); - if (options.nullResultByDefault && argsWithoutError.length === 0) { - argsWithoutError.push(null); - } - if (arguments[0]) { - // Assume error - return _handleWrapError(_this, arguments[0], name, context, - argsWithoutError, options, lastArg); - } else { - _this.execPost(name, context, argsWithoutError, function() { - if (arguments[0]) { - return typeof lastArg === 'function' ? - lastArg(arguments[0]) : - undefined; - } - - return typeof lastArg === 'function' ? - lastArg.apply(context, arguments) : - undefined; - }); - } - } - }); -}; - -Kareem.prototype.filter = function(fn) { - const clone = this.clone(); - - const pres = Array.from(clone._pres.keys()); - for (const name of pres) { - const hooks = this._pres.get(name). - map(h => Object.assign({}, h, { name: name })). - filter(fn); - - if (hooks.length === 0) { - clone._pres.delete(name); - continue; - } - - hooks.numAsync = hooks.filter(h => h.isAsync).length; - - clone._pres.set(name, hooks); - } - - const posts = Array.from(clone._posts.keys()); - for (const name of posts) { - const hooks = this._posts.get(name). - map(h => Object.assign({}, h, { name: name })). - filter(fn); - - if (hooks.length === 0) { - clone._posts.delete(name); - continue; - } - - clone._posts.set(name, hooks); - } - - return clone; -}; - -Kareem.prototype.hasHooks = function(name) { - return this._pres.has(name) || this._posts.has(name); -}; - -Kareem.prototype.createWrapper = function(name, fn, context, options) { - var _this = this; - if (!this.hasHooks(name)) { - // Fast path: if there's no hooks for this function, just return the - // function wrapped in a nextTick() - return function() { - process.nextTick(() => fn.apply(this, arguments)); - }; - } - return function() { - var _context = context || this; - var args = Array.prototype.slice.call(arguments); - _this.wrap(name, fn, _context, args, options); - }; -}; - -Kareem.prototype.pre = function(name, isAsync, fn, error, unshift) { - let options = {}; - if (typeof isAsync === 'object' && isAsync != null) { - options = isAsync; - isAsync = options.isAsync; - } else if (typeof arguments[1] !== 'boolean') { - error = fn; - fn = isAsync; - isAsync = false; - } - - const pres = get(this._pres, name, []); - this._pres.set(name, pres); - - if (isAsync) { - pres.numAsync = pres.numAsync || 0; - ++pres.numAsync; - } - - if (unshift) { - pres.unshift(Object.assign({}, options, { fn: fn, isAsync: isAsync })); - } else { - pres.push(Object.assign({}, options, { fn: fn, isAsync: isAsync })); - } - - return this; -}; - -Kareem.prototype.post = function(name, options, fn, unshift) { - const hooks = get(this._posts, name, []); - - if (typeof options === 'function') { - unshift = !!fn; - fn = options; - options = {}; - } - - if (unshift) { - hooks.unshift(Object.assign({}, options, { fn: fn })); - } else { - hooks.push(Object.assign({}, options, { fn: fn })); - } - this._posts.set(name, hooks); - return this; -}; - -Kareem.prototype.clone = function() { - const n = new Kareem(); - - for (let key of this._pres.keys()) { - const clone = this._pres.get(key).slice(); - clone.numAsync = this._pres.get(key).numAsync; - n._pres.set(key, clone); - } - for (let key of this._posts.keys()) { - n._posts.set(key, this._posts.get(key).slice()); - } - - return n; -}; - -Kareem.prototype.merge = function(other, clone) { - clone = arguments.length === 1 ? true : clone; - var ret = clone ? this.clone() : this; - - for (let key of other._pres.keys()) { - const sourcePres = get(ret._pres, key, []); - const deduplicated = other._pres.get(key). - // Deduplicate based on `fn` - filter(p => sourcePres.map(_p => _p.fn).indexOf(p.fn) === -1); - const combined = sourcePres.concat(deduplicated); - combined.numAsync = sourcePres.numAsync || 0; - combined.numAsync += deduplicated.filter(p => p.isAsync).length; - ret._pres.set(key, combined); - } - for (let key of other._posts.keys()) { - const sourcePosts = get(ret._posts, key, []); - const deduplicated = other._posts.get(key). - filter(p => sourcePosts.indexOf(p) === -1); - ret._posts.set(key, sourcePosts.concat(deduplicated)); - } - - return ret; -}; - -function get(map, key, def) { - if (map.has(key)) { - return map.get(key); - } - return def; -} - -function callMiddlewareFunction(fn, context, args, next) { - let maybePromise; - try { - maybePromise = fn.apply(context, args); - } catch (error) { - return next(error); - } - - if (isPromise(maybePromise)) { - maybePromise.then(() => next(), err => next(err)); - } -} - -function isPromise(v) { - return v != null && typeof v.then === 'function'; -} - -function decorateNextFn(fn) { - var called = false; - var _this = this; - return function() { - // Ensure this function can only be called once - if (called) { - return; - } - called = true; - // Make sure to clear the stack so try/catch doesn't catch errors - // in subsequent middleware - return process.nextTick(() => fn.apply(_this, arguments)); - }; -} - -module.exports = Kareem; diff --git a/node_modules/kareem/package.json b/node_modules/kareem/package.json deleted file mode 100644 index ee4a4f998a358487f950a318f9656bfc6ef0c82a..0000000000000000000000000000000000000000 --- a/node_modules/kareem/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "_from": "kareem@2.3.0", - "_id": "kareem@2.3.0", - "_inBundle": false, - "_integrity": "sha512-6hHxsp9e6zQU8nXsP+02HGWXwTkOEw6IROhF2ZA28cYbUk4eJ6QbtZvdqZOdD9YPKghG3apk5eOCvs+tLl3lRg==", - "_location": "/kareem", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "kareem@2.3.0", - "name": "kareem", - "escapedName": "kareem", - "rawSpec": "2.3.0", - "saveSpec": null, - "fetchSpec": "2.3.0" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/kareem/-/kareem-2.3.0.tgz", - "_shasum": "ef33c42e9024dce511eeaf440cd684f3af1fc769", - "_spec": "kareem@2.3.0", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongoose", - "author": { - "name": "Valeri Karpov", - "email": "val@karpov.io" - }, - "bugs": { - "url": "https://github.com/vkarpov15/kareem/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Next-generation take on pre/post function hooks", - "devDependencies": { - "acquit": "0.5.1", - "gulp": "3.8.10", - "gulp-jscs": "1.4.0", - "gulp-mocha": "2.0.0", - "istanbul": "0.4.5", - "jscs": "1.9.0", - "mocha": "3.2.0", - "standard-version": "4.4.0" - }, - "homepage": "https://github.com/vkarpov15/kareem#readme", - "jscsConfig": { - "preset": "airbnb", - "requireMultipleVarDecl": null, - "disallowMultipleVarDecl": true - }, - "license": "Apache-2.0", - "main": "index.js", - "name": "kareem", - "repository": { - "type": "git", - "url": "git://github.com/vkarpov15/kareem.git" - }, - "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/*" - }, - "version": "2.3.0" -} diff --git a/node_modules/kareem/test/examples.test.js b/node_modules/kareem/test/examples.test.js deleted file mode 100644 index f120723dd38ee0892faf601049de88d14620f7cb..0000000000000000000000000000000000000000 --- a/node_modules/kareem/test/examples.test.js +++ /dev/null @@ -1,379 +0,0 @@ -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(); - }); - }); - - /* You can also return a promise from your pre hooks instead of calling - * `next()`. When the returned promise resolves, kareem will kick off the - * next middleware. - */ - it('supports returning a promise', function(done) { - hooks.pre('cook', function() { - return new Promise(resolve => { - setTimeout(() => { - this.bacon = 3; - resolve(); - }, 100); - }); - }); - - var obj = { bacon: 0 }; - - hooks.execPre('cook', obj, function() { - assert.equal(3, obj.bacon); - 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(Array.from(k2._pres.keys()), ['cook']); - assert.deepEqual(Array.from(k2._posts.keys()), ['cook']); - }); -}); - -describe('merge()', function() { - it('pulls hooks from another Kareem object', function() { - var k1 = new Kareem(); - var test1 = function() {}; - k1.pre('cook', test1); - k1.post('cook', function() {}); - - var k2 = new Kareem(); - var test2 = function() {}; - k2.pre('cook', test2); - var k3 = k2.merge(k1); - assert.equal(k3._pres.get('cook').length, 2); - assert.equal(k3._pres.get('cook')[0].fn, test2); - assert.equal(k3._pres.get('cook')[1].fn, test1); - assert.equal(k3._posts.get('cook').length, 1); - }); -}); diff --git a/node_modules/kareem/test/misc.test.js b/node_modules/kareem/test/misc.test.js deleted file mode 100644 index 531b1d49d57b2ac29e9d56970fa0e72f1202501d..0000000000000000000000000000000000000000 --- a/node_modules/kareem/test/misc.test.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const Kareem = require('../'); - -describe('hasHooks', function() { - it('returns false for toString (Automattic/mongoose#6538)', function() { - const k = new Kareem(); - assert.ok(!k.hasHooks('toString')); - }); -}); - -describe('merge', function() { - it('handles async pres if source doesnt have them', function() { - const k1 = new Kareem(); - k1.pre('cook', true, function(next, done) { - execed.first = true; - setTimeout( - function() { - done('error!'); - }, - 5); - - next(); - }); - - assert.equal(k1._pres.get('cook').numAsync, 1); - - const k2 = new Kareem(); - const k3 = k2.merge(k1); - assert.equal(k3._pres.get('cook').numAsync, 1); - }); -}); - -describe('filter', function() { - it('returns clone with only hooks that match `fn()`', function() { - const k1 = new Kareem(); - - k1.pre('update', { document: true }, f1); - k1.pre('update', { query: true }, f2); - k1.pre('remove', { document: true }, f3); - - k1.post('update', { document: true }, f1); - k1.post('update', { query: true }, f2); - k1.post('remove', { document: true }, f3); - - const k2 = k1.filter(hook => hook.document); - assert.equal(k2._pres.get('update').length, 1); - assert.equal(k2._pres.get('update')[0].fn, f1); - assert.equal(k2._pres.get('remove').length, 1); - assert.equal(k2._pres.get('remove')[0].fn, f3); - - assert.equal(k2._posts.get('update').length, 1); - assert.equal(k2._posts.get('update')[0].fn, f1); - assert.equal(k2._posts.get('remove').length, 1); - assert.equal(k2._posts.get('remove')[0].fn, f3); - - const k3 = k1.filter(hook => hook.query); - assert.equal(k3._pres.get('update').length, 1); - assert.equal(k3._pres.get('update')[0].fn, f2); - assert.ok(!k3._pres.has('remove')); - - assert.equal(k3._posts.get('update').length, 1); - assert.equal(k3._posts.get('update')[0].fn, f2); - assert.ok(!k3._posts.has('remove')); - - function f1() {} - function f2() {} - function f3() {} - }); -}); diff --git a/node_modules/kareem/test/post.test.js b/node_modules/kareem/test/post.test.js deleted file mode 100644 index 8cb2067536a18cd0f932874e04abd02ffea48b20..0000000000000000000000000000000000000000 --- a/node_modules/kareem/test/post.test.js +++ /dev/null @@ -1,194 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const 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('unshift', function() { - var f1 = function() {}; - var f2 = function() {}; - hooks.post('cook', f1); - hooks.post('cook', f2, true); - assert.strictEqual(hooks._posts.get('cook')[0].fn, f2); - assert.strictEqual(hooks._posts.get('cook')[1].fn, f1); - }); - - it('arbitrary options', function() { - const f1 = function() {}; - const f2 = function() {}; - hooks.post('cook', { foo: 'bar' }, f1); - hooks.post('cook', { bar: 'baz' }, f2, true); - assert.equal(hooks._posts.get('cook')[1].foo, 'bar'); - assert.equal(hooks._posts.get('cook')[0].bar, 'baz'); - }); - - 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(); - }); - }); - - it('error posts', function(done) { - var called = {}; - hooks.post('cook', function(eggs, callback) { - called.first = true; - callback(); - }); - - hooks.post('cook', function(eggs, callback) { - called.second = true; - callback(new Error('fail')); - }); - - hooks.post('cook', function(eggs, callback) { - assert.ok(false); - }); - - hooks.post('cook', function(error, eggs, callback) { - called.fourth = true; - assert.equal(error.message, 'fail'); - callback(new Error('fourth')); - }); - - hooks.post('cook', function(error, eggs, callback) { - called.fifth = true; - assert.equal(error.message, 'fourth'); - callback(new Error('fifth')); - }); - - hooks.execPost('cook', null, [4], function(error, eggs) { - assert.ok(error); - assert.equal(error.message, 'fifth'); - assert.deepEqual(called, { - first: true, - second: true, - fourth: true, - fifth: true - }); - done(); - }); - }); - - it('error posts with initial error', function(done) { - var called = {}; - - hooks.post('cook', function(eggs, callback) { - assert.ok(false); - }); - - hooks.post('cook', function(error, eggs, callback) { - called.second = true; - assert.equal(error.message, 'fail'); - callback(new Error('second')); - }); - - hooks.post('cook', function(error, eggs, callback) { - called.third = true; - assert.equal(error.message, 'second'); - callback(new Error('third')); - }); - - hooks.post('cook', function(error, eggs, callback) { - called.fourth = true; - assert.equal(error.message, 'third'); - callback(); - }); - - var options = { error: new Error('fail') }; - hooks.execPost('cook', null, [4], options, function(error, eggs) { - assert.ok(error); - assert.equal(error.message, 'third'); - assert.deepEqual(called, { - second: true, - third: true, - fourth: true - }); - done(); - }); - }); - - it('supports returning a promise', function(done) { - var calledPost = 0; - - hooks.post('cook', function() { - return new Promise(resolve => { - setTimeout(() => { - ++calledPost; - resolve(); - }, 100); - }); - }); - - hooks.execPost('cook', null, [], {}, function(error) { - assert.ifError(error); - assert.equal(calledPost, 1); - done(); - }); - }); -}); - -describe('execPostSync', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('executes hooks synchronously', function() { - var execed = {}; - - hooks.post('cook', function() { - execed.first = true; - }); - - hooks.post('cook', function() { - execed.second = true; - }); - - hooks.execPostSync('cook', null); - assert.ok(execed.first); - assert.ok(execed.second); - }); - - it('works with no hooks specified', function() { - assert.doesNotThrow(function() { - hooks.execPostSync('cook', null); - }); - }); -}); diff --git a/node_modules/kareem/test/pre.test.js b/node_modules/kareem/test/pre.test.js deleted file mode 100644 index 10240f42947d277a5f92adb1be57c8deb7086b21..0000000000000000000000000000000000000000 --- a/node_modules/kareem/test/pre.test.js +++ /dev/null @@ -1,316 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const 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('sync errors', function(done) { - var called = 0; - - hooks.pre('cook', function(next) { - throw new Error('woops!'); - }); - - hooks.pre('cook', function(next) { - ++called; - next(); - }); - - hooks.execPre('cook', null, function(err) { - assert.equal(err.message, 'woops!'); - assert.equal(called, 0); - done(); - }); - }); - - it('unshift', function() { - var f1 = function() {}; - var f2 = function() {}; - hooks.pre('cook', false, f1); - hooks.pre('cook', false, f2, null, true); - assert.strictEqual(hooks._pres.get('cook')[0].fn, f2); - assert.strictEqual(hooks._pres.get('cook')[1].fn, f1); - }); - - it('arbitrary options', function() { - const f1 = function() {}; - const f2 = function() {}; - hooks.pre('cook', { foo: 'bar' }, f1); - hooks.pre('cook', { bar: 'baz' }, f2, null, true); - assert.equal(hooks._pres.get('cook')[1].foo, 'bar'); - assert.equal(hooks._pres.get('cook')[0].bar, 'baz'); - }); - - 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('async pres with clone()', function(done) { - var execed = false; - - hooks.pre('cook', true, function(next, done) { - execed = true; - setTimeout( - function() { - done(); - }, - 5); - - next(); - }); - - hooks.clone().execPre('cook', null, function(err) { - assert.ifError(err); - assert.ok(execed); - 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(); - }); - }); -}); - -describe('execPreSync', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('executes hooks synchronously', function() { - var execed = {}; - - hooks.pre('cook', function() { - execed.first = true; - }); - - hooks.pre('cook', function() { - execed.second = true; - }); - - hooks.execPreSync('cook', null); - assert.ok(execed.first); - assert.ok(execed.second); - }); - - it('works with no hooks specified', function() { - assert.doesNotThrow(function() { - hooks.execPreSync('cook', null); - }); - }); -}); diff --git a/node_modules/kareem/test/wrap.test.js b/node_modules/kareem/test/wrap.test.js deleted file mode 100644 index dd9196e033114eb258c84a8771b2b3eba382d1da..0000000000000000000000000000000000000000 --- a/node_modules/kareem/test/wrap.test.js +++ /dev/null @@ -1,342 +0,0 @@ -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('defers errors to post hooks if enabled', function(done) { - hooks.pre('cook', function(done) { - done(new Error('fail')); - }); - - hooks.post('cook', function(error, res, callback) { - callback(new Error('another error occurred')); - }); - - var args = []; - args.push(function(error) { - assert.equal(error.message, 'another error occurred'); - done(); - }); - - hooks.wrap( - 'cook', - function(callback) { - assert.ok(false); - callback(); - }, - null, - args, - { useErrorHandlers: true, numCallbackParams: 1 }); - }); - - it('error handlers with no callback', function(done) { - hooks.pre('cook', function(done) { - done(new Error('fail')); - }); - - hooks.post('cook', function(error, callback) { - assert.equal(error.message, 'fail'); - done(); - }); - - var args = []; - - hooks.wrap( - 'cook', - function(callback) { - assert.ok(false); - callback(); - }, - null, - args, - { useErrorHandlers: true }); - }); - - it('error handlers with no error', function(done) { - hooks.post('cook', function(error, callback) { - callback(new Error('another error occurred')); - }); - - var args = []; - args.push(function(error) { - assert.ifError(error); - done(); - }); - - hooks.wrap( - 'cook', - function(callback) { - callback(); - }, - null, - args, - { useErrorHandlers: true }); - }); - - 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('sync wrappers', function() { - var calledPre = 0; - var calledFn = 0; - var calledPost = 0; - hooks.pre('cook', function() { - ++calledPre; - }); - - hooks.post('cook', function() { - ++calledPost; - }); - - var wrapper = hooks.createWrapperSync('cook', function() { ++calledFn; }); - - wrapper(); - - assert.equal(calledPre, 1); - assert.equal(calledFn, 1); - assert.equal(calledPost, 1); - }); -}); diff --git a/node_modules/memory-pager/.travis.yml b/node_modules/memory-pager/.travis.yml deleted file mode 100644 index 1c4ab31e974d37bcfd286980ffa53891b2e5b608..0000000000000000000000000000000000000000 --- a/node_modules/memory-pager/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - '4' - - '6' diff --git a/node_modules/memory-pager/LICENSE b/node_modules/memory-pager/LICENSE deleted file mode 100644 index 56fce0895e13ffe83650a7274d79fbcfb80d3e2f..0000000000000000000000000000000000000000 --- a/node_modules/memory-pager/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 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. diff --git a/node_modules/memory-pager/README.md b/node_modules/memory-pager/README.md deleted file mode 100644 index aed176140ca3a3d6ca2d73128a588600b3240299..0000000000000000000000000000000000000000 --- a/node_modules/memory-pager/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# memory-pager - -Access memory using small fixed sized buffers instead of allocating a huge buffer. -Useful if you are implementing sparse data structures (such as large bitfield). - - - -``` -npm install memory-pager -``` - -## Usage - -``` js -var pager = require('paged-memory') - -var pages = pager(1024) // use 1kb per page - -var page = pages.get(10) // get page #10 - -console.log(page.offset) // 10240 -console.log(page.buffer) // a blank 1kb buffer -``` - -## API - -#### `var pages = pager(pageSize)` - -Create a new pager. `pageSize` defaults to `1024`. - -#### `var page = pages.get(pageNumber, [noAllocate])` - -Get a page. The page will be allocated at first access. - -Optionally you can set the `noAllocate` flag which will make the -method return undefined if no page has been allocated already - -A page looks like this - -``` js -{ - offset: byteOffset, - buffer: bufferWithPageSize -} -``` - -#### `pages.set(pageNumber, buffer)` - -Explicitly set the buffer for a page. - -#### `pages.updated(page)` - -Mark a page as updated. - -#### `pages.lastUpdate()` - -Get the last page that was updated. - -#### `var buf = pages.toBuffer()` - -Concat all pages allocated pages into a single buffer - -## License - -MIT diff --git a/node_modules/memory-pager/index.js b/node_modules/memory-pager/index.js deleted file mode 100644 index 687f346f30e6e8e6f3247f06c4946643ae2baba8..0000000000000000000000000000000000000000 --- a/node_modules/memory-pager/index.js +++ /dev/null @@ -1,160 +0,0 @@ -module.exports = Pager - -function Pager (pageSize, opts) { - if (!(this instanceof Pager)) return new Pager(pageSize, opts) - - this.length = 0 - this.updates = [] - this.path = new Uint16Array(4) - this.pages = new Array(32768) - this.maxPages = this.pages.length - this.level = 0 - this.pageSize = pageSize || 1024 - this.deduplicate = opts ? opts.deduplicate : null - this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null -} - -Pager.prototype.updated = function (page) { - while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { - page.deduplicate++ - if (page.deduplicate === this.deduplicate.length) { - page.deduplicate = 0 - if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate - break - } - } - if (page.updated || !this.updates) return - page.updated = true - this.updates.push(page) -} - -Pager.prototype.lastUpdate = function () { - if (!this.updates || !this.updates.length) return null - var page = this.updates.pop() - page.updated = false - return page -} - -Pager.prototype._array = function (i, noAllocate) { - if (i >= this.maxPages) { - if (noAllocate) return - grow(this, i) - } - - factor(i, this.path) - - var arr = this.pages - - for (var j = this.level; j > 0; j--) { - var p = this.path[j] - var next = arr[p] - - if (!next) { - if (noAllocate) return - next = arr[p] = new Array(32768) - } - - arr = next - } - - return arr -} - -Pager.prototype.get = function (i, noAllocate) { - var arr = this._array(i, noAllocate) - var first = this.path[0] - var page = arr && arr[first] - - if (!page && !noAllocate) { - page = arr[first] = new Page(i, alloc(this.pageSize)) - if (i >= this.length) this.length = i + 1 - } - - if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { - page.buffer = copy(page.buffer) - page.deduplicate = 0 - } - - return page -} - -Pager.prototype.set = function (i, buf) { - var arr = this._array(i, false) - var first = this.path[0] - - if (i >= this.length) this.length = i + 1 - - if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { - arr[first] = undefined - return - } - - if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { - buf = this.deduplicate - } - - var page = arr[first] - var b = truncate(buf, this.pageSize) - - if (page) page.buffer = b - else arr[first] = new Page(i, b) -} - -Pager.prototype.toBuffer = function () { - var list = new Array(this.length) - var empty = alloc(this.pageSize) - var ptr = 0 - - while (ptr < list.length) { - var arr = this._array(ptr, true) - for (var i = 0; i < 32768 && ptr < list.length; i++) { - list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty - } - } - - return Buffer.concat(list) -} - -function grow (pager, index) { - while (pager.maxPages < index) { - var old = pager.pages - pager.pages = new Array(32768) - pager.pages[0] = old - pager.level++ - pager.maxPages *= 32768 - } -} - -function truncate (buf, len) { - if (buf.length === len) return buf - if (buf.length > len) return buf.slice(0, len) - var cpy = alloc(len) - buf.copy(cpy) - return cpy -} - -function alloc (size) { - if (Buffer.alloc) return Buffer.alloc(size) - var buf = new Buffer(size) - buf.fill(0) - return buf -} - -function copy (buf) { - var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) - buf.copy(cpy) - return cpy -} - -function Page (i, buf) { - this.offset = i * buf.length - this.buffer = buf - this.updated = false - this.deduplicate = 0 -} - -function factor (n, out) { - n = (n - (out[0] = (n & 32767))) / 32768 - n = (n - (out[1] = (n & 32767))) / 32768 - out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 -} diff --git a/node_modules/memory-pager/package.json b/node_modules/memory-pager/package.json deleted file mode 100644 index 358faa0853bf8dff762fb590c356c0d873810c71..0000000000000000000000000000000000000000 --- a/node_modules/memory-pager/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "_from": "memory-pager@^1.0.2", - "_id": "memory-pager@1.5.0", - "_inBundle": false, - "_integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", - "_location": "/memory-pager", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "memory-pager@^1.0.2", - "name": "memory-pager", - "escapedName": "memory-pager", - "rawSpec": "^1.0.2", - "saveSpec": null, - "fetchSpec": "^1.0.2" - }, - "_requiredBy": [ - "/sparse-bitfield" - ], - "_resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", - "_shasum": "d8751655d22d384682741c972f2c3d6dfa3e66b5", - "_spec": "memory-pager@^1.0.2", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/sparse-bitfield", - "author": { - "name": "Mathias Buus", - "url": "@mafintosh" - }, - "bugs": { - "url": "https://github.com/mafintosh/memory-pager/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Access memory using small fixed sized buffers", - "devDependencies": { - "standard": "^9.0.0", - "tape": "^4.6.3" - }, - "homepage": "https://github.com/mafintosh/memory-pager", - "license": "MIT", - "main": "index.js", - "name": "memory-pager", - "repository": { - "type": "git", - "url": "git+https://github.com/mafintosh/memory-pager.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "1.5.0" -} diff --git a/node_modules/memory-pager/test.js b/node_modules/memory-pager/test.js deleted file mode 100644 index 16382100376b99a29f748969ba419c1b200080d9..0000000000000000000000000000000000000000 --- a/node_modules/memory-pager/test.js +++ /dev/null @@ -1,80 +0,0 @@ -var tape = require('tape') -var pager = require('./') - -tape('get page', function (t) { - var pages = pager(1024) - - var page = pages.get(0) - - t.same(page.offset, 0) - t.same(page.buffer, Buffer.alloc(1024)) - t.end() -}) - -tape('get page twice', function (t) { - var pages = pager(1024) - t.same(pages.length, 0) - - var page = pages.get(0) - - t.same(page.offset, 0) - t.same(page.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1) - - var other = pages.get(0) - - t.same(other, page) - t.end() -}) - -tape('get no mutable page', function (t) { - var pages = pager(1024) - - t.ok(!pages.get(141, true)) - t.ok(pages.get(141)) - t.ok(pages.get(141, true)) - - t.end() -}) - -tape('get far out page', function (t) { - var pages = pager(1024) - - var page = pages.get(1000000) - - t.same(page.offset, 1000000 * 1024) - t.same(page.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1000000 + 1) - - var other = pages.get(1) - - t.same(other.offset, 1024) - t.same(other.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1000000 + 1) - t.ok(other !== page) - - t.end() -}) - -tape('updates', function (t) { - var pages = pager(1024) - - t.same(pages.lastUpdate(), null) - - var page = pages.get(10) - - page.buffer[42] = 1 - pages.updated(page) - - t.same(pages.lastUpdate(), page) - t.same(pages.lastUpdate(), null) - - page.buffer[42] = 2 - pages.updated(page) - pages.updated(page) - - t.same(pages.lastUpdate(), page) - t.same(pages.lastUpdate(), null) - - t.end() -}) diff --git a/node_modules/mongodb-core/HISTORY.md b/node_modules/mongodb-core/HISTORY.md deleted file mode 100644 index 501bbb0cda923f6087969fe5d004e853fd776516..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/HISTORY.md +++ /dev/null @@ -1,1085 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -<a name="3.1.11"></a> -## [3.1.11](https://github.com/mongodb-js/mongodb-core/compare/v3.1.10...v3.1.11) (2019-01-16) - - -### Bug Fixes - -* **wire-protocol:** don't allow override of `slaveOk` ([8fcef69](https://github.com/mongodb-js/mongodb-core/commit/8fcef69)) - - - -<a name="3.1.10"></a> -## [3.1.10](https://github.com/mongodb-js/mongodb-core/compare/v3.1.9...v3.1.10) (2019-01-15) - - -### Bug Fixes - -* **mongos-replset:** pass connect options to child server instances ([7ffb4bb](https://github.com/mongodb-js/mongodb-core/commit/7ffb4bb)) -* **prettier:** fix prettier file paths for Windows ([00c631e](https://github.com/mongodb-js/mongodb-core/commit/00c631e)) - - - -<a name="3.1.9"></a> -## [3.1.9](https://github.com/mongodb-js/mongodb-core/compare/v3.1.8...v3.1.9) (2018-11-16) - - -### Bug Fixes - -* **mongos:** ensure servers are properly cleaned up when destroyed ([68f4fd3](https://github.com/mongodb-js/mongodb-core/commit/68f4fd3)) -* **uri_parser:** uri-encoded auth handling ([81b5b45](https://github.com/mongodb-js/mongodb-core/commit/81b5b45)) -* **url-parser:** support passing in `auth` to parsing options ([29455ca](https://github.com/mongodb-js/mongodb-core/commit/29455ca)) - - - -<a name="3.1.8"></a> -## [3.1.8](https://github.com/mongodb-js/mongodb-core/compare/v3.1.7...v3.1.8) (2018-11-05) - - -### Bug Fixes - -* **sspi:** correct auth process for SSPI ([808ab21](https://github.com/mongodb-js/mongodb-core/commit/808ab21)) -* **uri_parser:** add `replSet` to exemption list for number coercion ([d00b1ab](https://github.com/mongodb-js/mongodb-core/commit/d00b1ab)) - - - -<a name="3.1.7"></a> -## [3.1.7](https://github.com/mongodb-js/mongodb-core/compare/v3.1.6...v3.1.7) (2018-10-10) - - -### Bug Fixes - -* **uri-parser:** persist default database when authSource present ([aa601d3](https://github.com/mongodb-js/mongodb-core/commit/aa601d3)) - - - -<a name="3.1.6"></a> -## [3.1.6](https://github.com/mongodb-js/mongodb-core/compare/v3.1.4...v3.1.6) (2018-10-09) - - -### Bug Fixes - -* **srv-parsing:** ensure parse options are propogated to txt lookup ([923ceb0](https://github.com/mongodb-js/mongodb-core/commit/923ceb0)) -* **uri-parser:** add exemption list for number coercion in options ([82896ea](https://github.com/mongodb-js/mongodb-core/commit/82896ea)) - - - -<a name="3.1.5"></a> -## [3.1.5](https://github.com/mongodb-js/mongodb-core/compare/v3.1.4...v3.1.5) (2018-09-15) - -### Bug Fixes - -* **connection:** Revert fast fallback due to Atlas connect issues ([3133fc3](https://github.com/mongodb-js/mongodb-core/commit/3133fc3)) - - -<a name="3.1.4"></a> -## [3.1.4](https://github.com/mongodb-js/mongodb-core/compare/v3.1.3...v3.1.4) (2018-09-14) - - -### Bug Fixes - -* **apm:** fix upconversion for OP_QUERY in apm ([f969bee](https://github.com/mongodb-js/mongodb-core/commit/f969bee)) -* **gssapi:** check lowercase and camelCase gssapiServiceName option ([bf0315d](https://github.com/mongodb-js/mongodb-core/commit/bf0315d)) -* **test:** do not check deep equality when test.auth.db is null ([7d3c057](https://github.com/mongodb-js/mongodb-core/commit/7d3c057)) -* **uri_parser:** use admin as default auth.db ([345e6af](https://github.com/mongodb-js/mongodb-core/commit/345e6af)) - - -### Features - -* **connection:** Implement fast fallback ([622394a](https://github.com/mongodb-js/mongodb-core/commit/622394a)) - - - -<a name="3.1.3"></a> -## [3.1.3](https://github.com/mongodb-js/mongodb-core/compare/v3.1.2...v3.1.3) (2018-08-25) - - -### Bug Fixes - -* **buffer:** use safe-buffer polyfill to maintain compatibility ([728d897](https://github.com/mongodb-js/mongodb-core/commit/728d897)) -* **EJSON:** export the result of optionally requiring EJSON ([645d73d](https://github.com/mongodb-js/mongodb-core/commit/645d73d)) - - -### Features - -* **kerberos:** bump kerberos dependency to `^1.0.0` ([1155ebe](https://github.com/mongodb-js/mongodb-core/commit/1155ebe)) -* **standard-version:** automate part of the release process ([4c768c4](https://github.com/mongodb-js/mongodb-core/commit/4c768c4)) - - - -<a name="3.1.2"></a> -## [3.1.2](https://github.com/mongodb-js/mongodb-core/compare/v3.1.1...v3.1.2) (2018-08-13) - - -### Bug Fixes - -* **mongos:** fix connection leak when mongos reconnects ([2453746](https://github.com/mongodb-js/mongodb-core/commit/2453746)) - - -### Features - -* **bson:** update to bson ^1.1.x ([952a2f0](https://github.com/mongodb-js/mongodb-core/commit/952a2f0)) - - - -<a name="3.1.1"></a> -## [3.1.1](https://github.com/mongodb-js/mongodb-core/compare/v3.0.6...v3.1.1) (2018-08-13) - - -### Bug Fixes - -* **auth:** prevent stalling on authentication when connected ([6b4ac89](https://github.com/mongodb-js/mongodb-core/commit/6b4ac89)) -* **buffer:** replace deprecated Buffer constructor ([7c71e19](https://github.com/mongodb-js/mongodb-core/commit/7c71e19)) -* **commands:** check doc.cursor errors ([4f2b263](https://github.com/mongodb-js/mongodb-core/commit/4f2b263)) -* **cursor:** check for session presence independently ([7c76c62](https://github.com/mongodb-js/mongodb-core/commit/7c76c62)) -* **cursor:** check for sessions independently in core cursor ([cb5df28](https://github.com/mongodb-js/mongodb-core/commit/cb5df28)) -* **cursor:** typo in _find() ([95f7fd2](https://github.com/mongodb-js/mongodb-core/commit/95f7fd2)) -* **error:** attach command response to MongoWriteConcernError ([#322](https://github.com/mongodb-js/mongodb-core/issues/322)) ([24c5d06](https://github.com/mongodb-js/mongodb-core/commit/24c5d06)) -* **getmore-killcursor:** slaveOk shall not be included on these ([40fb2f4](https://github.com/mongodb-js/mongodb-core/commit/40fb2f4)) -* **kerberos:** loosen restrictions on kerberos versions ([c4add26](https://github.com/mongodb-js/mongodb-core/commit/c4add26)) -* **mongos:** use `incrementTransactionNumber` directly on session ([e230d54](https://github.com/mongodb-js/mongodb-core/commit/e230d54)) -* **pool:** ensure that lsid is sent in get requests to mongos ([ae820f6](https://github.com/mongodb-js/mongodb-core/commit/ae820f6)) -* **read-preference:** correct server sort for `nearest` selection ([dd4eb9a](https://github.com/mongodb-js/mongodb-core/commit/dd4eb9a)) -* **sdam:** we can't use Array.includes yet ([9c3b5ab](https://github.com/mongodb-js/mongodb-core/commit/9c3b5ab)) -* **server:** correct typo using `this` instead of `server` ([c54f040](https://github.com/mongodb-js/mongodb-core/commit/c54f040)) -* **sessions:** add `toBSON` method to `ClientSession` ([d95a4d1](https://github.com/mongodb-js/mongodb-core/commit/d95a4d1)) -* **sessions:** never send `endSessions` from a `ClientSession` ([05ffe82](https://github.com/mongodb-js/mongodb-core/commit/05ffe82)) -* **topology-description:** we can't use Object.values yet ([91df350](https://github.com/mongodb-js/mongodb-core/commit/91df350)) -* **transactions:** do not send txnNumber for non-write commands ([#308](https://github.com/mongodb-js/mongodb-core/issues/308)) ([eb67b1a](https://github.com/mongodb-js/mongodb-core/commit/eb67b1a)) -* **uri_parser:** ensure default port is 27017 ([426a95e](https://github.com/mongodb-js/mongodb-core/commit/426a95e)) -* **uri-parser:** Incorrect parsing of arrays ([fcff104](https://github.com/mongodb-js/mongodb-core/commit/fcff104)) -* **uri-parser:** Parse comma separated option values ([2dd1de0](https://github.com/mongodb-js/mongodb-core/commit/2dd1de0)) -* **wireprotocol:** only send bypassDocumentValidation if true ([a81678b](https://github.com/mongodb-js/mongodb-core/commit/a81678b)) - - -### Features - -* **auth:** adds saslprep and SCRAM-SHA-256 ([506c087](https://github.com/mongodb-js/mongodb-core/commit/506c087)) -* **cursor:** implement cursor for new sdam implementation ([f289226](https://github.com/mongodb-js/mongodb-core/commit/f289226)) -* **cursor:** store operation time from initial query ([55e761e](https://github.com/mongodb-js/mongodb-core/commit/55e761e)) -* **error:** add more specific error type for write concern errors ([347c5d7](https://github.com/mongodb-js/mongodb-core/commit/347c5d7)) -* **Error:** adding error metadata field ([33be560](https://github.com/mongodb-js/mongodb-core/commit/33be560)) -* **kerberos:** expose warning for kerberos mismatch versions ([efc0e43](https://github.com/mongodb-js/mongodb-core/commit/efc0e43)) -* **max-staleness:** properly support a max staleness reducer ([d9c5c16](https://github.com/mongodb-js/mongodb-core/commit/d9c5c16)) -* **MongoTimeoutError:** add common class for timeout events ([c5b4752](https://github.com/mongodb-js/mongodb-core/commit/c5b4752)) -* **monitoring:** add support for server monitoring to `Server` ([30a394d](https://github.com/mongodb-js/mongodb-core/commit/30a394d)) -* **op-compressed:** add support for OP_COMPRESSED to new sdam impl ([8deec9b](https://github.com/mongodb-js/mongodb-core/commit/8deec9b)) -* **retryableWrites:** adding more support for retries ([d4c1597](https://github.com/mongodb-js/mongodb-core/commit/d4c1597)) -* **sdam-monitoring:** add basic monitoring for new Topology type ([bb0c522](https://github.com/mongodb-js/mongodb-core/commit/bb0c522)) -* **server:** add `command` support to new server class ([d9a8c05](https://github.com/mongodb-js/mongodb-core/commit/d9a8c05)) -* **server-selection:** add basic support for server selection ([ccc5e1d](https://github.com/mongodb-js/mongodb-core/commit/ccc5e1d)) -* **topology:** introduce a single Topology type, and test runner ([f35d773](https://github.com/mongodb-js/mongodb-core/commit/f35d773)) -* **topology-description:** add helper method for server ownership ([2c64c75](https://github.com/mongodb-js/mongodb-core/commit/2c64c75)) -* **txns:** add initial transaction interface for sessions ([ed76be0](https://github.com/mongodb-js/mongodb-core/commit/ed76be0)) - - - -<a name="3.1.0"></a> -# [3.1.0](https://github.com/mongodb-js/mongodb-core/compare/v3.0.6...v3.1.0) (2018-06-27) - - -### Bug Fixes - -* **auth:** prevent stalling on authentication when connected ([6b4ac89](https://github.com/mongodb-js/mongodb-core/commit/6b4ac89)) -* **cursor:** check for session presence independently ([7c76c62](https://github.com/mongodb-js/mongodb-core/commit/7c76c62)) -* **cursor:** check for sessions independently in core cursor ([cb5df28](https://github.com/mongodb-js/mongodb-core/commit/cb5df28)) -* **error:** attach command response to MongoWriteConcernError ([#322](https://github.com/mongodb-js/mongodb-core/issues/322)) ([24c5d06](https://github.com/mongodb-js/mongodb-core/commit/24c5d06)) -* **getmore-killcursor:** slaveOk shall not be included on these ([40fb2f4](https://github.com/mongodb-js/mongodb-core/commit/40fb2f4)) -* **kerberos:** loosen restrictions on kerberos versions ([c4add26](https://github.com/mongodb-js/mongodb-core/commit/c4add26)) -* **mongos:** use `incrementTransactionNumber` directly on session ([e230d54](https://github.com/mongodb-js/mongodb-core/commit/e230d54)) -* **pool:** ensure that lsid is sent in get requests to mongos ([ae820f6](https://github.com/mongodb-js/mongodb-core/commit/ae820f6)) -* **sdam:** we can't use Array.includes yet ([9c3b5ab](https://github.com/mongodb-js/mongodb-core/commit/9c3b5ab)) -* **sessions:** add `toBSON` method to `ClientSession` ([d95a4d1](https://github.com/mongodb-js/mongodb-core/commit/d95a4d1)) -* **sessions:** never send `endSessions` from a `ClientSession` ([05ffe82](https://github.com/mongodb-js/mongodb-core/commit/05ffe82)) -* **topology-description:** we can't use Object.values yet ([91df350](https://github.com/mongodb-js/mongodb-core/commit/91df350)) -* **transactions:** do not send txnNumber for non-write commands ([#308](https://github.com/mongodb-js/mongodb-core/issues/308)) ([eb67b1a](https://github.com/mongodb-js/mongodb-core/commit/eb67b1a)) -* **wireprotocol:** only send bypassDocumentValidation if true ([a81678b](https://github.com/mongodb-js/mongodb-core/commit/a81678b)) - - -### Features - -* **auth:** adds saslprep and SCRAM-SHA-256 ([506c087](https://github.com/mongodb-js/mongodb-core/commit/506c087)) -* **cursor:** implement cursor for new sdam implementation ([f289226](https://github.com/mongodb-js/mongodb-core/commit/f289226)) -* **cursor:** store operation time from initial query ([55e761e](https://github.com/mongodb-js/mongodb-core/commit/55e761e)) -* **error:** add more specific error type for write concern errors ([347c5d7](https://github.com/mongodb-js/mongodb-core/commit/347c5d7)) -* **Error:** adding error metadata field ([33be560](https://github.com/mongodb-js/mongodb-core/commit/33be560)) -* **kerberos:** expose warning for kerberos mismatch versions ([efc0e43](https://github.com/mongodb-js/mongodb-core/commit/efc0e43)) -* **max-staleness:** properly support a max staleness reducer ([d9c5c16](https://github.com/mongodb-js/mongodb-core/commit/d9c5c16)) -* **MongoTimeoutError:** add common class for timeout events ([c5b4752](https://github.com/mongodb-js/mongodb-core/commit/c5b4752)) -* **op-compressed:** add support for OP_COMPRESSED to new sdam impl ([8deec9b](https://github.com/mongodb-js/mongodb-core/commit/8deec9b)) -* **retryableWrites:** adding more support for retries ([d4c1597](https://github.com/mongodb-js/mongodb-core/commit/d4c1597)) -* **sdam-monitoring:** add basic monitoring for new Topology type ([bb0c522](https://github.com/mongodb-js/mongodb-core/commit/bb0c522)) -* **server:** add `command` support to new server class ([d9a8c05](https://github.com/mongodb-js/mongodb-core/commit/d9a8c05)) -* **server-selection:** add basic support for server selection ([ccc5e1d](https://github.com/mongodb-js/mongodb-core/commit/ccc5e1d)) -* **topology:** introduce a single Topology type, and test runner ([f35d773](https://github.com/mongodb-js/mongodb-core/commit/f35d773)) -* **topology-description:** add helper method for server ownership ([2c64c75](https://github.com/mongodb-js/mongodb-core/commit/2c64c75)) -* **txns:** add initial transaction interface for sessions ([ed76be0](https://github.com/mongodb-js/mongodb-core/commit/ed76be0)) - - - -<a name="3.0.6"></a> -## [3.0.6](https://github.com/mongodb-js/mongodb-core/compare/v3.0.5...v3.0.6) (2018-04-09) - - -### Bug Fixes - -* **2.6-protocol:** kill cursor callback is called by pool now ([65f2bf7](https://github.com/mongodb-js/mongodb-core/commit/65f2bf7)) -* **evergreen:** change name to id ([9303e12](https://github.com/mongodb-js/mongodb-core/commit/9303e12)) -* **evergreen:** change nvm path to local ([e42ea5b](https://github.com/mongodb-js/mongodb-core/commit/e42ea5b)) -* **evergreen:** pass in flag through npm scripts ([85708dd](https://github.com/mongodb-js/mongodb-core/commit/85708dd)) -* **pool:** ensure noResponse callback is only called if cb exists ([5281605](https://github.com/mongodb-js/mongodb-core/commit/5281605)) -* **replset:** only remove primary if primary is there ([1acd288](https://github.com/mongodb-js/mongodb-core/commit/1acd288)) -* **test-environments:** ensure all servers run on separate ports ([b63e5d8](https://github.com/mongodb-js/mongodb-core/commit/b63e5d8)) -* **uri_parser:** support a default database on mongodb+srv uris ([be01ffe](https://github.com/mongodb-js/mongodb-core/commit/be01ffe)) - - -### Features - -* **apm:** add events for command monitoring support in core ([37dce9c](https://github.com/mongodb-js/mongodb-core/commit/37dce9c)) -* **evergreen:** add evergreen config based on drivers skeleton ([b71da99](https://github.com/mongodb-js/mongodb-core/commit/b71da99)) -* **evergreen:** use evergreen flag when running tests ([55dff3b](https://github.com/mongodb-js/mongodb-core/commit/55dff3b)) - - - -<a name="3.0.5"></a> -## [3.0.5](https://github.com/mongodb-js/mongodb-core/compare/v3.0.4...v3.0.5) (2018-03-14) - - -### Features - -* **sessions:** adding implicit cursor session support ([1607321](https://github.com/mongodb-js/mongodb-core/commit/1607321)) - - - -<a name="3.0.4"></a> -## [3.0.4](https://github.com/mongodb-js/mongodb-core/compare/v3.0.3...v3.0.4) (2018-03-05) - - -### Bug Fixes - -* **connection:** ensure socket options are applied to ssl sockets ([e5ff927](https://github.com/mongodb-js/mongodb-core/commit/e5ff927)) - - - -<a name="3.0.3"></a> -## [3.0.3](https://github.com/mongodb-js/mongodb-core/compare/v3.0.2...v3.0.3) (2018-02-23) - - -### Bug Fixes - -* **connection:** make pool not try to reconnect forever when reconnectTries = 0 ([#275](https://github.com/mongodb-js/mongodb-core/issues/275)) ([2d3fa98](https://github.com/mongodb-js/mongodb-core/commit/2d3fa98)), closes [Automattic/mongoose#6028](https://github.com/Automattic/mongoose/issues/6028) -* **retryableWrites:** only remove primary after retry ([#274](https://github.com/mongodb-js/mongodb-core/issues/274)) ([7ac171e](https://github.com/mongodb-js/mongodb-core/commit/7ac171e)) -* **sessions:** actually allow ending of sessions ([2b81bb6](https://github.com/mongodb-js/mongodb-core/commit/2b81bb6)) -* **uri-parser:** do not use `hasOwnProperty` to detect ssl ([69d16c7](https://github.com/mongodb-js/mongodb-core/commit/69d16c7)) - - -### Features - -* **sessions:** adding endAllPooledSessions helper method ([d7804ed](https://github.com/mongodb-js/mongodb-core/commit/d7804ed)) - - - -<a name="3.0.2"></a> -## [3.0.2](https://github.com/mongodb-js/mongodb-core/compare/v3.0.1...v3.0.2) (2018-01-29) - - -### Bug Fixes - -* **cursor:** check for autoReconnect option only for single server ([645d6df](https://github.com/mongodb-js/mongodb-core/commit/645d6df)) - - -### Features - -* **mongodb+srv:** add support for mongodb+srv to the uri parser ([19b42ce](https://github.com/mongodb-js/mongodb-core/commit/19b42ce)) -* **uri-parser:** add initial implementation of uri parser for core ([8f797a7](https://github.com/mongodb-js/mongodb-core/commit/8f797a7)) -* **uri-parser:** expose the connection string parser as api ([fdeca2f](https://github.com/mongodb-js/mongodb-core/commit/fdeca2f)) - - - -<a name="3.0.1"></a> -## [3.0.1](https://github.com/mongodb-js/mongodb-core/compare/v3.0.0...v3.0.1) (2017-12-24) - - -### Bug Fixes - -* **connection:** correct erroneous use of `this` in helper method ([06b9388](https://github.com/mongodb-js/mongodb-core/commit/06b9388)) - - - -<a name="3.0.0"></a> -# [3.0.0](https://github.com/christkv/mongodb-core/compare/v3.0.0-rc0...v3.0.0) (2017-12-23) - - -### Bug Fixes - -* **connection:** ensure connection cleanup before fallback retry ([de62615](https://github.com/christkv/mongodb-core/commit/de62615)) -* **mock-server:** expose potential errors in message handlers ([65dcca4](https://github.com/christkv/mongodb-core/commit/65dcca4)) -* **mongos:** remove listener on destroy event ([243e942](https://github.com/christkv/mongodb-core/commit/243e942)), closes [#257](https://github.com/christkv/mongodb-core/issues/257) -* **sdam:** more explicit wire protocol error message ([6d6d19a](https://github.com/christkv/mongodb-core/commit/6d6d19a)) -* **secondaries:** fixes connection with secondary readPreference ([#258](https://github.com/christkv/mongodb-core/issues/258)) ([0060ad7](https://github.com/christkv/mongodb-core/commit/0060ad7)) -* **sessions:** ensure that we ignore session details from arbiters ([de0105c](https://github.com/christkv/mongodb-core/commit/de0105c)) -* **sharded-tests:** add `shardsvr` cmdline opt, wait for async fns ([867b080](https://github.com/christkv/mongodb-core/commit/867b080)) - - -### Features - -* **connection:** attempt both ipv6 and ipv4 when no family entered ([#260](https://github.com/christkv/mongodb-core/issues/260)) ([107bae5](https://github.com/christkv/mongodb-core/commit/107bae5)) - - - -<a name="3.0.0-rc0"></a> -# 3.0.0-rc0 (2017-12-05) - - -### Bug Fixes - -* **auth-plain:** only use BSON -after- requiring it ([4934adf](https://github.com/christkv/mongodb-core/commit/4934adf)) -* **auth-scram:** cache the ScramSHA1 salted passwords up to 200 entries ([31ef03a](https://github.com/christkv/mongodb-core/commit/31ef03a)) -* **client-session:** don't report errors for endSessions commands ([c34eaf5](https://github.com/christkv/mongodb-core/commit/c34eaf5)) -* **connection:** default `family` to undefined rather than 4 ([c1b5e04](https://github.com/christkv/mongodb-core/commit/c1b5e04)) -* **connection:** fixing leak in 3.0.0 ([#235](https://github.com/christkv/mongodb-core/issues/235)) ([fc669c0](https://github.com/christkv/mongodb-core/commit/fc669c0)) -* **cursor:** avoid waiting for reconnect if reconnect disabled ([43e9b23](https://github.com/christkv/mongodb-core/commit/43e9b23)) -* **cursor:** callback with server response on `_find` ([6999459](https://github.com/christkv/mongodb-core/commit/6999459)) -* **errors:** export MongoError and MongoNetworkError at top-level ([972064a](https://github.com/christkv/mongodb-core/commit/972064a)) -* **errors:** throw MongoNetworkError from more places ([2cec239](https://github.com/christkv/mongodb-core/commit/2cec239)) -* **errors:** use subclassing for MongoNetworkError ([a132830](https://github.com/christkv/mongodb-core/commit/a132830)) -* **errors:** use util.inherits() and protect edge case ([c953246](https://github.com/christkv/mongodb-core/commit/c953246)) -* **mocha_server_tests:** rename confusing variable to fix tests ([a9fbae2](https://github.com/christkv/mongodb-core/commit/a9fbae2)) -* **mock-tests:** ensure all servers are properly cleaned up ([5dafc86](https://github.com/christkv/mongodb-core/commit/5dafc86)) -* **package:** upgrade mongodb-test-runner with bug fix ([5b2e99e](https://github.com/christkv/mongodb-core/commit/5b2e99e)) -* **pool:** check topology exists before verifying session support ([0aa146d](https://github.com/christkv/mongodb-core/commit/0aa146d)) -* **pool:** ensure inUse and connecting queues are cleared on reauth ([aa2840d](https://github.com/christkv/mongodb-core/commit/aa2840d)) -* **pool:** ensure that errors are propagated on force destroy ([8f8ad56](https://github.com/christkv/mongodb-core/commit/8f8ad56)) -* **pool:** ensure workItem is not null before accessing properties ([2143963](https://github.com/christkv/mongodb-core/commit/2143963)) -* **pool_tests:** remove .only ([8172137](https://github.com/christkv/mongodb-core/commit/8172137)) -* **retryable-writes:** don't increment `txnNumber` on retries ([e7c2242](https://github.com/christkv/mongodb-core/commit/e7c2242)) -* **retryable-writes:** network errors are retryable, inverted logic ([2727551](https://github.com/christkv/mongodb-core/commit/2727551)) -* **scram:** cache salted data, not the original data ([0cbe95f](https://github.com/christkv/mongodb-core/commit/0cbe95f)) -* **SDAM:** emit SDAM events on close and reconnect ([3451ff0](https://github.com/christkv/mongodb-core/commit/3451ff0)) -* **server:** avoid waiting for reconnect if reconnect disabled ([611a352](https://github.com/christkv/mongodb-core/commit/611a352)) -* **server:** correct minor typo in porting 2.x patch ([d92efec](https://github.com/christkv/mongodb-core/commit/d92efec)) -* **server_tests:** change 'this' to 'self' in some server tests ([992d9e9](https://github.com/christkv/mongodb-core/commit/992d9e9)) -* **server_tests:** fix errors in broken test ([1602e4d](https://github.com/christkv/mongodb-core/commit/1602e4d)) -* **server-session-pool:** don't add expired sessions to the pool ([8f48b89](https://github.com/christkv/mongodb-core/commit/8f48b89)) -* **server-session-pool:** ensure the queue is LIFO ([ac68e76](https://github.com/christkv/mongodb-core/commit/ac68e76)) -* **utils:** don't throw if no snappy ([55bf2ad](https://github.com/christkv/mongodb-core/commit/55bf2ad)) -* **wire-protocol:** 2.6 killCursor should not way for reply ([7337d91](https://github.com/christkv/mongodb-core/commit/7337d91)) - - -### Features - -* **cluster-time:** ensure clusterTime makes it to outgoing commands ([e700b79](https://github.com/christkv/mongodb-core/commit/e700b79)) -* **cluster-time:** track incoming cluster time gossiping ([c910706](https://github.com/christkv/mongodb-core/commit/c910706)) -* **compression:** implement wire protocol compression support ([2356ffb](https://github.com/christkv/mongodb-core/commit/2356ffb)) -* **connection-spy:** add class for monitoring active connections ([6dd6db3](https://github.com/christkv/mongodb-core/commit/6dd6db3)) -* **errors:** create MongoNetworkError ([df12740](https://github.com/christkv/mongodb-core/commit/df12740)) -* **inital-cluster-time:** allow session to define initia value ([e3a1c8b](https://github.com/christkv/mongodb-core/commit/e3a1c8b)) -* **mock:** support a means of consistently cleaning up mock servers ([ab3b70b](https://github.com/christkv/mongodb-core/commit/ab3b70b)) -* **mock-server:** add the ability to set a message handler ([9a8b815](https://github.com/christkv/mongodb-core/commit/9a8b815)) -* **operation-time:** track operationTime in relevant sessions ([8d512f1](https://github.com/christkv/mongodb-core/commit/8d512f1)) -* **pool:** introduce the concept of a minimum pool size ([b01b1f8](https://github.com/christkv/mongodb-core/commit/b01b1f8)) -* **replset:** more verbose replica set errors emission ([6d5eccd](https://github.com/christkv/mongodb-core/commit/6d5eccd)) -* **retryable-writes:** add mongos support for retryable writes ([7778067](https://github.com/christkv/mongodb-core/commit/7778067)) -* **retryable-writes:** initial support on replicasets ([73ac688](https://github.com/christkv/mongodb-core/commit/73ac688)) -* **retryable-writes:** retry on "not master" stepdown errors ([028aec7](https://github.com/christkv/mongodb-core/commit/028aec7)) -* **server-check:** reintroduce server version check ([486aace](https://github.com/christkv/mongodb-core/commit/486aace)) -* **server-session-pool:** implement session pool per spect ([a1d5b22](https://github.com/christkv/mongodb-core/commit/a1d5b22)) -* **session:** allow `session` options to be passed to write cmds ([5da75e4](https://github.com/christkv/mongodb-core/commit/5da75e4)) -* **sessions:** add equality operator to ease readability ([6510d7d](https://github.com/christkv/mongodb-core/commit/6510d7d)) -* **sessions:** export all sessions types on the top level ([35265b3](https://github.com/christkv/mongodb-core/commit/35265b3)) -* **sessions:** support sessions with cursors with find/getMore ([a016602](https://github.com/christkv/mongodb-core/commit/a016602)) -* **sessions:** track `logicalSessionTimeoutMinutes` for sessions ([11865bf](https://github.com/christkv/mongodb-core/commit/11865bf)) -* **ssl:** adding ssl options ciphers and ecdhCurve ([c839d5c](https://github.com/christkv/mongodb-core/commit/c839d5c)) -* **test/:** convert server_tests, undefined_tests, replset_tests, replset_state_tests, and repleset_server_selection_tests to run with mongodb-test-runner ([3a7c5fd](https://github.com/christkv/mongodb-core/commit/3a7c5fd)) - - -2.1.16 2017-10-11 ------------------ -* avoid waiting for reconnect if reconnect disabled in Server topology -* avoid waiting for reconnect if reconnect disabled in Cursor -* NODE-990 cache the ScramSHA1 salted passwords up to 200 entries -* NODE-1153 ensure that errors are propagated on force destroy -* NODE-1153 ensure inUse and connecting queues are cleared on reauth - -2.1.15 2017-08-08 ------------------ -* Emit SDAM events on close and reconnect - -2.1.14 2017-07-07 ------------------ -* NODE-1073 updates scram.js hi() algorithm to utilize crypto.pbkdf2Sync() -* NODE-1049 only include primary server if there are no secondary servers for - readPrefrence secondaryPreferred -* moved `assign` polyfill to shared utils, replace usage of `extend` in tests - -2.1.13 2017-06-19 ------------------ -* NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. -* Use actual server type in standalone SDAM events. - -2.1.12 2017-06-02 ------------------ -* NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. -* Minor fix to report the correct state on error. -* NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). -* Fix require_optional loading of bson-ext. -* Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. -* NODE-999 SDAM fixes for Mongos and single Server event emitting. -* NODE-1014 Set socketTimeout to default to 360 seconds. -* NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. - -2.1.11 2017-05-22 ------------------ -* NODE-987 Clear out old intervalIds on when calling topologyMonitor. -* NODE-987 Moved filtering to pingServer method and added test case. -* Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). -* NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interva. - -2.1.10 2017-04-18 ------------------ -* NODE-981 delegate auth to replset/mongos if inTopology is set. -* NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. -* Remove dynamic require (Issue #175, https://github.com/tellnes). -* NODE-696 Handle interrupted error for createIndexes. -* Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. -* NODE-966 promoteValues not being promoted correctly to getMore. -* Merged in fix for flushing out monitoring operations. - -2.1.9 2017-03-17 ----------------- -* Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. -* Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. -* Ensure SSL error propegates better for Replset connections when there is a SSL validation error. -* NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. -* NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. - -2.1.8 2017-02-13 ----------------- -* NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. -* NODE-927 fixes issue where authentication was performed against arbiter instances. -* NODE-915 Normalize all host names to avoid comparison issues. -* Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. - -2.1.7 2017-01-24 ----------------- -* NODE-919 ReplicaSet connection does not close immediately (Issue #156). -* NODE-901 Fixed bug when normalizing host names. -* NODE-909 Fixed readPreference issue caused by direct connection to primary. -* NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. - -2.1.6 2017-01-13 ----------------- -* NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. - -2.1.5 2017-01-11 ----------------- -* updated bson and bson-ext dependencies to 1.0.4 to work past early node 4.x.x version having a broken Buffer.from implementation. - -2.1.4 2017-01-03 ----------------- -* updated bson and bson-ext dependencies to 1.0.3 due to util.inspect issue with ObjectId optimizations. - -2.1.3 2017-01-03 ----------------- -* Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining -* Moved replicaset monitoring away from serial mode and to parallel mode. -* updated bson and bson-ext dependencies to 1.0.2. - -2.1.2 2016-12-10 ----------------- -* Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. -* Emit reconnect event in primary joining when in connected status for a replicaset. - -2.1.1 2016-12-08 ----------------- -* Updated bson library to 1.0.1. -* Added optional support for bson-ext 1.0.1. - -2.1.0 2016-12-05 ----------------- -* Updated bson library to 1.0.0. -* Added optional support for bson-ext 1.0.0. -* Expose property parserType allowing for identification of currently configured parser. - -2.0.14 2016-11-29 ------------------ -* Updated bson library to 0.5.7. -* Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). -* Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). -* Only check isConnected against availableConnections (Issue #142). -* NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. -* Set default servername to host is not passed through for sni. -* Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). -* NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. -* NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. -* NODE-850 Update Max Staleness implementation. -* NODE-849 username no longer required for MONGODB-X509 auth. -* NODE-848 BSON Regex flags must be alphabetically ordered. -* NODE-846 Create notice for all third party libraries. -* NODE-843 Executing bulk operations overwrites write concern parameter. -* NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. -* NODE-840 Resync CRUD spec tests. -* Unescapable while(true) loop (Issue #152). - -2.0.13 2016-10-21 ------------------ -* Updated bson library to 0.5.6. - - Included cyclic dependency detection -* Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). -* Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). -* Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). -* NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). - -2.0.12 2016-09-15 ------------------ -* fix debug logging message not printing server name. -* fixed application metadata being sent by wrong ismaster. -* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. -* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". -* Updated bson library to 0.5.5. -* Added DBPointer up conversion to DBRef. - -2.0.11 2016-08-29 ------------------ -* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. -* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). -* Ensure promoteBuffers is propagated in same fashion as promoteValues and promoteLongs - -2.0.10 2016-08-23 ------------------ -* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. -* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). - -2.0.9 2016-08-19 ----------------- -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* NODE-798 Driver hangs on count command in replica set with one member. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* Allow passing in servername for TLS connections for SNI support. - -2.0.8 2016-08-16 ----------------- -* Allow execution of store operations indepent of having both a primary and secondary available (Issue #123). -* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. -* Added hashed connection names and fullResult. -* Updated bson library to 0.5.3. -* Wrap callback in nextTick to ensure exceptions are thrown correctly. - -2.0.7 2016-07-28 ----------------- -* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). -* Added better warnings when passing in illegal seed list members to a Mongos topology. -* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. -* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) -* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. -* Initial max staleness implementation for ReplSet and Mongos for 3.4 support. -* Added handling of collation for 3.4 support. - -2.0.6 2016-07-19 ----------------- -* Destroy connection on socket timeout due to newer node versions not closing the socket. - -2.0.5 2016-07-15 ----------------- -* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. -* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. -* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. -* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. - -2.0.4 2016-07-11 ------------------ -* Updated bson to version 0.5.1. -* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. -* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. -* NODE-746 Improves replicaset errors for wrong setName. - -2.0.3 2016-07-08 ------------------ -* Implemented Server Selection Specification test suite. -* Added warning level to logger. -* Added warning message when sockeTimeout < haInterval for Replset/Mongos. - -2.0.2 2016-07-06 ------------------ -* Mongos emits close event on no proxies available or when reconnect attempt fails. -* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. -* Don't throw in auth methods but return error in callback. - -2.0.1 2016-07-05 ------------------ -* Added missing logout method on mongos proxy topology. -* Fixed logger error serialization issue. -* Documentation fixes. - -2.0.0 2016-07-05 ------------------ -* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. -* All authentication methods now handle both auth/reauthenticate and logout events. -* Introduced logout method to get rid of onAll option for logout command. -* Updated bson to 0.5.0 that includes Decimal128 support. - -1.3.21 2016-05-30 ------------------ -* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). -* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. -* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. -* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). -* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. -* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. - -1.3.20 2016-05-25 ------------------ -* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. -* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. -* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. -* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. - -1.3.19 2016-05-17 ------------------ -- Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. -- Set keepAlive to false by default to work around bug in node.js for Windows XP and Windows 2003. -- Ensure replicaset topology destroy is never called by SDAM. -- Ensure all paths are correctly returned on inspectServer in replset. - -1.3.18 2016-04-27 ------------------ -- Hardened cursor connection handling for getMore and killCursor to ensure mid operation connection kill does not throw null exception. -- Fixes for Node 6.0 support. - -1.3.17 2016-04-26 ------------------ -- Added improved handling of reconnect when topology is a single server. -- Added better handling of $query queries passed down for 3.2 or higher. -- Introduced getServerFrom method to topologies to let cursor grab a new pool for getMore and killCursors commands and not use connection pipelining. -- NODE-693 Move authentication to be after ismaster call to avoid authenticating against arbiters. - -1.3.16 2016-04-07 ------------------ -- Only call unref on destroy if it exists to ensure proper working destroy method on early node v0.10.x versions. - -1.3.15 2016-04-06 ------------------ -- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. -- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. - -1.3.14 2016-04-01 ------------------ -- Ensure server inquireServerState exits immediately on server.destroy call. -- Refactored readPreference handling in 2.4, 2.6 and 3.2 wire protocol handling. - -1.3.13 2016-03-30 ------------------ -- Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. - -1.3.12 2016-03-29 ------------------ -- Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. - -1.3.11 2016-03-29 ------------------ -- isConnected method for mongos uses same selection code as getServer. -- Exceptions in cursor getServer trapped and correctly delegated to high level handler. - -1.3.10 2016-03-22 ------------------ -- SDAM Monitoring emits diff for Replicasets to simplify detecting the state changes. -- SDAM Monitoring correctly emits Mongos as serverDescriptionEvent. - -1.3.9 2016-03-20 ----------------- -- Removed monitoring exclusive connection, should resolve timeouts and reconnects on idle replicasets where haInteval > socketTimeout. - -1.3.8 2016-03-18 ----------------- -- Implements the SDAM monitoring specification. -- Fix issue where cursor would error out and not be buffered when primary is not connected. - -1.3.7 2016-03-16 ----------------- -- Fixed issue with replicasetInquirer where it could stop performing monitoring if there was no servers available. - -1.3.6 2016-03-15 ----------------- -- Fixed raise condition where multiple replicasetInquirer operations could be started in parallel creating redundant connections. - -1.3.5 2016-03-14 ----------------- -- Handle rogue SSL exceptions (Issue #85, https://github.com/durran). - -1.3.4 2016-03-14 ----------------- -- Added unref options on server, replicaset and mongos (Issue #81, https://github.com/allevo) -- cursorNotFound flag always false (Issue #83, https://github.com/xgfd) -- refactor of events emission of fullsetup and all events (Issue #84, https://github.com/xizhibei) - -1.3.3 2016-03-08 ----------------- -- Added support for promoteLongs option for command function. -- Return connection if no callback available -- Emit connect event when server reconnects after initial connection failed (Issue #76, https://github.com/vkarpov15) -- Introduced optional monitoringSocketTimeout option to allow better control of SDAM monitoring timeouts. -- Made monitoringSocketTimeout default to 30000 if no connectionTimeout value specified or if set to 0. -- Fixed issue where tailable cursor would not retry even though cursor was still alive. -- Disabled exhaust flag support to avoid issues where users could easily write code that would cause memory to run out. -- Handle the case where the first command result document returns an empty list of documents but a live cursor. -- Allow passing down off CANONICALIZE_HOST_NAME and SERVICE_REALM options for kerberos. - -1.3.2 2016-02-09 ----------------- -- Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. -- Ensure RequestId can never be larger than Max Number integer size. - -1.3.1 2016-02-05 ----------------- -- Removed annoying missing Kerberos error (NODE-654). - -1.3.0 2016-02-03 ----------------- -- Added raw support for the command function on topologies. -- Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) -- Copy over all the properties to the callback returned from bindToDomain, (Issue #72) -- Added connection hash id to be able to reference connection host/name without leaking it outside of driver. -- NODE-638, Cannot authenticate database user with utf-8 password. -- Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. -- Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. -- Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. -- Switched to using Array.push instead of concat for use cases of a lot of documents. -- Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. -- Added peer optional dependencies support using require_optional module. - -1.2.32 2016-01-12 ------------------ -- Bumped bson to V0.4.21 to allow using minor optimizations. - -1.2.31 2016-01-04 ------------------ -- Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) - -1.2.30 2015-12-23 ------------------ -- Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -- Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -1.2.29 2015-12-17 ------------------ -- Correctly emit close event when calling destroy on server topology. - -1.2.28 2015-12-13 ------------------ -- Backed out Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous) as it breaks node 0.10.x support. - -1.2.27 2015-12-13 ------------------ -- Added [options.checkServerIdentity=true] {boolean|function}. Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function, (Issue #29). -- Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous). -- State is not defined in mongos, (Issue #63, https://github.com/flyingfisher). -- Fixed corner case issue on exhaust cursors on pre 3.0.x MongoDB. - -1.2.26 2015-11-23 ------------------ -- Converted test suite to use mongodb-topology-manager. -- Upgraded bson library to V0.4.20. -- Minor fixes for 3.2 readPreferences. - -1.2.25 2015-11-23 ------------------ -- Correctly error out when passed a seedlist of non-valid server members. - -1.2.24 2015-11-20 ------------------ -- Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). -- $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. - -1.2.23 2015-11-16 ------------------ -- ismaster runs against admin.$cmd instead of system.$cmd. - -1.2.22 2015-11-16 ------------------ -- Fixes to handle getMore command errors for MongoDB 3.2 -- Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. - -1.2.21 2015-11-07 ------------------ -- Hardened the checking for replicaset equality checks. -- OpReplay flag correctly set on Wire protocol query. -- Mongos load balancing added, introduced localThresholdMS to control the feature. -- Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. - -1.2.20 2015-10-28 ------------------ -- Fixed bug in arbiter connection capping code. -- NODE-599 correctly handle arrays of server tags in order of priority. -- Fix for 2.6 wire protocol handler related to readPreference handling. -- Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -- Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). - -1.2.19 2015-10-15 ------------------ -- Make batchSize always be > 0 for 3.2 wire protocol to make it work consistently with pre 3.2 servers. -- Locked to bson 0.4.19. - -1.2.18 2015-10-15 ------------------ -- Minor 3.2 fix for handling readPreferences on sharded commands. -- Minor fixes to correctly pass APM specification test suite. - -1.2.17 2015-10-08 ------------------ -- Connections to arbiters only maintain a single connection. - -1.2.15 2015-10-06 ------------------ -- Set slaveOk to true for getMore and killCursors commands. -- Don't swallow callback errors for 2.4 single server (Issue #49, https://github.com/vkarpov15). -- Apply toString('hex') to each buffer in an array when logging (Issue #48, https://github.com/nbrachet). - -1.2.14 2015-09-28 ------------------ -- NODE-547 only emit error if there are any listeners. -- Fixed APM issue with issuing readConcern. - -1.2.13 2015-09-18 ------------------ -- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. - -1.2.12 2015-09-08 ------------------ -- NODE-541 Added initial support for readConcern. - -1.2.11 2015-08-31 ------------------ -- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. -- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. -- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). - -1.2.10 2015-08-14 ------------------ -- Added missing Mongos.prototype.parserType function. - -1.2.9 2015-08-05 ----------------- -- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -- NODE-518 connectTimeoutMS is doubled in 2.0.39. - -1.2.8 2015-07-24 ------------------ -- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. - -1.2.7 2015-07-16 ------------------ -- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. - -1.2.6 2015-07-14 ------------------ -- NODE-505 Query fails to find records that have a 'result' property with an array value. - -1.2.5 2015-07-14 ------------------ -- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. - -1.2.4 2015-07-07 ------------------ -- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. - -1.2.3 2015-06-26 ------------------ -- Minor bug fixes. - -1.2.2 2015-06-22 ------------------ -- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). - -1.2.1 2015-06-17 ------------------ -- Ensure serializeFunctions passed down correctly to wire protocol. - -1.2.0 2015-06-17 ------------------ -- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. -- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. -- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -1.1.33 2015-05-31 ------------------ -- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. - -1.1.32 2015-05-20 ------------------ -- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) - -1.1.31 2015-05-19 ------------------ -- Minor fixes for issues with re-authentication of mongos. - -1.1.30 2015-05-18 ------------------ -- Correctly emit 'all' event when primary + all secondaries have connected. - -1.1.29 2015-05-17 ------------------ -- 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 2015-05-12 ------------------ -- Fixed buffer compare for electionId for < node 12.0.2 - -1.1.27 2015-05-12 ------------------ -- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. - -1.1.26 2015-05-06 ------------------ -- 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 2015-04-24 ------------------ -- Handle lack of callback in crud operations when returning error on application closed. - -1.1.24 2015-04-22 ------------------ -- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. - -1.1.23 2015-04-15 ------------------ -- 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 2015-04-10 ------------------ -- 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 2015-03-26 ------------------ -- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. - -1.1.20 2015-03-24 ------------------ -- 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 2015-03-21 ------------------ -- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. - -1.1.18 2015-03-17 ------------------ -- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. - -1.1.17 2015-03-16 ------------------ -- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. - -1.1.16 2015-03-06 ------------------ -- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. - -1.1.15 2015-03-04 ------------------ -- Removed check for type in replset pickserver function. - -1.1.14 2015-02-26 ------------------ -- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads - -1.1.13 2015-02-24 ------------------ -- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) - -1.1.12 2015-02-16 ------------------ -- Fixed cursor transforms for buffered document reads from cursor. - -1.1.11 2015-02-02 ------------------ -- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -1.1.10 2015-31-01 ------------------ -- Added tranforms.doc option to cursor to allow for pr. document transformations. - -1.1.9 2015-21-01 ----------------- -- 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 2015-09-12 ----------------- -- 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 2014-18-12 ----------------- -- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. - -1.1.6 2014-18-12 ----------------- -- Server manager fixed to support 2.2.X servers for travis test matrix. - -1.1.5 2014-17-12 ----------------- -- Fall back to errmsg when creating MongoError for command errors - -1.1.4 2014-17-12 ----------------- -- 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 2014-01-12 ----------------- -- 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 2014-20-11 ----------------- -- 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 2014-14-11 ----------------- -- 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 2014-29-10 ----------------- -- Fixed issue with wrong namespace being created for command cursors. - -1.0.4 2014-24-10 ----------------- -- 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 2014-21-10 ----------------- -- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. - -1.0.2 2014-07-10 ----------------- -- 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 2014-07-10 ----------------- -- Dependency issue solved - -1.0.0 2014-07-10 ----------------- -- Initial release of mongodb-core diff --git a/node_modules/mongodb-core/LICENSE b/node_modules/mongodb-core/LICENSE deleted file mode 100644 index ad410e11302107da9aa47ce3d46bd5ad011c4c43..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ -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/mongodb-core/README.md b/node_modules/mongodb-core/README.md deleted file mode 100644 index d8b9edd4c6392dc8446ba39efc09fb2a821e84f8..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/README.md +++ /dev/null @@ -1,228 +0,0 @@ -[](http://travis-ci.org/mongodb-js/mongodb-core) -[](https://coveralls.io/github/mongodb-js/mongodb-core?branch=1.3) - -# 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/mongodb-js/mongodb-core | -| mongodb | http://www.mongodb.org/ | - -### Blogs of Engineers involved in the driver -- Christian Kvalheim [@christkv](https://twitter.com/christkv) <http://christiankvalheim.com> - -### 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 <https://jira.mongodb.org>. -- Navigate to the NODE project <https://jira.mongodb.org/browse/NODE>. -- 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 step is to get more in 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/mongodb-core/index.js b/node_modules/mongodb-core/index.js deleted file mode 100644 index a542d7962c48a4dee6ca522b37c6fd1718cfaea7..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/index.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -var BSON = require('bson'); -var require_optional = require('require_optional'); -const EJSON = require('./lib/utils').retrieveEJSON(); - -try { - // Attempt to grab the native BSON parser - var BSONNative = require_optional('bson-ext'); - // If we got the native parser, use it instead of the - // Javascript one - if (BSONNative) { - BSON = BSONNative; - } -} catch (err) {} // eslint-disable-line - -module.exports = { - // Errors - MongoError: require('./lib/error').MongoError, - MongoNetworkError: require('./lib/error').MongoNetworkError, - MongoParseError: require('./lib/error').MongoParseError, - MongoTimeoutError: require('./lib/error').MongoTimeoutError, - MongoWriteConcernError: require('./lib/error').MongoWriteConcernError, - mongoErrorContextSymbol: require('./lib/error').mongoErrorContextSymbol, - // Core - Connection: require('./lib/connection/connection'), - 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'), - Sessions: require('./lib/sessions'), - BSON: BSON, - EJSON: EJSON, - // Raw operations - Query: require('./lib/connection/commands').Query, - // Auth mechanisms - defaultAuthProviders: require('./lib/auth/defaultAuthProviders').defaultAuthProviders, - MongoCR: require('./lib/auth/mongocr'), - X509: require('./lib/auth/x509'), - Plain: require('./lib/auth/plain'), - GSSAPI: require('./lib/auth/gssapi'), - ScramSHA1: require('./lib/auth/scram').ScramSHA1, - ScramSHA256: require('./lib/auth/scram').ScramSHA256, - // Utilities - parseConnectionString: require('./lib/uri_parser') -}; diff --git a/node_modules/mongodb-core/lib/auth/defaultAuthProviders.js b/node_modules/mongodb-core/lib/auth/defaultAuthProviders.js deleted file mode 100644 index fc5f4c28364e4879664d6cba6141a2078ffce4a8..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/auth/defaultAuthProviders.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const MongoCR = require('./mongocr'); -const X509 = require('./x509'); -const Plain = require('./plain'); -const GSSAPI = require('./gssapi'); -const SSPI = require('./sspi'); -const ScramSHA1 = require('./scram').ScramSHA1; -const ScramSHA256 = require('./scram').ScramSHA256; - -/** - * Returns the default authentication providers. - * - * @param {BSON} bson Bson definition - * @returns {Object} a mapping of auth names to auth types - */ -function defaultAuthProviders(bson) { - return { - mongocr: new MongoCR(bson), - x509: new X509(bson), - plain: new Plain(bson), - gssapi: new GSSAPI(bson), - sspi: new SSPI(bson), - 'scram-sha-1': new ScramSHA1(bson), - 'scram-sha-256': new ScramSHA256(bson) - }; -} - -module.exports = { defaultAuthProviders }; diff --git a/node_modules/mongodb-core/lib/auth/gssapi.js b/node_modules/mongodb-core/lib/auth/gssapi.js deleted file mode 100644 index cfaab74e211fc91d371b09dc8b160cb7b4153d86..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/auth/gssapi.js +++ /dev/null @@ -1,381 +0,0 @@ -'use strict'; - -const f = require('util').format; -const Query = require('../connection/commands').Query; -const MongoError = require('../error').MongoError; -const retrieveKerberos = require('../utils').retrieveKerberos; - -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 - ); -}; - -/** - * Creates a new GSSAPI authentication mechanism - * @class - * @return {GSSAPI} A cursor instance - */ -var GSSAPI = function(bson) { - this.bson = bson; - this.authStore = []; -}; - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @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, connections, db, username, password, options, callback) { - var self = this; - let kerberos; - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e, null); - } - - // TODO: remove this once we fix URI parsing - var gssapiServiceName = options['gssapiservicename'] || options['gssapiServiceName'] || 'mongodb'; - // Total connections - var count = connections.length; - if (count === 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - 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( - self, - kerberos.processes.MongoAuthProcess, - db, - username, - password, - db, - gssapiServiceName, - server, - connection, - options, - 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 { - 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); - } - } - ); - }; - - var _execute = function(_connection) { - process.nextTick(function() { - execute(_connection); - }); - }; - - _execute(connections.shift()); - } -}; - -// -// Initialize step -var GSSAPIInitialize = function( - self, - MongoAuthProcess, - db, - username, - password, - authdb, - gssapiServiceName, - server, - connection, - options, - callback -) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess( - connection.host, - connection.port, - gssapiServiceName, - options - ); - - // Perform initialization - mongo_auth_process.init(username, password, function(err) { - 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( - self, - mongo_auth_process, - payload, - db, - username, - password, - authdb, - server, - connection, - callback - ); - }); - }); -}; - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function( - self, - 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 - }; - - // Write the commmand on the connection - server( - connection, - new Query(self.bson, '$external.$cmd', command, { - numberToSkip: 0, - numberToReturn: 1 - }), - 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( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - server, - connection, - callback - ); - }); - } - ); -}; - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function( - self, - 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 - // Write the commmand on the connection - server( - connection, - new Query(self.bson, '$external.$cmd', command, { - numberToSkip: 0, - numberToReturn: 1 - }), - 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( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - server, - connection, - callback - ); - }); - } - ); -}; - -var MongoDBGSSAPIThirdStep = function( - self, - 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( - connection, - new Query(self.bson, '$external.$cmd', command, { - numberToSkip: 0, - numberToReturn: 1 - }), - function(err, r) { - if (err) return callback(err, false); - mongo_auth_process.transition(null, function(err) { - 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); -}; - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -GSSAPI.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db !== dbName; - }); -}; - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -GSSAPI.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - if (count === 0) return callback(null, null); - // Iterate over all the auth details stored - for (var i = 0; i < authStore.length; i++) { - this.auth( - server, - connections, - authStore[i].db, - authStore[i].username, - authStore[i].password, - authStore[i].options, - function(err) { - count = count - 1; - // Done re-authenticating - if (count === 0) { - callback(err, 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; diff --git a/node_modules/mongodb-core/lib/auth/mongocr.js b/node_modules/mongodb-core/lib/auth/mongocr.js deleted file mode 100644 index 3f6a36cc7244cd2c8c69109203cf6e2d8bcfab0b..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/auth/mongocr.js +++ /dev/null @@ -1,214 +0,0 @@ -'use strict'; - -var f = require('util').format, - crypto = require('crypto'), - Query = require('../connection/commands').Query, - MongoError = require('../error').MongoError; - -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(bson) { - this.bson = bson; - 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 {[]Connections} connections Connections to authenticate using this authenticator - * @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, connections, db, username, password, callback) { - var self = this; - // Total connections - var count = connections.length; - if (count === 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var errorObject = null; - - // For each connection we need to authenticate - while (connections.length > 0) { - // Execute MongoCR - var executeMongoCR = function(connection) { - // Write the commmand on the connection - server( - connection, - new Query( - self.bson, - f('%s.$cmd', db), - { - getnonce: 1 - }, - { - numberToSkip: 0, - numberToReturn: 1 - } - ), - 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, 'utf8'); - var hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password, 'utf8'); - key = md5.digest('hex'); - } - - // Execute command - // Write the commmand on the connection - server( - connection, - new Query( - self.bson, - f('%s.$cmd', db), - { - authenticate: 1, - user: username, - nonce: nonce, - key: key - }, - { - numberToSkip: 0, - numberToReturn: 1 - } - ), - 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 { - 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); - } - } - ); - } - ); - }; - - var _execute = function(_connection) { - process.nextTick(function() { - executeMongoCR(_connection); - }); - }; - - _execute(connections.shift()); - } -}; - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -MongoCR.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db !== dbName; - }); -}; - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -MongoCR.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - if (count === 0) return callback(null, null); - // Iterate over all the auth details stored - for (var i = 0; i < authStore.length; i++) { - this.auth( - server, - connections, - authStore[i].db, - authStore[i].username, - authStore[i].password, - function(err) { - count = count - 1; - // Done re-authenticating - if (count === 0) { - callback(err, 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; diff --git a/node_modules/mongodb-core/lib/auth/plain.js b/node_modules/mongodb-core/lib/auth/plain.js deleted file mode 100644 index deaea5913f3fd2c7fe9e7ccdc85364c3a6dff41b..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/auth/plain.js +++ /dev/null @@ -1,183 +0,0 @@ -'use strict'; - -var f = require('util').format, - retrieveBSON = require('../connection/utils').retrieveBSON, - Query = require('../connection/commands').Query, - MongoError = require('../error').MongoError; - -var BSON = retrieveBSON(), - Binary = BSON.Binary; - -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(bson) { - this.bson = bson; - this.authStore = []; -}; - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @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, connections, db, username, password, callback) { - var self = this; - // Total connections - var count = connections.length; - if (count === 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - 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( - connection, - new Query(self.bson, '$external.$cmd', command, { - numberToSkip: 0, - numberToReturn: 1 - }), - 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 { - 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); - } - } - ); - }; - - var _execute = function(_connection) { - process.nextTick(function() { - execute(_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); -}; - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -Plain.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db !== dbName; - }); -}; - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -Plain.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - if (count === 0) return callback(null, null); - // Iterate over all the auth details stored - for (var i = 0; i < authStore.length; i++) { - this.auth( - server, - connections, - authStore[i].db, - authStore[i].username, - authStore[i].password, - function(err) { - count = count - 1; - // Done re-authenticating - if (count === 0) { - callback(err, 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; diff --git a/node_modules/mongodb-core/lib/auth/scram.js b/node_modules/mongodb-core/lib/auth/scram.js deleted file mode 100644 index 719c580b6c7716cf03d7e8bd3a4a4f6afcdce0b8..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/auth/scram.js +++ /dev/null @@ -1,442 +0,0 @@ -'use strict'; - -var f = require('util').format, - crypto = require('crypto'), - retrieveBSON = require('../connection/utils').retrieveBSON, - Query = require('../connection/commands').Query, - MongoError = require('../error').MongoError, - Buffer = require('safe-buffer').Buffer; - -let saslprep; - -try { - saslprep = require('saslprep'); -} catch (e) { - // don't do anything; -} - -var BSON = retrieveBSON(), - Binary = BSON.Binary; - -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 - ); -}; - -var id = 0; - -/** - * Creates a new ScramSHA authentication mechanism - * @class - * @return {ScramSHA} A cursor instance - */ -var ScramSHA = function(bson, cryptoMethod) { - this.bson = bson; - this.authStore = []; - this.id = id++; - this.cryptoMethod = cryptoMethod || 'sha1'; -}; - -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, 'utf8'); - return md5.digest('hex'); -}; - -// XOR two buffers -function xor(a, b) { - if (!Buffer.isBuffer(a)) a = Buffer.from(a); - if (!Buffer.isBuffer(b)) b = Buffer.from(b); - const length = Math.max(a.length, b.length); - const res = []; - - for (let i = 0; i < length; i += 1) { - res.push(a[i] ^ b[i]); - } - - return Buffer.from(res).toString('base64'); -} - -function H(method, text) { - return crypto - .createHash(method) - .update(text) - .digest(); -} - -function HMAC(method, key, text) { - return crypto - .createHmac(method, key) - .update(text) - .digest(); -} - -var _hiCache = {}; -var _hiCacheCount = 0; -var _hiCachePurge = function() { - _hiCache = {}; - _hiCacheCount = 0; -}; - -const hiLengthMap = { - sha256: 32, - sha1: 20 -}; - -function HI(data, salt, iterations, cryptoMethod) { - // omit the work if already generated - const key = [data, salt.toString('base64'), iterations].join('_'); - if (_hiCache[key] !== undefined) { - return _hiCache[key]; - } - - // generate the salt - const saltedData = crypto.pbkdf2Sync( - data, - salt, - iterations, - hiLengthMap[cryptoMethod], - cryptoMethod - ); - - // cache a copy to speed up the next lookup, but prevent unbounded cache growth - if (_hiCacheCount >= 200) { - _hiCachePurge(); - } - - _hiCache[key] = saltedData; - _hiCacheCount += 1; - return saltedData; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @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} - */ -ScramSHA.prototype.auth = function(server, connections, db, username, password, callback) { - var self = this; - // Total connections - var count = connections.length; - if (count === 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var errorObject = null; - - const cryptoMethod = this.cryptoMethod; - let mechanism = 'SCRAM-SHA-1'; - let processedPassword; - - if (cryptoMethod === 'sha256') { - mechanism = 'SCRAM-SHA-256'; - - let saslprepFn = (server.s && server.s.saslprep) || saslprep; - - if (saslprepFn) { - processedPassword = saslprepFn(password); - } else { - console.warn('Warning: no saslprep library specified. Passwords will not be sanitized'); - processedPassword = password; - } - } else { - processedPassword = passwordDigest(username, password); - } - - // 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' - - // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. - // Since the username is not sasl-prep-d, we need to do this here. - const firstBare = Buffer.concat([ - Buffer.from('n=', 'utf8'), - Buffer.from(username, 'utf8'), - Buffer.from(',r=', 'utf8'), - Buffer.from(nonce, 'utf8') - ]); - - // Build command structure - var cmd = { - saslStart: 1, - mechanism: mechanism, - payload: new Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), firstBare])), - autoAuthorize: 1 - }; - - // Handle the error - var handleError = function(err, r) { - if (err) { - numberOfValidConnections = numberOfValidConnections - 1; - 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 { - 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); - }; - - // Write the commmand on the connection - server( - connection, - new Query(self.bson, f('%s.$cmd', db), cmd, { - numberToSkip: 0, - numberToReturn: 1 - }), - 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 saltedPassword = HI( - processedPassword, - Buffer.from(salt, 'base64'), - iterations, - cryptoMethod - ); - - if (iterations && iterations < 4096) { - const error = new MongoError(`Server returned an invalid iteration count ${iterations}`); - return callback(error, false); - } - - // Create the client key - const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); - - // Create the stored key - const storedKey = H(cryptoMethod, clientKey); - - // Create the authentication message - const authMessage = [ - firstBare, - r.result.payload.value().toString('base64'), - withoutProof - ].join(','); - - // Create client signature - const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); - - // Create client proof - const clientProof = f('p=%s', xor(clientKey, clientSignature)); - - // Create client final - const clientFinal = [withoutProof, clientProof].join(','); - - // Create continue message - const cmd = { - saslContinue: 1, - conversationId: r.result.conversationId, - payload: new Binary(Buffer.from(clientFinal)) - }; - - // - // Execute sasl continue - // Write the commmand on the connection - server( - connection, - new Query(self.bson, f('%s.$cmd', db), cmd, { - numberToSkip: 0, - numberToReturn: 1 - }), - function(err, r) { - if (r && r.result.done === false) { - var cmd = { - saslContinue: 1, - conversationId: r.result.conversationId, - payload: Buffer.alloc(0) - }; - - // Write the commmand on the connection - server( - connection, - new Query(self.bson, f('%s.$cmd', db), cmd, { - numberToSkip: 0, - numberToReturn: 1 - }), - function(err, r) { - handleEnd(err, r); - } - ); - } else { - handleEnd(err, r); - } - } - ); - } - ); - }; - - var _execute = function(_connection) { - process.nextTick(function() { - executeScram(_connection); - }); - }; - - // For each connection we need to authenticate - while (connections.length > 0) { - _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); -}; - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -ScramSHA.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db !== dbName; - }); -}; - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -ScramSHA.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - // No connections - if (count === 0) return callback(null, null); - // Iterate over all the auth details stored - for (var i = 0; i < authStore.length; i++) { - this.auth( - server, - connections, - authStore[i].db, - authStore[i].username, - authStore[i].password, - function(err) { - count = count - 1; - // Done re-authenticating - if (count === 0) { - callback(err, null); - } - } - ); - } -}; - -class ScramSHA1 extends ScramSHA { - constructor(bson) { - super(bson, 'sha1'); - } -} - -class ScramSHA256 extends ScramSHA { - constructor(bson) { - super(bson, 'sha256'); - } -} - -module.exports = { ScramSHA1, ScramSHA256 }; diff --git a/node_modules/mongodb-core/lib/auth/sspi.js b/node_modules/mongodb-core/lib/auth/sspi.js deleted file mode 100644 index 61ff48de019dc8e1a891ae033d13289e2b685c27..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/auth/sspi.js +++ /dev/null @@ -1,262 +0,0 @@ -'use strict'; - -const f = require('util').format; -const Query = require('../connection/commands').Query; -const MongoError = require('../error').MongoError; -const retrieveKerberos = require('../utils').retrieveKerberos; - -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 - ); -}; - -/** - * Creates a new SSPI authentication mechanism - * @class - * @return {SSPI} A cursor instance - */ -var SSPI = function(bson) { - this.bson = bson; - this.authStore = []; -}; - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @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, connections, db, username, password, options, callback) { - var self = this; - let kerberos; - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e, null); - } - - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - // Total connections - var count = connections.length; - if (count === 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - 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( - self, - kerberos.processes.MongoAuthProcess, - username, - password, - gssapiServiceName, - server, - connection, - options, - 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 { - 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); - } - } - ); - }; - - var _execute = function(_connection) { - process.nextTick(function() { - execute(_connection); - }); - }; - - _execute(connections.shift()); - } -}; - -function SSIPAuthenticate( - self, - MongoAuthProcess, - username, - password, - gssapiServiceName, - server, - connection, - options, - callback -) { - const authProcess = new MongoAuthProcess( - connection.host, - connection.port, - gssapiServiceName, - options - ); - - function authCommand(command, authCb) { - const query = new Query(self.bson, '$external.$cmd', command, { - numberToSkip: 0, - numberToReturn: 1 - }); - - server(connection, query, authCb); - } - - authProcess.init(username, password, err => { - if (err) return callback(err, false); - - authProcess.transition('', (err, payload) => { - if (err) return callback(err, false); - - const command = { - saslStart: 1, - mechanism: 'GSSAPI', - payload, - autoAuthorize: 1 - }; - - authCommand(command, (err, result) => { - if (err) return callback(err, false); - const doc = result.result; - - authProcess.transition(doc.payload, (err, payload) => { - if (err) return callback(err, false); - const command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload - }; - - authCommand(command, (err, result) => { - if (err) return callback(err, false); - const doc = result.result; - - authProcess.transition(doc.payload, (err, payload) => { - if (err) return callback(err, false); - const command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload - }; - - authCommand(command, (err, response) => { - if (err) return callback(err, false); - - authProcess.transition(null, err => { - if (err) return callback(err, null); - callback(null, response); - }); - }); - }); - }); - }); - }); - }); - }); -} - -// 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); -}; - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -SSPI.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db !== dbName; - }); -}; - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -SSPI.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - if (count === 0) return callback(null, null); - // Iterate over all the auth details stored - for (var i = 0; i < authStore.length; i++) { - this.auth( - server, - connections, - authStore[i].db, - authStore[i].username, - authStore[i].password, - authStore[i].options, - function(err) { - count = count - 1; - // Done re-authenticating - if (count === 0) { - callback(err, 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; diff --git a/node_modules/mongodb-core/lib/auth/x509.js b/node_modules/mongodb-core/lib/auth/x509.js deleted file mode 100644 index e7c4bd86c86fe8345c19ae75f7ac6610576651d7..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/auth/x509.js +++ /dev/null @@ -1,179 +0,0 @@ -'use strict'; - -var f = require('util').format, - Query = require('../connection/commands').Query, - MongoError = require('../error').MongoError; - -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(bson) { - this.bson = bson; - this.authStore = []; -}; - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @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, connections, db, username, password, callback) { - var self = this; - // Total connections - var count = connections.length; - if (count === 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - 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' - }; - - // Add username if specified - if (username) { - command.user = username; - } - - // Let's start the process - server( - connection, - new Query(self.bson, '$external.$cmd', command, { - numberToSkip: 0, - numberToReturn: 1 - }), - 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 { - 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); - } - } - ); - }; - - var _execute = function(_connection) { - process.nextTick(function() { - execute(_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); -}; - -/** - * Remove authStore credentials - * @method - * @param {string} db Name of database we are removing authStore details about - * @return {object} - */ -X509.prototype.logout = function(dbName) { - this.authStore = this.authStore.filter(function(x) { - return x.db !== dbName; - }); -}; - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {[]Connections} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -X509.prototype.reauthenticate = function(server, connections, callback) { - var authStore = this.authStore.slice(0); - var count = authStore.length; - if (count === 0) return callback(null, null); - // Iterate over all the auth details stored - for (var i = 0; i < authStore.length; i++) { - this.auth( - server, - connections, - authStore[i].db, - authStore[i].username, - authStore[i].password, - function(err) { - count = count - 1; - // Done re-authenticating - if (count === 0) { - callback(err, 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; diff --git a/node_modules/mongodb-core/lib/connection/apm.js b/node_modules/mongodb-core/lib/connection/apm.js deleted file mode 100644 index 8cf19036faa5b551947d1db8b1a8bb03f71c6f63..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/connection/apm.js +++ /dev/null @@ -1,228 +0,0 @@ -'use strict'; -const KillCursor = require('../connection/commands').KillCursor; -const GetMore = require('../connection/commands').GetMore; -const calculateDurationInMs = require('../utils').calculateDurationInMs; - -/** Commands that we want to redact because of the sensitive nature of their contents */ -const SENSITIVE_COMMANDS = new Set([ - 'authenticate', - 'saslStart', - 'saslContinue', - 'getnonce', - 'createUser', - 'updateUser', - 'copydbgetnonce', - 'copydbsaslstart', - 'copydb' -]); - -// helper methods -const extractCommandName = command => Object.keys(command)[0]; -const namespace = command => command.ns; -const databaseName = command => command.ns.split('.')[0]; -const collectionName = command => command.ns.split('.')[1]; -const generateConnectionId = pool => `${pool.options.host}:${pool.options.port}`; -const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result); - -const LEGACY_FIND_QUERY_MAP = { - $query: 'filter', - $orderby: 'sort', - $hint: 'hint', - $comment: 'comment', - $maxScan: 'maxScan', - $max: 'max', - $min: 'min', - $returnKey: 'returnKey', - $showDiskLoc: 'showRecordId', - $maxTimeMS: 'maxTimeMS', - $snapshot: 'snapshot' -}; - -const LEGACY_FIND_OPTIONS_MAP = { - numberToSkip: 'skip', - numberToReturn: 'batchSize', - returnFieldsSelector: 'projection' -}; - -const OP_QUERY_KEYS = [ - 'tailable', - 'oplogReplay', - 'noCursorTimeout', - 'awaitData', - 'partial', - 'exhaust' -]; - -/** - * Extract the actual command from the query, possibly upconverting if it's a legacy - * format - * - * @param {Object} command the command - */ -const extractCommand = command => { - if (command instanceof GetMore) { - return { - getMore: command.cursorId, - collection: collectionName(command), - batchSize: command.numberToReturn - }; - } - - if (command instanceof KillCursor) { - return { - killCursors: collectionName(command), - cursors: command.cursorIds - }; - } - - if (command.query && command.query.$query) { - let result; - if (command.ns === 'admin.$cmd') { - // upconvert legacy command - result = Object.assign({}, command.query.$query); - } else { - // upconvert legacy find command - result = { find: collectionName(command) }; - Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { - if (typeof command.query[key] !== 'undefined') - result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key]; - }); - } - - Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { - if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key]; - }); - - OP_QUERY_KEYS.forEach(key => { - if (command[key]) result[key] = command[key]; - }); - - if (typeof command.pre32Limit !== 'undefined') { - result.limit = command.pre32Limit; - } - - if (command.query.$explain) { - return { explain: result }; - } - - return result; - } - - return command.query ? command.query : command; -}; - -const extractReply = (command, reply) => { - if (command instanceof GetMore) { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - nextBatch: reply.message.documents - } - }; - } - - if (command instanceof KillCursor) { - return { - ok: 1, - cursorsUnknown: command.cursorIds - }; - } - - // is this a legacy find command? - if (command.query && typeof command.query.$query !== 'undefined') { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - firstBatch: reply.message.documents - } - }; - } - - return reply.result; -}; - -/** An event indicating the start of a given command */ -class CommandStartedEvent { - /** - * Create a started event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - */ - constructor(pool, command) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - - // NOTE: remove in major revision, this is not spec behavior - if (SENSITIVE_COMMANDS.has(commandName)) { - this.commandObj = {}; - this.commandObj[commandName] = true; - } - - Object.assign(this, { - command: cmd, - databaseName: databaseName(command), - commandName, - requestId: command.requestId, - connectionId: generateConnectionId(pool) - }); - } -} - -/** An event indicating the success of a given command */ -class CommandSucceededEvent { - /** - * Create a succeeded event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {Object} reply the reply for this command from the server - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, reply, started) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - - Object.assign(this, { - duration: calculateDurationInMs(started), - commandName, - reply: maybeRedact(commandName, extractReply(command, reply)), - requestId: command.requestId, - connectionId: generateConnectionId(pool) - }); - } -} - -/** An event indicating the failure of a given command */ -class CommandFailedEvent { - /** - * Create a failure event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {MongoError|Object} error the generated error or a server error response - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, error, started) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - - Object.assign(this, { - duration: calculateDurationInMs(started), - commandName, - failure: maybeRedact(commandName, error), - requestId: command.requestId, - connectionId: generateConnectionId(pool) - }); - } -} - -module.exports = { - CommandStartedEvent, - CommandSucceededEvent, - CommandFailedEvent -}; diff --git a/node_modules/mongodb-core/lib/connection/command_result.js b/node_modules/mongodb-core/lib/connection/command_result.js deleted file mode 100644 index be4eb52ddd0985e0a5f33706715c1a5403b67db0..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/connection/command_result.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -/** - * 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, message) { - this.result = result; - this.connection = connection; - this.message = message; -}; - -/** - * 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; diff --git a/node_modules/mongodb-core/lib/connection/commands.js b/node_modules/mongodb-core/lib/connection/commands.js deleted file mode 100644 index 0547a752ad2e28243bd63d0716d86c037c6b257e..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/connection/commands.js +++ /dev/null @@ -1,546 +0,0 @@ -'use strict'; - -var retrieveBSON = require('./utils').retrieveBSON; -var BSON = retrieveBSON(); -var Long = BSON.Long; -const MongoError = require('../error').MongoError; -const Buffer = require('safe-buffer').Buffer; - -// Incrementing request id -var _requestId = 0; - -// Wire command operation ids -var opcodes = require('../wireprotocol/shared').opcodes; - -// Query flags -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 = 1; -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 collection name - if (ns.indexOf('\x00') !== -1) { - throw new Error('namespace cannot contain a null character'); - } - - // Basic options - this.bson = bson; - this.ns = ns; - this.query = query; - - // Additional options - this.numberToSkip = options.numberToSkip || 0; - this.numberToReturn = options.numberToReturn || 0; - this.returnFieldSelector = options.returnFieldSelector || null; - this.requestId = Query.getRequestId(); - - // special case for pre-3.2 find commands, delete ASAP - this.pre32Limit = options.pre32Limit; - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : 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 = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; - this.oplogReplay = 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++; -}; - -// -// Assign a new request Id -Query.nextRequestId = function() { - return _requestId + 1; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -Query.prototype.toBin = function() { - var self = this; - var buffers = []; - var projection = null; - - // Set up the flags - var flags = 0; - if (this.tailable) { - flags |= OPTS_TAILABLE_CURSOR; - } - - if (this.slaveOk) { - flags |= OPTS_SLAVE; - } - - if (this.oplogReplay) { - 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; - - // Allocate write protocol header buffer - var header = Buffer.alloc( - 4 * 4 + // Header - 4 + // Flags - Buffer.byteLength(self.ns) + - 1 + // namespace - 4 + // numberToSkip - 4 // numberToReturn - ); - - // Add header to buffers - buffers.push(header); - - // Serialize the query - var query = self.bson.serialize(this.query, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - - // Add query document - buffers.push(query); - - if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { - // Serialize the projection document - projection = self.bson.serialize(this.returnFieldSelector, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - // Add projection document - buffers.push(projection); - } - - // Total message size - var totalLength = header.length + query.length + (projection ? projection.length : 0); - - // Set up the index - var index = 4; - - // Write total document length - header[3] = (totalLength >> 24) & 0xff; - header[2] = (totalLength >> 16) & 0xff; - header[1] = (totalLength >> 8) & 0xff; - header[0] = totalLength & 0xff; - - // Write header information requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = this.requestId & 0xff; - index = index + 4; - - // Write header information responseTo - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = 0 & 0xff; - index = index + 4; - - // Write header information OP_QUERY - header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; - header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; - header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; - header[index] = opcodes.OP_QUERY & 0xff; - index = index + 4; - - // Write header information flags - header[index + 3] = (flags >> 24) & 0xff; - header[index + 2] = (flags >> 16) & 0xff; - header[index + 1] = (flags >> 8) & 0xff; - header[index] = flags & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write header information flags numberToSkip - header[index + 3] = (this.numberToSkip >> 24) & 0xff; - header[index + 2] = (this.numberToSkip >> 16) & 0xff; - header[index + 1] = (this.numberToSkip >> 8) & 0xff; - header[index] = this.numberToSkip & 0xff; - index = index + 4; - - // Write header information flags numberToReturn - header[index + 3] = (this.numberToReturn >> 24) & 0xff; - header[index + 2] = (this.numberToReturn >> 16) & 0xff; - header[index + 1] = (this.numberToReturn >> 8) & 0xff; - header[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -}; - -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 = Buffer.alloc(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] = (opcodes.OP_GETMORE >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; - _buffer[index] = opcodes.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, ns, cursorIds) { - this.ns = ns; - 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 = Buffer.alloc(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] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; - _buffer[index] = opcodes.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, message, msgHeader, msgBody, opts) { - opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read the message body - this.responseFlags = msgBody.readInt32LE(0); - this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); - this.startingFrom = msgBody.readInt32LE(12); - this.numberReturned = msgBody.readInt32LE(16); - - // 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; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; -}; - -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; - var documentsReturnedIn = options.documentsReturnedIn || null; - var promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - var promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - var promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; - var bsonSize, _options; - - // Set up the options - _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers - }; - - // Position within OP_REPLY at which documents start - // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) - this.index = 20; - - // - // Single document and documentsReturnedIn set - // - if (this.numberReturned === 1 && documentsReturnedIn != null && raw) { - // Calculate the bson size - bsonSize = - this.data[this.index] | - (this.data[this.index + 1] << 8) | - (this.data[this.index + 2] << 16) | - (this.data[this.index + 3] << 24); - // Slice out the buffer containing the command result document - var document = this.data.slice(this.index, this.index + bsonSize); - // Set up field we wish to keep as raw - var fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - // Deserialize but keep the array of documents in non-parsed form - var doc = this.bson.deserialize(document, _options); - - if (doc instanceof Error) { - throw doc; - } - - if (doc.errmsg) { - throw new MongoError(doc.errmsg); - } - - if (!doc.cursor) { - throw new MongoError('Cursor not found'); - } - - // Get the documents - this.documents = doc.cursor[documentsReturnedIn]; - this.numberReturned = this.documents.length; - // Ensure we have a Long valie cursor id - this.cursorId = - typeof doc.cursor.id === 'number' ? Long.fromNumber(doc.cursor.id) : doc.cursor.id; - - // Adjust the index - this.index = this.index + bsonSize; - - // Set as parsed - this.parsed = true; - return; - } - - // - // Parse Body - // - for (var i = 0; i < this.numberReturned; i++) { - bsonSize = - this.data[this.index] | - (this.data[this.index + 1] << 8) | - (this.data[this.index + 2] << 16) | - (this.data[this.index + 3] << 24); - - // 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 -}; diff --git a/node_modules/mongodb-core/lib/connection/connection.js b/node_modules/mongodb-core/lib/connection/connection.js deleted file mode 100644 index 71d461a2b4f8c164766836296abe0e4a18442bc1..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/connection/connection.js +++ /dev/null @@ -1,805 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - EventEmitter = require('events').EventEmitter, - net = require('net'), - tls = require('tls'), - crypto = require('crypto'), - f = require('util').format, - debugOptions = require('./utils').debugOptions, - parseHeader = require('../wireprotocol/shared').parseHeader, - decompress = require('../wireprotocol/compression').decompress, - Response = require('./commands').Response, - MongoNetworkError = require('../error').MongoNetworkError, - Logger = require('./logger'), - OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED, - MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE, - Buffer = require('safe-buffer').Buffer; - -var _id = 0; -var debugFields = [ - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'socketTimeout', - 'singleBufferSerializtion', - 'ssl', - 'ca', - 'crl', - 'cert', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'checkServerIdentity' -]; - -var connectionAccountingSpy = undefined; -var connectionAccounting = false; -var connections = {}; - -/** - * Creates a new Connection instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.family=null] IP version for DNS lookup, passed down to Node's [`dns.lookup()` function](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback). If set to `6`, will only look for ipv6 addresses. - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] 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 {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation 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 {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @fires Connection#connect - * @fires Connection#close - * @fires Connection#error - * @fires Connection#timeout - * @fires Connection#parseError - * @return {Connection} A cursor instance - */ -var Connection = function(messageHandler, 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 = 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.family = typeof options.family === 'number' ? options.family : void 0; - this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - this.keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; - this.noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; - this.connectionTimeout = - typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; - this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - - // Is the keepAliveInitialDelay > socketTimeout set it to half of socketTimeout - if (this.keepAliveInitialDelay > this.socketTimeout) { - this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); - } - - // If connection was destroyed - this.destroyed = false; - - // 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.crl = options.crl || null; - this.cert = options.cert || null; - this.key = options.key || null; - this.passphrase = options.passphrase || null; - this.ciphers = options.ciphers || null; - this.ecdhCurve = options.ecdhCurve || null; - this.ssl = typeof options.ssl === 'boolean' ? options.ssl : false; - this.rejectUnauthorized = - typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; - this.checkServerIdentity = - typeof options.checkServerIdentity === 'boolean' || - typeof options.checkServerIdentity === 'function' - ? options.checkServerIdentity - : true; - - // If ssl not enabled - if (!this.ssl) this.rejectUnauthorized = false; - - // Response options - this.responseOptions = { - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false - }; - - // Flushing - this.flushing = false; - this.queue = []; - - // Internal state - this.connection = null; - this.writeStream = null; - - // Create hash method - var hash = crypto.createHash('sha1'); - hash.update(f('%s:%s', this.host, this.port)); - - // Create a hash name - this.hashedName = hash.digest('hex'); - - // All operations in flight on the connection - this.workItems = []; -}; - -inherits(Connection, EventEmitter); - -Connection.prototype.setSocketTimeout = function(value) { - if (this.connection) { - this.connection.setTimeout(value); - } -}; - -Connection.prototype.resetSocketTimeout = function() { - if (this.connection) { - this.connection.setTimeout(this.socketTimeout); - } -}; - -Connection.enableConnectionAccounting = function(spy) { - if (spy) { - connectionAccountingSpy = spy; - } - - connectionAccounting = true; - connections = {}; -}; - -Connection.disableConnectionAccounting = function() { - connectionAccounting = false; - connectionAccountingSpy = undefined; -}; - -Connection.connections = function() { - return connections; -}; - -function deleteConnection(id) { - // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) - delete connections[id]; - - if (connectionAccountingSpy) { - connectionAccountingSpy.deleteConnection(id); - } -} - -function addConnection(id, connection) { - // console.log("=== added connection " + id + " :: " + connection.port) - connections[id] = connection; - - if (connectionAccountingSpy) { - connectionAccountingSpy.addConnection(id, connection); - } -} - -// -// Connection handlers -var errorHandler = function(self) { - return function(err) { - if (connectionAccounting) deleteConnection(self.id); - // 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', new MongoNetworkError(err), self); - }; -}; - -var timeoutHandler = function(self) { - return function() { - if (connectionAccounting) deleteConnection(self.id); - // 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', - new MongoNetworkError(f('connection %s to %s:%s timed out', self.id, self.host, self.port)), - self - ); - }; -}; - -var closeHandler = function(self) { - return function(hadError) { - if (connectionAccounting) deleteConnection(self.id); - // 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', - new MongoNetworkError(f('connection %s to %s:%s closed', self.id, self.host, self.port)), - self - ); - } - }; -}; - -// Handle a message once it is received -var emitMessageHandler = function(self, message) { - var msgHeader = parseHeader(message); - if (msgHeader.opCode === OP_COMPRESSED) { - msgHeader.fromCompressed = true; - var index = MESSAGE_HEADER_SIZE; - msgHeader.opCode = message.readInt32LE(index); - index += 4; - msgHeader.length = message.readInt32LE(index); - index += 4; - var compressorID = message[index]; - index++; - decompress(compressorID, message.slice(index), function(err, decompressedMsgBody) { - if (err) { - throw err; - } - if (decompressedMsgBody.length !== msgHeader.length) { - throw new Error( - 'Decompressing a compressed message from the server failed. The message is corrupt.' - ); - } - self.messageHandler( - new Response(self.bson, message, msgHeader, decompressedMsgBody, self.responseOptions), - self - ); - }); - } else { - self.messageHandler( - new Response( - self.bson, - message, - msgHeader, - message.slice(MESSAGE_HEADER_SIZE), - self.responseOptions - ), - 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 = Buffer.alloc(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; - - emitMessageHandler(self, emitBuffer); - } 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 = Buffer.alloc(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 = Buffer.alloc(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 = Buffer.alloc(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) { - 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 = Buffer.alloc(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 = Buffer.alloc(0); - } else if ( - sizeOfMessage > 4 && - sizeOfMessage < self.maxBsonMessageSize && - sizeOfMessage === data.length - ) { - try { - emitBuffer = data; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - // Emit the message - emitMessageHandler(self, emitBuffer); - } catch (err) { - self.emit('parseError', err, self); - } - } else if (sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { - 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 = Buffer.alloc(0); - } else { - 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 - emitMessageHandler(self, emitBuffer); - } - } else { - // Create a buffer that contains the space for the non-complete message - self.stubBuffer = Buffer.alloc(data.length); - // Copy the data to the stub buffer - data.copy(self.stubBuffer, 0); - // Exit parsing loop - data = Buffer.alloc(0); - } - } - } - } - }; -}; - -// List of socket level valid ssl options -var legalSslSocketOptions = [ - 'pfx', - 'key', - 'passphrase', - 'cert', - 'ca', - 'ciphers', - 'NPNProtocols', - 'ALPNProtocols', - 'servername', - 'ecdhCurve', - 'secureProtocol', - 'secureContext', - 'session', - 'minDHSize' -]; - -function merge(options1, options2) { - // Merge in any allowed ssl options - for (var name in options2) { - if (options2[name] != null && legalSslSocketOptions.indexOf(name) !== -1) { - options1[name] = options2[name]; - } - } -} - -function makeSSLConnection(self, _options) { - let sslOptions = { - socket: self.connection, - rejectUnauthorized: self.rejectUnauthorized - }; - - // Merge in options - merge(sslOptions, self.options); - merge(sslOptions, _options); - - // Set options for ssl - if (self.ca) sslOptions.ca = self.ca; - if (self.crl) sslOptions.crl = self.crl; - if (self.cert) sslOptions.cert = self.cert; - if (self.key) sslOptions.key = self.key; - if (self.passphrase) sslOptions.passphrase = self.passphrase; - - // Override checkServerIdentity behavior - if (self.checkServerIdentity === false) { - // Skip the identiy check by retuning undefined as per node documents - // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback - sslOptions.checkServerIdentity = function() { - return undefined; - }; - } else if (typeof self.checkServerIdentity === 'function') { - sslOptions.checkServerIdentity = self.checkServerIdentity; - } - - // Set default sni servername to be the same as host - if (sslOptions.servername == null) { - sslOptions.servername = self.host; - } - - // Attempt SSL connection - const connection = tls.connect(self.port, self.host, sslOptions, function() { - // Error on auth or skip - if (connection.authorizationError && self.rejectUnauthorized) { - return self.emit('error', connection.authorizationError, self, { ssl: true }); - } - - // Set socket timeout instead of connection timeout - connection.setTimeout(self.socketTimeout); - // We are done emit connect - self.emit('connect', self); - }); - - // Set the options for the connection - connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); - connection.setTimeout(self.connectionTimeout); - connection.setNoDelay(self.noDelay); - - return connection; -} - -function makeUnsecureConnection(self, family) { - // Create new connection instance - let connection_options; - if (self.domainSocket) { - connection_options = { path: self.host }; - } else { - connection_options = { port: self.port, host: self.host }; - connection_options.family = family; - } - - const connection = net.createConnection(connection_options); - - // Set the options for the connection - connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); - connection.setTimeout(self.connectionTimeout); - connection.setNoDelay(self.noDelay); - - connection.once('connect', function() { - // Set socket timeout instead of connection timeout - connection.setTimeout(self.socketTimeout); - // Emit connect event - self.emit('connect', self); - }); - - return connection; -} - -function doConnect(self, family, _options, _errorHandler) { - self.connection = self.ssl - ? makeSSLConnection(self, _options) - : makeUnsecureConnection(self, family); - - // Add handlers for events - self.connection.once('error', _errorHandler); - self.connection.once('timeout', timeoutHandler(self)); - self.connection.once('close', closeHandler(self)); - self.connection.on('data', dataHandler(self)); -} - -/** - * Connect - * @method - */ -Connection.prototype.connect = function(_options) { - _options = _options || {}; - // Set the connections - if (connectionAccounting) addConnection(this.id, this); - // Check if we are overriding the promoteLongs - if (typeof _options.promoteLongs === 'boolean') { - this.responseOptions.promoteLongs = _options.promoteLongs; - this.responseOptions.promoteValues = _options.promoteValues; - this.responseOptions.promoteBuffers = _options.promoteBuffers; - } - - const _errorHandler = errorHandler(this); - - if (this.family !== void 0) { - return doConnect(this, this.family, _options, _errorHandler); - } - - return doConnect(this, 6, _options, err => { - if (this.logger.isDebug()) { - this.logger.debug( - f( - 'connection %s for [%s:%s] errored out with [%s]', - this.id, - this.host, - this.port, - JSON.stringify(err) - ) - ); - } - - // clean up existing event handlers - this.connection.removeAllListeners('error'); - this.connection.removeAllListeners('timeout'); - this.connection.removeAllListeners('close'); - this.connection.removeAllListeners('data'); - this.connection = undefined; - - return doConnect(this, 4, _options, _errorHandler); - }); -}; - -/** - * Unref this connection - * @method - * @return {boolean} - */ -Connection.prototype.unref = function() { - if (this.connection) this.connection.unref(); - else { - var self = this; - this.once('connect', function() { - self.connection.unref(); - }); - } -}; - -/** - * Destroy connection - * @method - */ -Connection.prototype.destroy = function() { - // Set the connections - if (connectionAccounting) deleteConnection(this.id); - if (this.connection) { - // Catch posssible exception thrown by node 0.10.x - try { - this.connection.end(); - } catch (err) {} // eslint-disable-line - // Destroy connection - this.connection.destroy(); - } - - this.destroyed = true; -}; - -/** - * Write to connection - * @method - * @param {Command} command Command to write out need to implement toBin and toBinUnified - */ -Connection.prototype.write = function(buffer) { - var i; - // Debug Log - if (this.logger.isDebug()) { - if (!Array.isArray(buffer)) { - this.logger.debug( - f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port) - ); - } else { - for (i = 0; i < buffer.length; i++) - this.logger.debug( - f('writing buffer [%s] to %s:%s', buffer[i].toString('hex'), this.host, this.port) - ); - } - } - - // Double check that the connection is not destroyed - if (this.connection.destroyed === false) { - // Write out the command - if (!Array.isArray(buffer)) { - this.connection.write(buffer, 'binary'); - return true; - } - - // Iterate over all buffers and write them in order to the socket - for (i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); - return true; - } - - // Connection is destroyed return write failed - return false; -}; - -/** - * 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() { - if (this.destroyed) return false; - 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/mongodb-core/lib/connection/logger.js b/node_modules/mongodb-core/lib/connection/logger.js deleted file mode 100644 index eb11e43d65b703b9c7396b8ea464c21af58bcb74..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/connection/logger.js +++ /dev/null @@ -1,246 +0,0 @@ -'use strict'; - -var f = require('util').format, - MongoError = require('../error').MongoError; - -// 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 - this.className = className; - - // Current logger - if (options.logger) { - currentLogger = options.logger; - } else if (currentLogger == null) { - currentLogger = console.log; - } - - // Set level of logging, default is error - if (options.loggerLevel) { - 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() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - 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 warn level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -(Logger.prototype.warn = function(message, object) { - if ( - this.isWarn() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); - var state = { - type: 'warn', - 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() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - 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() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - 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 error level - * @method - * @return {boolean} - */ - (Logger.prototype.isWarn = function() { - return level === 'error' || level === 'warn' || 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' && _level !== 'warn') { - throw new Error(f('%s is an illegal logging level', _level)); - } - - level = _level; -}; - -module.exports = Logger; diff --git a/node_modules/mongodb-core/lib/connection/pool.js b/node_modules/mongodb-core/lib/connection/pool.js deleted file mode 100644 index 02458be83152ccbf8726e357fb6da3746c5d4adc..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/connection/pool.js +++ /dev/null @@ -1,1657 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const EventEmitter = require('events').EventEmitter; -const Connection = require('./connection'); -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const MongoWriteConcernError = require('../error').MongoWriteConcernError; -const Logger = require('./logger'); -const f = require('util').format; -const Query = require('./commands').Query; -const CommandResult = require('./command_result'); -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const opcodes = require('../wireprotocol/shared').opcodes; -const compress = require('../wireprotocol/compression').compress; -const compressorIDs = require('../wireprotocol/compression').compressorIDs; -const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands; -const resolveClusterTime = require('../topologies/shared').resolveClusterTime; -const apm = require('./apm'); -const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; -const Buffer = require('safe-buffer').Buffer; - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYING = 'destroying'; -var DESTROYED = 'destroyed'; - -var _id = 0; - -function hasSessionSupport(topology) { - if (topology == null) return false; - return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; -} - -/** - * 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] Max server connection pool size - * @param {number} [options.minSize=0] Minimum server connection pool size - * @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.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation 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 - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @fires Pool#connect - * @fires Pool#close - * @fires Pool#error - * @fires Pool#timeout - * @fires Pool#parseError - * @return {Pool} A cursor instance - */ -var Pool = function(topology, options) { - // Add event listener - EventEmitter.call(this); - - // Store topology for later use - this.topology = topology; - - // Add the options - this.options = Object.assign( - { - // Host and port settings - host: 'localhost', - port: 27017, - // Pool default max size - size: 5, - // Pool default min size - minSize: 0, - // socket settings - connectionTimeout: 30000, - socketTimeout: 360000, - keepAlive: true, - keepAliveInitialDelay: 300000, - noDelay: true, - // SSL Settings - ssl: false, - checkServerIdentity: true, - ca: null, - crl: null, - cert: null, - key: null, - passPhrase: null, - rejectUnauthorized: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - // Reconnection options - reconnect: true, - reconnectInterval: 1000, - reconnectTries: 30, - // Enable domains - domainsEnabled: false - }, - options - ); - - // Identification information - this.id = _id++; - // Current reconnect retries - this.retriesLeft = this.options.reconnectTries; - this.reconnectId = null; - // No bson parser passed in - if ( - !options.bson || - (options.bson && - (typeof options.bson.serialize !== 'function' || - typeof options.bson.deserialize !== 'function')) - ) { - throw new Error('must pass in valid bson parser'); - } - - // Logger instance - this.logger = Logger('Pool', options); - // Pool state - this.state = DISCONNECTED; - // Connections - this.availableConnections = []; - this.inUseConnections = []; - this.connectingConnections = []; - // Currently executing - this.executing = false; - // Operation work queue - this.queue = []; - - // All the authProviders - this.authProviders = options.authProviders || defaultAuthProviders(options.bson); - - // Contains the reconnect connection - this.reconnectConnection = null; - - // Are we currently authenticating - this.authenticating = false; - this.loggingout = false; - this.nonAuthenticatedConnections = []; - this.authenticatingTimestamp = null; - // Number of consecutive timeouts caught - this.numberOfConsecutiveTimeouts = 0; - // Current pool Index - this.connectionIndex = 0; -}; - -inherits(Pool, EventEmitter); - -Object.defineProperty(Pool.prototype, 'size', { - enumerable: true, - get: function() { - return this.options.size; - } -}); - -Object.defineProperty(Pool.prototype, 'minSize', { - enumerable: true, - get: function() { - return this.options.minSize; - } -}); - -Object.defineProperty(Pool.prototype, 'connectionTimeout', { - enumerable: true, - get: function() { - return this.options.connectionTimeout; - } -}); - -Object.defineProperty(Pool.prototype, 'socketTimeout', { - enumerable: true, - get: function() { - return this.options.socketTimeout; - } -}); - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYING, DISCONNECTED], - connecting: [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYING], - destroying: [DESTROYING, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.emit('stateChanged', self.state, newState); - self.state = newState; - } else { - self.logger.error( - f( - 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -function authenticate(pool, auth, connection, cb) { - if (auth[0] === undefined) return cb(null); - // We need to authenticate the server - var mechanism = auth[0]; - var db = auth[1]; - // Validate if the mechanism exists - if (!pool.authProviders[mechanism]) { - throw new MongoError(f('authMechanism %s not supported', mechanism)); - } - - // Get the provider - var provider = pool.authProviders[mechanism]; - - // Authenticate using the provided mechanism - provider.auth.apply(provider, [write(pool), [connection], db].concat(auth.slice(2)).concat([cb])); -} - -// The write function used by the authentication mechanism (bypasses external) -function write(self) { - return function(connection, command, callback) { - // Get the raw buffer - // Ensure we stop auth if pool was destroyed - if (self.state === DESTROYED || self.state === DESTROYING) { - return callback(new MongoError('pool destroyed')); - } - - // Set the connection workItem callback - connection.workItems.push({ - cb: callback, - command: true, - requestId: command.requestId - }); - - // Write the buffer out to the connection - connection.write(command.toBin()); - }; -} - -function reauthenticate(pool, connection, cb) { - // Authenticate - function authenticateAgainstProvider(pool, connection, providers, cb) { - // Finished re-authenticating against providers - if (providers.length === 0) return cb(); - // Get the provider name - var provider = pool.authProviders[providers.pop()]; - - // Auth provider - provider.reauthenticate(write(pool), [connection], function(err) { - // We got an error return immediately - if (err) return cb(err); - // Continue authenticating the connection - authenticateAgainstProvider(pool, connection, providers, cb); - }); - } - - // Start re-authenticating process - authenticateAgainstProvider(pool, connection, Object.keys(pool.authProviders), cb); -} - -function connectionFailureHandler(self, event) { - return function(err) { - if (this._connectionFailHandled) return; - this._connectionFailHandled = true; - // Destroy the connection - this.destroy(); - - // Remove the connection - removeConnection(self, this); - - // Flush all work Items on this connection - while (this.workItems.length > 0) { - var workItem = this.workItems.shift(); - if (workItem.cb) workItem.cb(err); - } - - // Did we catch a timeout, increment the numberOfConsecutiveTimeouts - if (event === 'timeout') { - self.numberOfConsecutiveTimeouts = self.numberOfConsecutiveTimeouts + 1; - - // Have we timed out more than reconnectTries in a row ? - // Force close the pool as we are trying to connect to tcp sink hole - if (self.numberOfConsecutiveTimeouts > self.options.reconnectTries) { - self.numberOfConsecutiveTimeouts = 0; - // Destroy all connections and pool - self.destroy(true); - // Emit close event - return self.emit('close', self); - } - } - - // No more socket available propegate the event - if (self.socketCount() === 0) { - if (self.state !== DESTROYED && self.state !== DESTROYING) { - stateTransition(self, DISCONNECTED); - } - - // Do not emit error events, they are always close events - // do not trigger the low level error handler in node - event = event === 'error' ? 'close' : event; - self.emit(event, err); - } - - // Start reconnection attempts - if (!self.reconnectId && self.options.reconnect) { - self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); - } - - // Do we need to do anything to maintain the minimum pool size - const totalConnections = - self.availableConnections.length + - self.connectingConnections.length + - self.inUseConnections.length; - - if (totalConnections < self.minSize) { - _createConnection(self); - } - }; -} - -function attemptReconnect(self) { - return function() { - self.emit('attemptReconnect', self); - if (self.state === DESTROYED || self.state === DESTROYING) return; - - // We are connected do not try again - if (self.isConnected()) { - self.reconnectId = null; - return; - } - - // If we have failure schedule a retry - function _connectionFailureHandler(self) { - return function() { - if (this._connectionFailHandled) return; - this._connectionFailHandled = true; - // Destroy the connection - this.destroy(); - // Count down the number of reconnects - self.retriesLeft = self.retriesLeft - 1; - // How many retries are left - if (self.retriesLeft <= 0) { - // Destroy the instance - self.destroy(); - // Emit close event - self.emit( - 'reconnectFailed', - new MongoNetworkError( - f( - 'failed to reconnect after %s attempts with interval %s ms', - self.options.reconnectTries, - self.options.reconnectInterval - ) - ) - ); - } else { - self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); - } - }; - } - - // Got a connect handler - function _connectHandler(self) { - return function() { - // Assign - var connection = this; - - // Pool destroyed stop the connection - if (self.state === DESTROYED || self.state === DESTROYING) { - return connection.destroy(); - } - - // Clear out all handlers - handlers.forEach(function(event) { - connection.removeAllListeners(event); - }); - - // Reset reconnect id - self.reconnectId = null; - - // Apply pool connection handlers - connection.on('error', connectionFailureHandler(self, 'error')); - connection.on('close', connectionFailureHandler(self, 'close')); - connection.on('timeout', connectionFailureHandler(self, 'timeout')); - connection.on('parseError', connectionFailureHandler(self, 'parseError')); - - // Apply any auth to the connection - reauthenticate(self, this, function() { - // Reset retries - self.retriesLeft = self.options.reconnectTries; - // Push to available connections - self.availableConnections.push(connection); - // Set the reconnectConnection to null - self.reconnectConnection = null; - // Emit reconnect event - self.emit('reconnect', self); - // Trigger execute to start everything up again - _execute(self)(); - }); - }; - } - - // Create a connection - self.reconnectConnection = new Connection(messageHandler(self), self.options); - // Add handlers - self.reconnectConnection.on('close', _connectionFailureHandler(self, 'close')); - self.reconnectConnection.on('error', _connectionFailureHandler(self, 'error')); - self.reconnectConnection.on('timeout', _connectionFailureHandler(self, 'timeout')); - self.reconnectConnection.on('parseError', _connectionFailureHandler(self, 'parseError')); - // On connection - self.reconnectConnection.on('connect', _connectHandler(self)); - // Attempt connection - self.reconnectConnection.connect(); - }; -} - -function moveConnectionBetween(connection, from, to) { - var index = from.indexOf(connection); - // Move the connection from connecting to available - if (index !== -1) { - from.splice(index, 1); - to.push(connection); - } -} - -function messageHandler(self) { - return function(message, connection) { - // workItem to execute - var workItem = null; - - // Locate the workItem - for (var i = 0; i < connection.workItems.length; i++) { - if (connection.workItems[i].requestId === message.responseTo) { - // Get the callback - workItem = connection.workItems[i]; - // Remove from list of workItems - connection.workItems.splice(i, 1); - } - } - - // Reset timeout counter - self.numberOfConsecutiveTimeouts = 0; - - // Reset the connection timeout if we modified it for - // this operation - if (workItem && workItem.socketTimeout) { - connection.resetSocketTimeout(); - } - - // Log if debug enabled - if (self.logger.isDebug()) { - self.logger.debug( - f( - 'message [%s] received from %s:%s', - message.raw.toString('hex'), - self.options.host, - self.options.port - ) - ); - } - - // Authenticate any straggler connections - function authenticateStragglers(self, connection, callback) { - // Get any non authenticated connections - var connections = self.nonAuthenticatedConnections.slice(0); - var nonAuthenticatedConnections = self.nonAuthenticatedConnections; - self.nonAuthenticatedConnections = []; - - // Establish if the connection need to be authenticated - // Add to authentication list if - // 1. we were in an authentication process when the operation was executed - // 2. our current authentication timestamp is from the workItem one, meaning an auth has happened - if ( - connection.workItems.length === 1 && - (connection.workItems[0].authenticating === true || - (typeof connection.workItems[0].authenticatingTimestamp === 'number' && - connection.workItems[0].authenticatingTimestamp !== self.authenticatingTimestamp)) - ) { - // Add connection to the list - connections.push(connection); - } - - // No connections need to be re-authenticated - if (connections.length === 0) { - // Release the connection back to the pool - moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); - // Finish - return callback(); - } - - // Apply re-authentication to all connections before releasing back to pool - var connectionCount = connections.length; - // Authenticate all connections - for (var i = 0; i < connectionCount; i++) { - reauthenticate(self, connections[i], function() { - connectionCount = connectionCount - 1; - - if (connectionCount === 0) { - // Put non authenticated connections in available connections - self.availableConnections = self.availableConnections.concat( - nonAuthenticatedConnections - ); - // Release the connection back to the pool - moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); - // Return - callback(); - } - }); - } - } - - function handleOperationCallback(self, cb, err, result) { - // No domain enabled - if (!self.options.domainsEnabled) { - return process.nextTick(function() { - return cb(err, result); - }); - } - - // Domain enabled just call the callback - cb(err, result); - } - - authenticateStragglers(self, connection, function() { - // Keep executing, ensure current message handler does not stop execution - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - - // Time to dispatch the message if we have a callback - if (workItem && !workItem.immediateRelease) { - try { - // Parse the message according to the provided options - message.parse(workItem); - } catch (err) { - return handleOperationCallback(self, workItem.cb, new MongoError(err)); - } - - // Look for clusterTime, and operationTime and update them if necessary - if (message.documents[0]) { - if (message.documents[0].$clusterTime) { - const $clusterTime = message.documents[0].$clusterTime; - self.topology.clusterTime = $clusterTime; - - if (workItem.session != null) { - resolveClusterTime(workItem.session, $clusterTime); - } - } - - if ( - message.documents[0].operationTime && - workItem.session && - workItem.session.supports.causalConsistency - ) { - workItem.session.advanceOperationTime(message.documents[0].operationTime); - } - } - - // Establish if we have an error - if (workItem.command && message.documents[0]) { - const responseDoc = message.documents[0]; - if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { - return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); - } - - if (responseDoc.writeConcernError) { - const err = - responseDoc.ok === 1 - ? new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc) - : new MongoWriteConcernError(responseDoc.writeConcernError); - return handleOperationCallback(self, workItem.cb, err); - } - } - - // Add the connection details - message.hashedName = connection.hashedName; - - // Return the documents - handleOperationCallback( - self, - workItem.cb, - null, - new CommandResult( - workItem.fullResult ? message : message.documents[0], - connection, - message - ) - ); - } - }); - }; -} - -/** - * Return the total socket count in the pool. - * @method - * @return {Number} The number of socket available. - */ -Pool.prototype.socketCount = function() { - return this.availableConnections.length + this.inUseConnections.length; - // + this.connectingConnections.length; -}; - -/** - * Return all pool connections - * @method - * @return {Connection[]} The pool connections - */ -Pool.prototype.allConnections = function() { - return this.availableConnections.concat(this.inUseConnections).concat(this.connectingConnections); -}; - -/** - * Get a pool connection (round-robin) - * @method - * @return {Connection} - */ -Pool.prototype.get = function() { - return this.allConnections()[0]; -}; - -/** - * Is the pool connected - * @method - * @return {boolean} - */ -Pool.prototype.isConnected = function() { - // We are in a destroyed state - if (this.state === DESTROYED || this.state === DESTROYING) { - return false; - } - - // Get connections - var connections = this.availableConnections.concat(this.inUseConnections); - - // Check if we have any connected connections - for (var i = 0; i < connections.length; i++) { - if (connections[i].isConnected()) return true; - } - - // Might be authenticating, but we are still connected - if (connections.length === 0 && this.authenticating) { - return true; - } - - // Not connected - return false; -}; - -/** - * Was the pool destroyed - * @method - * @return {boolean} - */ -Pool.prototype.isDestroyed = function() { - return this.state === DESTROYED || this.state === DESTROYING; -}; - -/** - * Is the pool in a disconnected state - * @method - * @return {boolean} - */ -Pool.prototype.isDisconnected = function() { - return this.state === DISCONNECTED; -}; - -/** - * Connect pool - * @method - */ -Pool.prototype.connect = function() { - if (this.state !== DISCONNECTED) { - throw new MongoError('connection in unlawful state ' + this.state); - } - - var self = this; - // Transition to connecting state - stateTransition(this, CONNECTING); - // Create an array of the arguments - var args = Array.prototype.slice.call(arguments, 0); - // Create a connection - var connection = new Connection(messageHandler(self), this.options); - // Add to list of connections - this.connectingConnections.push(connection); - // Add listeners to the connection - connection.once('connect', function(connection) { - if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); - - // If we are in a topology, delegate the auth to it - // This is to avoid issues where we would auth against an - // arbiter - if (self.options.inTopology) { - // Set connected mode - stateTransition(self, CONNECTED); - - // Move the active connection - moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); - - // Emit the connect event - return self.emit('connect', self); - } - - // Apply any store credentials - reauthenticate(self, connection, function(err) { - if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); - - // We have an error emit it - if (err) { - // Destroy the pool - self.destroy(); - // Emit the error - return self.emit('error', err); - } - - // Authenticate - authenticate(self, args, connection, function(err) { - if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); - - // We have an error emit it - if (err) { - // Destroy the pool - self.destroy(); - // Emit the error - return self.emit('error', err); - } - // Set connected mode - stateTransition(self, CONNECTED); - - // Move the active connection - moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); - - // if we have a minPoolSize, create a connection - if (self.minSize) { - for (let i = 0; i < self.minSize; i++) _createConnection(self); - } - - // Emit the connect event - self.emit('connect', self); - }); - }); - }); - - // Add error handlers - connection.once('error', connectionFailureHandler(this, 'error')); - connection.once('close', connectionFailureHandler(this, 'close')); - connection.once('timeout', connectionFailureHandler(this, 'timeout')); - connection.once('parseError', connectionFailureHandler(this, 'parseError')); - - try { - connection.connect(); - } catch (err) { - // SSL or something threw on connect - process.nextTick(function() { - self.emit('error', err); - }); - } -}; - -/** - * 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 - */ -Pool.prototype.auth = function(mechanism) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - var callback = args.pop(); - - // If we don't have the mechanism fail - if (self.authProviders[mechanism] == null && mechanism !== 'default') { - throw new MongoError(f('auth provider %s does not exist', mechanism)); - } - - // Signal that we are authenticating a new set of credentials - this.authenticating = true; - this.authenticatingTimestamp = new Date().getTime(); - - // Authenticate all live connections - function authenticateLiveConnections(self, args, cb) { - // Get the current viable connections - var connections = self.allConnections(); - // Allow nothing else to use the connections while we authenticate them - self.availableConnections = []; - self.inUseConnections = []; - self.connectingConnections = []; - - var connectionsCount = connections.length; - var error = null; - // No connections available, return - if (connectionsCount === 0) { - self.authenticating = false; - return callback(null); - } - - // Authenticate the connections - for (var i = 0; i < connections.length; i++) { - authenticate(self, args, connections[i], function(err, result) { - connectionsCount = connectionsCount - 1; - - // Store the error - if (err) error = err; - - // Processed all connections - if (connectionsCount === 0) { - // Auth finished - self.authenticating = false; - // Add the connections back to available connections - self.availableConnections = self.availableConnections.concat(connections); - // We had an error, return it - if (error) { - // Log the error - if (self.logger.isError()) { - self.logger.error( - f( - '[%s] failed to authenticate against server %s:%s', - self.id, - self.options.host, - self.options.port - ) - ); - } - - return cb(error, result); - } - cb(null, result); - } - }); - } - } - - // Wait for a logout in process to happen - function waitForLogout(self, cb) { - if (!self.loggingout) return cb(); - setTimeout(function() { - waitForLogout(self, cb); - }, 1); - } - - // Wait for loggout to finish - waitForLogout(self, function() { - // Authenticate all live connections - authenticateLiveConnections(self, args, function(err, result) { - // Credentials correctly stored in auth provider if successful - // Any new connections will now reauthenticate correctly - self.authenticating = false; - // Return after authentication connections - callback(err, result); - }); - }); -}; - -/** - * Logout all users against a database - * @method - * @param {string} dbName The database name - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.logout = function(dbName, callback) { - var self = this; - if (typeof dbName !== 'string') { - throw new MongoError('logout method requires a db name as first argument'); - } - - if (typeof callback !== 'function') { - throw new MongoError('logout method requires a callback'); - } - - // Indicate logout in process - this.loggingout = true; - - // Get all relevant connections - var connections = self.availableConnections.concat(self.inUseConnections); - var count = connections.length; - // Store any error - var error = null; - - // Send logout command over all the connections - for (var i = 0; i < connections.length; i++) { - write(self)( - connections[i], - new Query( - this.options.bson, - f('%s.$cmd', dbName), - { logout: 1 }, - { numberToSkip: 0, numberToReturn: 1 } - ), - function(err) { - count = count - 1; - if (err) error = err; - - if (count === 0) { - self.loggingout = false; - callback(error); - } - } - ); - } -}; - -/** - * Unref the pool - * @method - */ -Pool.prototype.unref = function() { - // Get all the known connections - var connections = this.availableConnections - .concat(this.inUseConnections) - .concat(this.connectingConnections); - connections.forEach(function(c) { - c.unref(); - }); -}; - -// Events -var events = ['error', 'close', 'timeout', 'parseError', 'connect']; - -// Destroy the connections -function destroy(self, connections) { - // Destroy all connections - connections.forEach(function(c) { - // Remove all listeners - for (var i = 0; i < events.length; i++) { - c.removeAllListeners(events[i]); - } - // Destroy connection - c.destroy(); - }); - - // Zero out all connections - self.inUseConnections = []; - self.availableConnections = []; - self.nonAuthenticatedConnections = []; - self.connectingConnections = []; - - // Set state to destroyed - stateTransition(self, DESTROYED); -} - -/** - * Destroy pool - * @method - */ -Pool.prototype.destroy = function(force) { - var self = this; - // Do not try again if the pool is already dead - if (this.state === DESTROYED || self.state === DESTROYING) return; - // Set state to destroyed - stateTransition(this, DESTROYING); - - // Are we force closing - if (force) { - // Get all the known connections - var connections = self.availableConnections - .concat(self.inUseConnections) - .concat(self.nonAuthenticatedConnections) - .concat(self.connectingConnections); - - // Flush any remaining work items with - // an error - while (self.queue.length > 0) { - var workItem = self.queue.shift(); - if (typeof workItem.cb === 'function') { - workItem.cb(new MongoError('Pool was force destroyed')); - } - } - - // Destroy the topology - return destroy(self, connections); - } - - // Clear out the reconnect if set - if (this.reconnectId) { - clearTimeout(this.reconnectId); - } - - // If we have a reconnect connection running, close - // immediately - if (this.reconnectConnection) { - this.reconnectConnection.destroy(); - } - - // Wait for the operations to drain before we close the pool - function checkStatus() { - flushMonitoringOperations(self.queue); - - if (self.queue.length === 0) { - // Get all the known connections - var connections = self.availableConnections - .concat(self.inUseConnections) - .concat(self.nonAuthenticatedConnections) - .concat(self.connectingConnections); - - // Check if we have any in flight operations - for (var i = 0; i < connections.length; i++) { - // There is an operation still in flight, reschedule a - // check waiting for it to drain - if (connections[i].workItems.length > 0) { - return setTimeout(checkStatus, 1); - } - } - - destroy(self, connections); - // } else if (self.queue.length > 0 && !this.reconnectId) { - } else { - // Ensure we empty the queue - _execute(self)(); - // Set timeout - setTimeout(checkStatus, 1); - } - } - - // Initiate drain of operations - checkStatus(); -}; - -// Prepare the buffer that Pool.prototype.write() uses to send to the server -var serializeCommands = function(self, commands, result, callback) { - // Base case when there are no more commands to serialize - if (commands.length === 0) return callback(null, result); - - // Pop off the zeroth command and serialize it - var thisCommand = commands.shift(); - var originalCommandBuffer = thisCommand.toBin(); - - // Check whether we and the server have agreed to use a compressor - if (self.options.agreedCompressor && !hasUncompressibleCommands(thisCommand)) { - // Transform originalCommandBuffer into OP_COMPRESSED - var concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); - var messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); - - // Extract information needed for OP_COMPRESSED from the uncompressed message - var originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); - - // Compress the message body - compress(self, messageToBeCompressed, function(err, compressedMessage) { - if (err) return callback(err, null); - - // Create the msgHeader of OP_COMPRESSED - var msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); - msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + 9 + compressedMessage.length, 0); // messageLength - msgHeader.writeInt32LE(thisCommand.requestId, 4); // requestID - msgHeader.writeInt32LE(0, 8); // responseTo (zero) - msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode - - // Create the compression details of OP_COMPRESSED - var compressionDetails = Buffer.alloc(9); - compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode - compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader - compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID - - // Push the concatenation of the OP_COMPRESSED message onto results - result.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); - - // Continue recursing through the commands array - serializeCommands(self, commands, result, callback); - }); - } else { - // Push the serialization of the command onto results - result.push(originalCommandBuffer); - - // Continue recursing through the commands array - serializeCommands(self, commands, result, callback); - } -}; - -/** - * Write a message to MongoDB - * @method - * @return {Connection} - */ -Pool.prototype.write = function(commands, options, cb) { - var self = this; - // Ensure we have a callback - if (typeof options === 'function') { - cb = options; - } - - // Always have options - options = options || {}; - - // We need to have a callback function unless the message returns no response - if (!(typeof cb === 'function') && !options.noResponse) { - throw new MongoError('write method must provide a callback'); - } - - // Pool was destroyed error out - if (this.state === DESTROYED || this.state === DESTROYING) { - // Callback with an error - if (cb) { - try { - cb(new MongoError('pool destroyed')); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - } - - return; - } - - if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { - // if we have a domain bind to it - var oldCb = cb; - cb = process.domain.bind(function() { - // v8 - argumentsToArray one-liner - var args = new Array(arguments.length); - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - // bounce off event loop so domain switch takes place - process.nextTick(function() { - oldCb.apply(null, args); - }); - }); - } - - // Do we have an operation - var operation = { - cb: cb, - raw: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - fullResult: false - }; - - // Set the options for the parsing - operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; - operation.promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : true; - operation.promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; - operation.raw = typeof options.raw === 'boolean' ? options.raw : false; - operation.immediateRelease = - typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; - operation.documentsReturnedIn = options.documentsReturnedIn; - operation.command = typeof options.command === 'boolean' ? options.command : false; - operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; - operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; - operation.session = options.session || null; - - // Optional per operation socketTimeout - operation.socketTimeout = options.socketTimeout; - operation.monitoring = options.monitoring; - // Custom socket Timeout - if (options.socketTimeout) { - operation.socketTimeout = options.socketTimeout; - } - - // Ensure commands is an array - if (!Array.isArray(commands)) { - commands = [commands]; - } - - // Get the requestId - operation.requestId = commands[commands.length - 1].requestId; - - if (hasSessionSupport(this.topology)) { - let sessionOptions = {}; - if (this.topology.clusterTime) { - sessionOptions = { $clusterTime: this.topology.clusterTime }; - } - - if (operation.session) { - // TODO: reenable when sessions development is complete - // if (operation.session.topology !== this.topology) { - // return cb( - // new MongoError('Sessions may only be used with the client they were created from') - // ); - // } - - if (operation.session.hasEnded) { - return cb(new MongoError('Use of expired sessions is not permitted')); - } - - if ( - operation.session.clusterTime && - operation.session.clusterTime.clusterTime.greaterThan( - sessionOptions.$clusterTime.clusterTime - ) - ) { - sessionOptions.$clusterTime = operation.session.clusterTime; - } - - sessionOptions.lsid = operation.session.id; - - // update the `lastUse` of the acquired ServerSession - operation.session.serverSession.lastUse = Date.now(); - } - - // decorate the commands with session-specific details - commands.forEach(command => { - if (command instanceof Query) { - if (command.query.$query) { - Object.assign(command.query.$query, sessionOptions); - } else { - Object.assign(command.query, sessionOptions); - } - } else { - Object.assign(command, sessionOptions); - } - }); - } - - // If command monitoring is enabled we need to modify the callback here - if (self.options.monitorCommands) { - // NOTE: there is only ever a single command, for some legacy reason I am unaware of we - // treat this as a potential array of commands - const command = commands[0]; - this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); - - operation.started = process.hrtime(); - operation.cb = (err, reply) => { - if (err) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, err, operation.started) - ); - } else { - if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, reply.result, operation.started) - ); - } else { - self.emit( - 'commandSucceeded', - new apm.CommandSucceededEvent(this, command, reply, operation.started) - ); - } - } - - if (typeof cb === 'function') cb(err, reply); - }; - } - - // Prepare the operation buffer - serializeCommands(self, commands, [], function(err, serializedCommands) { - if (err) throw err; - - // Set the operation's buffer to the serialization of the commands - operation.buffer = serializedCommands; - - // If we have a monitoring operation schedule as the very first operation - // Otherwise add to back of queue - if (options.monitoring) { - self.queue.unshift(operation); - } else { - self.queue.push(operation); - } - - // Attempt to execute the operation - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - }); -}; - -// Return whether a command contains an uncompressible command term -// Will return true if command contains no uncompressible command terms -var hasUncompressibleCommands = function(command) { - return uncompressibleCommands.some(function(cmd) { - return command.query.hasOwnProperty(cmd); - }); -}; - -// Remove connection method -function remove(connection, connections) { - for (var i = 0; i < connections.length; i++) { - if (connections[i] === connection) { - connections.splice(i, 1); - return true; - } - } -} - -function removeConnection(self, connection) { - if (remove(connection, self.availableConnections)) return; - if (remove(connection, self.inUseConnections)) return; - if (remove(connection, self.connectingConnections)) return; - if (remove(connection, self.nonAuthenticatedConnections)) return; -} - -// All event handlers -var handlers = ['close', 'message', 'error', 'timeout', 'parseError', 'connect']; - -function _createConnection(self) { - if (self.state === DESTROYED || self.state === DESTROYING) { - return; - } - var connection = new Connection(messageHandler(self), self.options); - - // Push the connection - self.connectingConnections.push(connection); - - // Handle any errors - var tempErrorHandler = function(_connection) { - return function() { - // Destroy the connection - _connection.destroy(); - // Remove the connection from the connectingConnections list - removeConnection(self, _connection); - // Start reconnection attempts - if (!self.reconnectId && self.options.reconnect) { - self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); - } - }; - }; - - // Handle successful connection - var tempConnectHandler = function(_connection) { - return function() { - // Destroyed state return - if (self.state === DESTROYED || self.state === DESTROYING) { - // Remove the connection from the list - removeConnection(self, _connection); - return _connection.destroy(); - } - - // Destroy all event emitters - handlers.forEach(function(e) { - _connection.removeAllListeners(e); - }); - - // Add the final handlers - _connection.once('close', connectionFailureHandler(self, 'close')); - _connection.once('error', connectionFailureHandler(self, 'error')); - _connection.once('timeout', connectionFailureHandler(self, 'timeout')); - _connection.once('parseError', connectionFailureHandler(self, 'parseError')); - - // Signal - reauthenticate(self, _connection, function(err) { - if (self.state === DESTROYED || self.state === DESTROYING) { - return _connection.destroy(); - } - // Remove the connection from the connectingConnections list - removeConnection(self, _connection); - - // Handle error - if (err) { - return _connection.destroy(); - } - - // If we are c at the moment - // Do not automatially put in available connections - // As we need to apply the credentials first - if (self.authenticating) { - self.nonAuthenticatedConnections.push(_connection); - } else { - // Push to available - self.availableConnections.push(_connection); - // Execute any work waiting - _execute(self)(); - } - }); - }; - }; - - // Add all handlers - connection.once('close', tempErrorHandler(connection)); - connection.once('error', tempErrorHandler(connection)); - connection.once('timeout', tempErrorHandler(connection)); - connection.once('parseError', tempErrorHandler(connection)); - connection.once('connect', tempConnectHandler(connection)); - - // Start connection - connection.connect(); -} - -function flushMonitoringOperations(queue) { - for (var i = 0; i < queue.length; i++) { - if (queue[i].monitoring) { - var workItem = queue[i]; - queue.splice(i, 1); - workItem.cb( - new MongoError({ message: 'no connection available for monitoring', driver: true }) - ); - } - } -} - -function _execute(self) { - return function() { - if (self.state === DESTROYED) return; - // Already executing, skip - if (self.executing) return; - // Set pool as executing - self.executing = true; - - // Wait for auth to clear before continuing - function waitForAuth(cb) { - if (!self.authenticating) return cb(); - // Wait for a milisecond and try again - setTimeout(function() { - waitForAuth(cb); - }, 1); - } - - // Block on any auth in process - waitForAuth(function() { - // New pool connections are in progress, wait them to finish - // before executing any more operation to ensure distribution of - // operations - if (self.connectingConnections.length > 0) { - return; - } - - // As long as we have available connections - // eslint-disable-next-line - while (true) { - // Total availble connections - var totalConnections = - self.availableConnections.length + - self.connectingConnections.length + - self.inUseConnections.length; - - // No available connections available, flush any monitoring ops - if (self.availableConnections.length === 0) { - // Flush any monitoring operations - flushMonitoringOperations(self.queue); - break; - } - - // No queue break - if (self.queue.length === 0) { - break; - } - - // Get a connection - var connection = null; - - // Locate all connections that have no work - var connections = []; - // Get a list of all connections - for (var i = 0; i < self.availableConnections.length; i++) { - if (self.availableConnections[i].workItems.length === 0) { - connections.push(self.availableConnections[i]); - } - } - - // No connection found that has no work on it, just pick one for pipelining - if (connections.length === 0) { - connection = - self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; - } else { - connection = connections[self.connectionIndex++ % connections.length]; - } - - // Is the connection connected - if (connection.isConnected()) { - // Get the next work item - var workItem = self.queue.shift(); - - // If we are monitoring we need to use a connection that is not - // running another operation to avoid socket timeout changes - // affecting an existing operation - if (workItem.monitoring) { - var foundValidConnection = false; - - for (i = 0; i < self.availableConnections.length; i++) { - // If the connection is connected - // And there are no pending workItems on it - // Then we can safely use it for monitoring. - if ( - self.availableConnections[i].isConnected() && - self.availableConnections[i].workItems.length === 0 - ) { - foundValidConnection = true; - connection = self.availableConnections[i]; - break; - } - } - - // No safe connection found, attempt to grow the connections - // if possible and break from the loop - if (!foundValidConnection) { - // Put workItem back on the queue - self.queue.unshift(workItem); - - // Attempt to grow the pool if it's not yet maxsize - if (totalConnections < self.options.size && self.queue.length > 0) { - // Create a new connection - _createConnection(self); - } - - // Re-execute the operation - setTimeout(function() { - _execute(self)(); - }, 10); - - break; - } - } - - // Don't execute operation until we have a full pool - if (totalConnections < self.options.size) { - // Connection has work items, then put it back on the queue - // and create a new connection - if (connection.workItems.length > 0) { - // Lets put the workItem back on the list - self.queue.unshift(workItem); - // Create a new connection - _createConnection(self); - // Break from the loop - break; - } - } - - // Get actual binary commands - var buffer = workItem.buffer; - - // Set current status of authentication process - workItem.authenticating = self.authenticating; - workItem.authenticatingTimestamp = self.authenticatingTimestamp; - - // If we are monitoring take the connection of the availableConnections - if (workItem.monitoring) { - moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); - } - - // Track the executing commands on the mongo server - // as long as there is an expected response - if (!workItem.noResponse) { - connection.workItems.push(workItem); - } - - // We have a custom socketTimeout - if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { - connection.setSocketTimeout(workItem.socketTimeout); - } - - // Capture if write was successful - var writeSuccessful = true; - - // Put operation on the wire - if (Array.isArray(buffer)) { - for (i = 0; i < buffer.length; i++) { - writeSuccessful = connection.write(buffer[i]); - } - } else { - writeSuccessful = connection.write(buffer); - } - - // if the command is designated noResponse, call the callback immeditely - if (workItem.noResponse && typeof workItem.cb === 'function') { - workItem.cb(null, null); - } - - if (writeSuccessful && workItem.immediateRelease && self.authenticating) { - removeConnection(self, connection); - self.nonAuthenticatedConnections.push(connection); - } else if (writeSuccessful === false) { - // If write not successful put back on queue - self.queue.unshift(workItem); - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - } - } else { - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - } - } - }); - - self.executing = false; - }; -} - -// Make execution loop available for testing -Pool._execute = _execute; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Pool#connect - * @type {Pool} - */ - -/** - * A server reconnect event, used to verify that pool reconnected. - * - * @event Pool#reconnect - * @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} - */ - -/** - * The driver attempted to reconnect - * - * @event Pool#attemptReconnect - * @type {Pool} - */ - -/** - * The driver exhausted all reconnect attempts - * - * @event Pool#reconnectFailed - * @type {Pool} - */ - -module.exports = Pool; diff --git a/node_modules/mongodb-core/lib/connection/utils.js b/node_modules/mongodb-core/lib/connection/utils.js deleted file mode 100644 index e2d8dff5003c88757b5a6a2bd73dcaf069879c76..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/connection/utils.js +++ /dev/null @@ -1,113 +0,0 @@ -'use strict'; - -var f = require('util').format, - require_optional = require('require_optional'); - -// 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; -}; - -var retrieveBSON = function() { - var BSON = require('bson'); - BSON.native = false; - - try { - var optionalBSON = require_optional('bson-ext'); - if (optionalBSON) { - optionalBSON.native = true; - return optionalBSON; - } - } catch (err) {} // eslint-disable-line - - return BSON; -}; - -// Throw an error if an attempt to use Snappy is made when Snappy is not installed -var noSnappyWarning = function() { - throw new Error( - 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' - ); -}; - -// Facilitate loading Snappy optionally -var retrieveSnappy = function() { - var snappy = null; - try { - snappy = require_optional('snappy'); - } catch (error) {} // eslint-disable-line - if (!snappy) { - snappy = { - compress: noSnappyWarning, - uncompress: noSnappyWarning, - compressSync: noSnappyWarning, - uncompressSync: noSnappyWarning - }; - } - return snappy; -}; - -exports.setProperty = setProperty; -exports.getProperty = getProperty; -exports.getSingleProperty = getSingleProperty; -exports.copy = copy; -exports.debugOptions = debugOptions; -exports.retrieveBSON = retrieveBSON; -exports.retrieveSnappy = retrieveSnappy; diff --git a/node_modules/mongodb-core/lib/cursor.js b/node_modules/mongodb-core/lib/cursor.js deleted file mode 100644 index 032fae6721a0d0977bf7a20cb0091e6803d22c0f..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/cursor.js +++ /dev/null @@ -1,766 +0,0 @@ -'use strict'; - -const Logger = require('./connection/logger'); -const retrieveBSON = require('./connection/utils').retrieveBSON; -const MongoError = require('./error').MongoError; -const MongoNetworkError = require('./error').MongoNetworkError; -const mongoErrorContextSymbol = require('./error').mongoErrorContextSymbol; -const f = require('util').format; -const collationNotSupported = require('./utils').collationNotSupported; - -const BSON = retrieveBSON(); -const Long = BSON.Long; - -/** - * 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 pool - this.pool = 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, - cmd: cmd, - 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, - raw: options.raw || (cmd && cmd.raw) - }; - - if (typeof options.session === 'object') { - this.cursorState.session = options.session; - } - - // Add promoteLong to cursor state - if (typeof topologyOptions.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = topologyOptions.promoteLongs; - } else if (typeof options.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = options.promoteLongs; - } - - // Add promoteValues to cursor state - if (typeof topologyOptions.promoteValues === 'boolean') { - this.cursorState.promoteValues = topologyOptions.promoteValues; - } else if (typeof options.promoteValues === 'boolean') { - this.cursorState.promoteValues = options.promoteValues; - } - - // Add promoteBuffers to cursor state - if (typeof topologyOptions.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; - } else if (typeof options.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = options.promoteBuffers; - } - - if (topologyOptions.reconnect) { - this.cursorState.reconnect = topologyOptions.reconnect; - } - - // Logger - this.logger = Logger('Cursor', topologyOptions); - - // - // Did we pass in a cursor id - if (typeof cmd === 'number') { - this.cursorState.cursorId = Long.fromNumber(cmd); - this.cursorState.lastCursorId = this.cursorState.cursorId; - } else if (cmd instanceof Long) { - this.cursorState.cursorId = cmd; - this.cursorState.lastCursorId = 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; -}; - -Cursor.prototype._endSession = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - - const session = this.cursorState.session; - - if (session && (options.force || session.owner === this)) { - this.cursorState.session = undefined; - session.endSession(callback); - return true; - } - - if (callback) { - callback(); - } - return false; -}; - -// -// Handle callback (including any exceptions thrown) -var handleCallback = function(callback, err, result) { - try { - callback(err, result); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } -}; - -// Internal methods -Cursor.prototype._getmore = function(callback) { - if (this.logger.isDebug()) - this.logger.debug(f('schedule getMore call for query [%s]', JSON.stringify(this.query))); - - // Set the current batchSize - var batchSize = this.cursorState.batchSize; - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + batchSize > this.cursorState.limit - ) { - batchSize = this.cursorState.limit - this.cursorState.currentLimit; - } - - this.server.wireProtocolHandler.getMore( - this.server, - this.ns, - this.cursorState, - batchSize, - this.options, - callback - ); -}; - -/** - * 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 - ); - - // 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]); - } - } - - // Ensure we do not return any more documents than the limit imposed - // Just return the number of elements up to the limit - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + elements.length > this.cursorState.limit - ) { - elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); - this.kill(); - } - - // Adjust current limit - this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; - this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; - - // 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; - } - - this.server.wireProtocolHandler.killCursor(this.server, this.ns, this.cursorState, 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 pool is dead and return error - */ -var isConnectionDead = function(self, callback) { - if (self.pool && self.pool.isDestroyed()) { - self.cursorState.killed = true; - const err = new MongoNetworkError( - f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port) - ); - _setCursorNotifiedImpl(self, () => callback(err)); - 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.killed = true; - setCursorNotified(self, callback); - 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, new MongoError('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) { - setCursorNotified(self, callback); - return true; - } - - return false; -}; - -/** - * Mark cursor as being dead and notified - */ -var setCursorDeadAndNotified = function(self, callback) { - self.cursorState.dead = true; - setCursorNotified(self, callback); -}; - -/** - * Mark cursor as being notified - */ -var setCursorNotified = function(self, callback) { - _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); -}; - -var _setCursorNotifiedImpl = function(self, callback) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - if (self._endSession) { - return self._endSession(undefined, () => callback()); - } - return callback(); -}; - -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) { - return initializeCursor(self, callback); - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - 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 MongoNetworkError('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 - self._getmore(function(err, doc, connection) { - if (err) { - if (err instanceof MongoError) { - err[mongoErrorContextSymbol].isGetMore = true; - } - - return handleCallback(callback, err); - } - - if (self.cursorState.cursorId && self.cursorState.cursorId.isZero() && self._endSession) { - self._endSession(); - } - - // Save the returned connection to ensure all getMore's fire over the same connection - self.connection = connection; - - // 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 && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - // No more documents in the tailed cursor - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - return nextFunction(self, callback); - } - - 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 && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - return handleCallback( - callback, - new MongoError({ - 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) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } - - // Increment the current cursor limit - self.cursorState.currentLimit += 1; - - // Get the document - var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; - - // Doc overflow - if (!doc || doc.$err) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, function() { - handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); - }); - } - - // 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); - } -}; - -function initializeCursor(cursor, callback) { - // 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 (!cursor.topology.isConnected(cursor.options)) { - // Only need this for single server, because repl sets and mongos - // will always continue trying to reconnect - if (cursor.topology._type === 'server' && !cursor.topology.s.options.reconnect) { - // Reconnect is disabled, so we'll never reconnect - return callback(new MongoError('no connection available')); - } - - if (cursor.disconnectHandler != null) { - if (cursor.topology.isDestroyed()) { - // Topology was destroyed, so don't try to wait for it to reconnect - return callback(new MongoError('Topology was destroyed')); - } - - return cursor.disconnectHandler.addObjectAndMethod( - 'cursor', - cursor, - 'next', - [callback], - callback - ); - } - } - - return cursor.topology.selectServer(cursor.options, (err, server) => { - if (err) { - const disconnectHandler = cursor.disconnectHandler; - if (disconnectHandler != null) { - return disconnectHandler.addObjectAndMethod('cursor', cursor, 'next', [callback], callback); - } - - return callback(err); - } - - cursor.server = server; - cursor.cursorState.init = true; - if (collationNotSupported(cursor.server, cursor.cmd)) { - return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); - } - - function done() { - if ( - cursor.cursorState.cursorId && - cursor.cursorState.cursorId.isZero() && - cursor._endSession - ) { - cursor._endSession(); - } - - if ( - cursor.cursorState.documents.length === 0 && - cursor.cursorState.cursorId && - cursor.cursorState.cursorId.isZero() && - !cursor.cmd.tailable && - !cursor.cmd.awaitData - ) { - return setCursorNotified(cursor, callback); - } - - nextFunction(cursor, callback); - } - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - const queryCallback = (err, r) => { - if (err) return callback(err); - - const result = r.message; - if (result.queryFailure) { - return callback(new MongoError(result.documents[0]), null); - } - - // Check if we have a command cursor - if ( - Array.isArray(result.documents) && - result.documents.length === 1 && - (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && - (typeof result.documents[0].cursor !== 'string' || - result.documents[0]['$err'] || - result.documents[0]['errmsg'] || - Array.isArray(result.documents[0].result)) - ) { - // We have an error document, return the error - if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { - return callback(new MongoError(result.documents[0]), null); - } - - // We have a cursor document - 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) { - cursor.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; - cursor.cursorState.lastCursorId = cursor.cursorState.cursorId; - cursor.cursorState.operationTime = result.documents[0].operationTime; - // If we have a firstBatch set it - if (Array.isArray(result.documents[0].cursor.firstBatch)) { - cursor.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse(); - } - - // Return after processing command cursor - return done(result); - } - - if (Array.isArray(result.documents[0].result)) { - cursor.cursorState.documents = result.documents[0].result; - cursor.cursorState.cursorId = Long.ZERO; - return done(result); - } - } - - // Otherwise fall back to regular find path - cursor.cursorState.cursorId = result.cursorId; - cursor.cursorState.documents = result.documents; - cursor.cursorState.lastCursorId = result.cursorId; - - // Transform the results with passed in transformation method if provided - if ( - cursor.cursorState.transforms && - typeof cursor.cursorState.transforms.query === 'function' - ) { - cursor.cursorState.documents = cursor.cursorState.transforms.query(result); - } - - // Return callback - done(result); - }; - - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - if (cursor.cmd.find != null) { - cursor.server.wireProtocolHandler.query( - cursor.server, - cursor.ns, - cursor.cmd, - cursor.cursorState, - cursor.options, - queryCallback - ); - - return; - } - - cursor.query = cursor.server.wireProtocolHandler.command( - cursor.server, - cursor.ns, - cursor.cmd, - cursor.options, - queryCallback - ); - }); -} - -/** - * 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/mongodb-core/lib/error.js b/node_modules/mongodb-core/lib/error.js deleted file mode 100644 index c0d707c1a8f7afc62522c1edd72a2ab7dd68c0d8..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/error.js +++ /dev/null @@ -1,146 +0,0 @@ -'use strict'; - -const mongoErrorContextSymbol = Symbol('mongoErrorContextSymbol'); - -/** - * Creates a new MongoError - * - * @augments Error - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - */ -class MongoError extends Error { - constructor(message) { - if (message instanceof Error) { - super(message.message); - this.stack = message.stack; - } else { - if (typeof message === 'string') { - super(message); - } else { - super(message.message || message.errmsg || message.$err || 'n/a'); - for (var name in message) { - this[name] = message[name]; - } - } - - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'MongoError'; - this[mongoErrorContextSymbol] = this[mongoErrorContextSymbol] || {}; - } - - /** - * Creates a new MongoError object - * - * @param {Error|string|object} options The options used to create the error. - * @return {MongoError} A MongoError instance - * @deprecated Use `new MongoError()` instead. - */ - static create(options) { - return new MongoError(options); - } -} - -/** - * Creates a new MongoNetworkError - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - */ -class MongoNetworkError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoNetworkError'; - - // This is added as part of the transactions specification - this.errorLabels = ['TransientTransactionError']; - } -} - -/** - * An error used when attempting to parse a value (like a connection string) - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - */ -class MongoParseError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoParseError'; - } -} - -/** - * An error signifying a timeout event - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - */ -class MongoTimeoutError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoTimeoutError'; - } -} - -/** - * An error thrown when the server reports a writeConcernError - * - * @param {Error|string|object} message The error message - * @param {object} result The result document (provided if ok: 1) - * @property {string} message The error message - * @property {object} [result] The result document (provided if ok: 1) - */ -class MongoWriteConcernError extends MongoError { - constructor(message, result) { - super(message); - this.name = 'MongoWriteConcernError'; - - if (result != null) { - this.result = result; - } - } -} - -// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms -const RETRYABLE_ERROR_CODES = new Set([ - 6, // HostUnreachable - 7, // HostNotFound - 89, // NetworkTimeout - 91, // ShutdownInProgress - 189, // PrimarySteppedDown - 9001, // SocketException - 10107, // NotMaster - 11600, // InterruptedAtShutdown - 11602, // InterruptedDueToReplStateChange - 13435, // NotMasterNoSlaveOk - 13436 // NotMasterOrSecondary -]); - -/** - * Determines whether an error is something the driver should attempt to retry - * - * @param {MongoError|Error} error - */ -function isRetryableError(error) { - return ( - RETRYABLE_ERROR_CODES.has(error.code) || - error instanceof MongoNetworkError || - error.message.match(/not master/) || - error.message.match(/node is recovering/) - ); -} - -module.exports = { - MongoError, - MongoNetworkError, - MongoParseError, - MongoTimeoutError, - MongoWriteConcernError, - mongoErrorContextSymbol, - isRetryableError -}; diff --git a/node_modules/mongodb-core/lib/sdam/cursor.js b/node_modules/mongodb-core/lib/sdam/cursor.js deleted file mode 100644 index f52d7b6176adbcc968554e7a98557cd8f388126f..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/sdam/cursor.js +++ /dev/null @@ -1,749 +0,0 @@ -'use strict'; - -const Logger = require('../connection/logger'); -const BSON = require('../connection/utils').retrieveBSON(); -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const mongoErrorContextSymbol = require('../error').mongoErrorContextSymbol; -const Long = BSON.Long; -const deprecate = require('util').deprecate; -const readPreferenceServerSelector = require('./server_selectors').readPreferenceServerSelector; -const ReadPreference = require('../topologies/read_preference'); - -/** - * Handle callback (including any exceptions thrown) - */ -function handleCallback(callback, err, result) { - try { - callback(err, result); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } -} - -/** - * This is a cursor results callback - * - * @callback resultCallback - * @param {error} error An error object. Set to null if no error present - * @param {object} document - */ - -/** - * An internal class that embodies a cursor on MongoDB, allowing for iteration over the - * results returned from a query. - * - * @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 - */ -class Cursor { - /** - * Create a cursor - * - * @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. - */ - constructor(bson, ns, cmd, options, topology, topologyOptions) { - options = options || {}; - - // Cursor pool - this.pool = 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.s = { - cursorId: null, - cmd: cmd, - 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 - }; - - if (typeof options.session === 'object') { - this.s.session = options.session; - } - - // Add promoteLong to cursor state - if (typeof topologyOptions.promoteLongs === 'boolean') { - this.s.promoteLongs = topologyOptions.promoteLongs; - } else if (typeof options.promoteLongs === 'boolean') { - this.s.promoteLongs = options.promoteLongs; - } - - // Add promoteValues to cursor state - if (typeof topologyOptions.promoteValues === 'boolean') { - this.s.promoteValues = topologyOptions.promoteValues; - } else if (typeof options.promoteValues === 'boolean') { - this.s.promoteValues = options.promoteValues; - } - - // Add promoteBuffers to cursor state - if (typeof topologyOptions.promoteBuffers === 'boolean') { - this.s.promoteBuffers = topologyOptions.promoteBuffers; - } else if (typeof options.promoteBuffers === 'boolean') { - this.s.promoteBuffers = options.promoteBuffers; - } - - if (topologyOptions.reconnect) { - this.s.reconnect = topologyOptions.reconnect; - } - - // Logger - this.logger = Logger('Cursor', topologyOptions); - - // - // Did we pass in a cursor id - if (typeof cmd === 'number') { - this.s.cursorId = Long.fromNumber(cmd); - this.s.lastCursorId = this.s.cursorId; - } else if (cmd instanceof Long) { - this.s.cursorId = cmd; - this.s.lastCursorId = cmd; - } - } - - setCursorBatchSize(value) { - this.s.batchSize = value; - } - - cursorBatchSize() { - return this.s.batchSize; - } - - setCursorLimit(value) { - this.s.limit = value; - } - - cursorLimit() { - return this.s.limit; - } - - setCursorSkip(value) { - this.s.skip = value; - } - - cursorSkip() { - return this.s.skip; - } - - _endSession(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - - const session = this.s.session; - if (session && (options.force || session.owner === this)) { - this.s.session = undefined; - session.endSession(callback); - return true; - } - - if (callback) { - callback(); - } - - return false; - } - - /** - * Clone the cursor - * @method - * @return {Cursor} - */ - clone() { - 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 - */ - isDead() { - return this.s.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 - */ - isKilled() { - return this.s.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 - */ - isNotified() { - return this.s.notified === true; - } - - /** - * Returns current buffered documents length - * @method - * @return {number} The number of items in the buffered documents - */ - bufferedCount() { - return this.s.documents.length - this.s.cursorIndex; - } - - /** - * Kill the cursor - * - * @param {resultCallback} callback A callback function - */ - kill(callback) { - // Set cursor to dead - this.s.dead = true; - this.s.killed = true; - // Remove documents - this.s.documents = []; - - // If no cursor id just return - if (this.s.cursorId == null || this.s.cursorId.isZero() || this.s.init === false) { - if (callback) callback(null, null); - return; - } - - // Default pool - const pool = this.s.server.s.pool; - - // Execute command - this.s.server.s.wireProtocolHandler.killCursor(this.bson, this.ns, this.s, pool, callback); - } - - /** - * Resets the cursor - */ - rewind() { - if (this.s.init) { - if (!this.s.dead) { - this.kill(); - } - - this.s.currentLimit = 0; - this.s.init = false; - this.s.dead = false; - this.s.killed = false; - this.s.notified = false; - this.s.documents = []; - this.s.cursorId = null; - this.s.cursorIndex = 0; - } - } - - /** - * Returns current buffered documents - * @method - * @return {Array} An array of buffered documents - */ - readBufferedDocuments(number) { - const unreadDocumentsLength = this.s.documents.length - this.s.cursorIndex; - const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; - let elements = this.s.documents.slice(this.s.cursorIndex, this.s.cursorIndex + length); - - // Transform the doc with passed in transformation method if provided - if (this.s.transforms && typeof this.s.transforms.doc === 'function') { - // Transform all the elements - for (let i = 0; i < elements.length; i++) { - elements[i] = this.s.transforms.doc(elements[i]); - } - } - - // Ensure we do not return any more documents than the limit imposed - // Just return the number of elements up to the limit - if (this.s.limit > 0 && this.s.currentLimit + elements.length > this.s.limit) { - elements = elements.slice(0, this.s.limit - this.s.currentLimit); - this.kill(); - } - - // Adjust current limit - this.s.currentLimit = this.s.currentLimit + elements.length; - this.s.cursorIndex = this.s.cursorIndex + elements.length; - - // Return elements - return elements; - } - - /** - * Retrieve the next document from the cursor - * - * @param {resultCallback} callback A callback function - */ - next(callback) { - nextFunction(this, callback); - } -} - -Cursor.prototype._find = deprecate( - callback => _find(this, callback), - '_find() is deprecated, please stop using it' -); - -Cursor.prototype._getmore = deprecate( - callback => _getmore(this, callback), - '_getmore() is deprecated, please stop using it' -); - -function _getmore(cursor, callback) { - if (cursor.logger.isDebug()) { - cursor.logger.debug(`schedule getMore call for query [${JSON.stringify(cursor.query)}]`); - } - - // Determine if it's a raw query - const raw = cursor.options.raw || cursor.cmd.raw; - - // Set the current batchSize - let batchSize = cursor.s.batchSize; - if (cursor.s.limit > 0 && cursor.s.currentLimit + batchSize > cursor.s.limit) { - batchSize = cursor.s.limit - cursor.s.currentLimit; - } - - // Default pool - const pool = cursor.s.server.s.pool; - - // We have a wire protocol handler - cursor.s.server.s.wireProtocolHandler.getMore( - cursor.bson, - cursor.ns, - cursor.s, - batchSize, - raw, - pool, - cursor.options, - callback - ); -} - -function _find(cursor, callback) { - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - const queryCallback = (err, r) => { - if (err) return callback(err); - - // Get the raw message - const result = r.message; - - // Query failure bit set - if (result.queryFailure) { - return callback(new MongoError(result.documents[0]), null); - } - - // Check if we have a command cursor - if ( - Array.isArray(result.documents) && - result.documents.length === 1 && - (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && - (result.documents[0].cursor !== 'string' || - result.documents[0]['$err'] || - result.documents[0]['errmsg'] || - Array.isArray(result.documents[0].result)) - ) { - // We have a an error document return the error - if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { - return callback(new MongoError(result.documents[0]), null); - } - - // We have a cursor document - if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { - const id = result.documents[0].cursor.id; - // If we have a namespace change set the new namespace for getmores - if (result.documents[0].cursor.ns) { - cursor.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - cursor.s.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; - cursor.s.lastCursorId = cursor.s.cursorId; - // If we have a firstBatch set it - if (Array.isArray(result.documents[0].cursor.firstBatch)) { - cursor.s.documents = result.documents[0].cursor.firstBatch; - } - - // Return after processing command cursor - return callback(null, result); - } - - if (Array.isArray(result.documents[0].result)) { - cursor.s.documents = result.documents[0].result; - cursor.s.cursorId = Long.ZERO; - return callback(null, result); - } - } - - // Otherwise fall back to regular find path - cursor.s.cursorId = result.cursorId; - cursor.s.documents = result.documents; - cursor.s.lastCursorId = result.cursorId; - - // Transform the results with passed in transformation method if provided - if (cursor.s.transforms && typeof cursor.s.transforms.query === 'function') { - cursor.s.documents = cursor.s.transforms.query(result); - } - - // Return callback - callback(null, result); - }; - - // Options passed to the pool - const queryOptions = {}; - - // If we have a raw query decorate the function - if (cursor.options.raw || cursor.cmd.raw) { - queryOptions.raw = cursor.options.raw || cursor.cmd.raw; - } - - // Do we have documentsReturnedIn set on the query - if (typeof cursor.query.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = cursor.query.documentsReturnedIn; - } - - // Add promote Long value if defined - if (typeof cursor.s.promoteLongs === 'boolean') { - queryOptions.promoteLongs = cursor.s.promoteLongs; - } - - // Add promote values if defined - if (typeof cursor.s.promoteValues === 'boolean') { - queryOptions.promoteValues = cursor.s.promoteValues; - } - - // Add promote values if defined - if (typeof cursor.s.promoteBuffers === 'boolean') { - queryOptions.promoteBuffers = cursor.s.promoteBuffers; - } - - if (typeof cursor.s.session === 'object') { - queryOptions.session = cursor.s.session; - } - - // Write the initial command out - cursor.s.server.s.pool.write(cursor.query, queryOptions, queryCallback); -} - -/** - * Validate if the pool is dead and return error - */ -function isConnectionDead(cursor, callback) { - if (cursor.pool && cursor.pool.isDestroyed()) { - cursor.s.killed = true; - const err = new MongoNetworkError( - `connection to host ${cursor.pool.host}:${cursor.pool.port} was destroyed` - ); - _setCursorNotifiedImpl(cursor, () => callback(err)); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead but was not explicitly killed by user - */ -function isCursorDeadButNotkilled(cursor, callback) { - // Cursor is dead but not marked killed, return null - if (cursor.s.dead && !cursor.s.killed) { - cursor.s.killed = true; - setCursorNotified(cursor, callback); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead and was killed by user - */ -function isCursorDeadAndKilled(cursor, callback) { - if (cursor.s.dead && cursor.s.killed) { - handleCallback(callback, new MongoError('cursor is dead')); - return true; - } - - return false; -} - -/** - * Validate if the cursor was killed by the user - */ -function isCursorKilled(cursor, callback) { - if (cursor.s.killed) { - setCursorNotified(cursor, callback); - return true; - } - - return false; -} - -/** - * Mark cursor as being dead and notified - */ -function setCursorDeadAndNotified(cursor, callback) { - cursor.s.dead = true; - setCursorNotified(cursor, callback); -} - -/** - * Mark cursor as being notified - */ -function setCursorNotified(cursor, callback) { - _setCursorNotifiedImpl(cursor, () => handleCallback(callback, null, null)); -} - -function _setCursorNotifiedImpl(cursor, callback) { - cursor.s.notified = true; - cursor.s.documents = []; - cursor.s.cursorIndex = 0; - if (cursor._endSession) { - return cursor._endSession(undefined, () => callback()); - } - return callback(); -} - -function initializeCursorAndRetryNext(cursor, callback) { - cursor.topology.selectServer( - readPreferenceServerSelector(cursor.options.readPreference || ReadPreference.primary), - (err, server) => { - if (err) { - callback(err, null); - return; - } - - cursor.s.server = server; - cursor.s.init = true; - - // check if server supports collation - // NOTE: this should be a part of the selection predicate! - if (cursor.cmd && cursor.cmd.collation && cursor.server.description.maxWireVersion < 5) { - callback(new MongoError(`server ${cursor.server.name} does not support collation`)); - return; - } - - try { - cursor.query = cursor.s.server.s.wireProtocolHandler.command( - cursor.bson, - cursor.ns, - cursor.cmd, - cursor.s, - cursor.topology, - cursor.options - ); - - nextFunction(cursor, callback); - } catch (err) { - callback(err); - return; - } - } - ); -} - -function nextFunction(cursor, callback) { - // We have notified about it - if (cursor.s.notified) { - return callback(new Error('cursor is exhausted')); - } - - // Cursor is killed return null - if (isCursorKilled(cursor, callback)) return; - - // Cursor is dead but not marked killed, return null - if (isCursorDeadButNotkilled(cursor, callback)) return; - - // We have a dead and killed cursor, attempting to call next should error - if (isCursorDeadAndKilled(cursor, callback)) return; - - // We have just started the cursor - if (!cursor.s.init) { - return initializeCursorAndRetryNext(cursor, callback); - } - - // If we don't have a cursorId execute the first query - if (cursor.s.cursorId == null) { - // Check if pool is dead and return if not possible to - // execute the query against the db - if (isConnectionDead(cursor, callback)) return; - - // query, cmd, options, s, callback - return _find(cursor, function(err) { - if (err) return handleCallback(callback, err, null); - - if (cursor.s.cursorId && cursor.s.cursorId.isZero() && cursor._endSession) { - cursor._endSession(); - } - - if ( - cursor.s.documents.length === 0 && - cursor.s.cursorId && - cursor.s.cursorId.isZero() && - !cursor.cmd.tailable && - !cursor.cmd.awaitData - ) { - return setCursorNotified(cursor, callback); - } - - nextFunction(cursor, callback); - }); - } - - if (cursor.s.documents.length === cursor.s.cursorIndex && Long.ZERO.equals(cursor.s.cursorId)) { - setCursorDeadAndNotified(cursor, callback); - return; - } - - if (cursor.s.limit > 0 && cursor.s.currentLimit >= cursor.s.limit) { - // Ensure we kill the cursor on the server - cursor.kill(); - // Set cursor in dead and notified state - setCursorDeadAndNotified(cursor, callback); - return; - } - - if ( - cursor.s.documents.length === cursor.s.cursorIndex && - cursor.cmd.tailable && - Long.ZERO.equals(cursor.s.cursorId) - ) { - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: cursor.cmd.tailable, - awaitData: cursor.cmd.awaitData - }) - ); - } - - if (cursor.s.cursorIndex === cursor.s.documents.length && !Long.ZERO.equals(cursor.s.cursorId)) { - // Ensure an empty cursor state - cursor.s.documents = []; - cursor.s.cursorIndex = 0; - - // Check if connection is dead and return if not possible to - if (isConnectionDead(cursor, callback)) return; - - // Execute the next get more - return _getmore(cursor, function(err, doc, connection) { - if (err) { - if (err instanceof MongoError) { - err[mongoErrorContextSymbol].isGetMore = true; - } - - return handleCallback(callback, err); - } - - if (cursor.s.cursorId && cursor.s.cursorId.isZero() && cursor._endSession) { - cursor._endSession(); - } - - // Save the returned connection to ensure all getMore's fire over the same connection - cursor.connection = connection; - - // 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 ( - cursor.s.documents.length === 0 && - cursor.cmd.tailable && - Long.ZERO.equals(cursor.s.cursorId) - ) { - // No more documents in the tailed cursor - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: cursor.cmd.tailable, - awaitData: cursor.cmd.awaitData - }) - ); - } else if ( - cursor.s.documents.length === 0 && - cursor.cmd.tailable && - !Long.ZERO.equals(cursor.s.cursorId) - ) { - return nextFunction(cursor, callback); - } - - if (cursor.s.limit > 0 && cursor.s.currentLimit >= cursor.s.limit) { - return setCursorDeadAndNotified(cursor, callback); - } - - nextFunction(cursor, callback); - }); - } - - if (cursor.s.limit > 0 && cursor.s.currentLimit >= cursor.s.limit) { - // Ensure we kill the cursor on the server - cursor.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(cursor, callback); - } - - // Increment the current cursor limit - cursor.s.currentLimit += 1; - - // Get the document - let doc = cursor.s.documents[cursor.s.cursorIndex++]; - - // Doc overflow - if (!doc || doc.$err) { - // Ensure we kill the cursor on the server - cursor.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(cursor, function() { - handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); - }); - } - - // Transform the doc with passed in transformation method if provided - if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { - doc = cursor.s.transforms.doc(doc); - } - - // Return the document - handleCallback(callback, null, doc); -} - -module.exports = Cursor; diff --git a/node_modules/mongodb-core/lib/sdam/monitoring.js b/node_modules/mongodb-core/lib/sdam/monitoring.js deleted file mode 100644 index dbd6b9f4ce6c26e5926d4b3285b9ea3952124e71..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/sdam/monitoring.js +++ /dev/null @@ -1,217 +0,0 @@ -'use strict'; - -const ServerDescription = require('./server_description').ServerDescription; -const calculateDurationInMs = require('../utils').calculateDurationInMs; - -/** - * Published when server description changes, but does NOT include changes to the RTT. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {ServerDescription} previousDescription The previous server description - * @property {ServerDescription} newDescription The new server description - */ -class ServerDescriptionChangedEvent { - constructor(topologyId, address, previousDescription, newDescription) { - Object.assign(this, { topologyId, address, previousDescription, newDescription }); - } -} - -/** - * Published when server is initialized. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - */ -class ServerOpeningEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when server is closed. - * - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {Object} topologyId A unique identifier for the topology - */ -class ServerClosedEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when topology description changes. - * - * @property {Object} topologyId - * @property {TopologyDescription} previousDescription The old topology description - * @property {TopologyDescription} newDescription The new topology description - */ -class TopologyDescriptionChangedEvent { - constructor(topologyId, previousDescription, newDescription) { - Object.assign(this, { topologyId, previousDescription, newDescription }); - } -} - -/** - * Published when topology is initialized. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyOpeningEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Published when topology is closed. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyClosedEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Fired when the server monitor’s ismaster command is started - immediately before - * the ismaster command is serialized into raw BSON and written to the socket. - * - * @property {Object} connectionId The connection id for the command - */ -class ServerHeartbeatStartedEvent { - constructor(connectionId) { - Object.assign(this, { connectionId }); - } -} - -/** - * Fired when the server monitor’s ismaster succeeds. - * - * @param {Number} duration The execution time of the event in ms - * @param {Object} reply The command reply - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatSucceededEvent { - constructor(duration, reply, connectionId) { - Object.assign(this, { duration, reply, connectionId }); - } -} - -/** - * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. - * - * @param {Number} duration The execution time of the event in ms - * @param {MongoError|Object} failure The command failure - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatFailedEvent { - constructor(duration, failure, connectionId) { - Object.assign(this, { duration, failure, connectionId }); - } -} - -/** - * Performs a server check as described by the SDAM spec. - * - * NOTE: This method automatically reschedules itself, so that there is always an active - * monitoring process - * - * @param {Server} server The server to monitor - */ -function monitorServer(server) { - // executes a single check of a server - const checkServer = callback => { - let start = process.hrtime(); - - // emit a signal indicating we have started the heartbeat - server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name)); - - server.command( - 'admin.$cmd', - { ismaster: true }, - { - monitoring: true, - socketTimeout: server.s.options.connectionTimeout || 2000 - }, - function(err, result) { - let duration = calculateDurationInMs(start); - - if (err) { - server.emit( - 'serverHeartbeatFailed', - new ServerHeartbeatFailedEvent(duration, err, server.name) - ); - - return callback(err, null); - } - - const isMaster = result.result; - server.emit( - 'serverHeartbeatSucceded', - new ServerHeartbeatSucceededEvent(duration, isMaster, server.name) - ); - - return callback(null, isMaster); - } - ); - }; - - const successHandler = isMaster => { - server.s.monitoring = false; - - // emit an event indicating that our description has changed - server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster)); - - // schedule the next monitoring process - server.s.monitorId = setTimeout( - () => monitorServer(server), - server.s.options.heartbeatFrequencyMS - ); - }; - - // run the actual monitoring loop - server.s.monitoring = true; - checkServer((err, isMaster) => { - if (!err) { - successHandler(isMaster); - return; - } - - // According to the SDAM specification's "Network error during server check" section, if - // an ismaster call fails we reset the server's pool. If a server was once connected, - // change its type to `Unknown` only after retrying once. - - // TODO: we need to reset the pool here - - return checkServer((err, isMaster) => { - if (err) { - server.s.monitoring = false; - - // revert to `Unknown` by emitting a default description with no isMaster - server.emit('descriptionReceived', new ServerDescription(server.description.address)); - - // do not reschedule monitoring in this case - return; - } - - successHandler(isMaster); - }); - }); -} - -module.exports = { - ServerDescriptionChangedEvent, - ServerOpeningEvent, - ServerClosedEvent, - TopologyDescriptionChangedEvent, - TopologyOpeningEvent, - TopologyClosedEvent, - ServerHeartbeatStartedEvent, - ServerHeartbeatSucceededEvent, - ServerHeartbeatFailedEvent, - monitorServer -}; diff --git a/node_modules/mongodb-core/lib/sdam/server.js b/node_modules/mongodb-core/lib/sdam/server.js deleted file mode 100644 index 57b28ed38cb07029e530a9634b4548e54b3594ec..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/sdam/server.js +++ /dev/null @@ -1,411 +0,0 @@ -'use strict'; -const EventEmitter = require('events'); -const MongoError = require('../error').MongoError; -const Pool = require('../connection/pool'); -const relayEvents = require('../utils').relayEvents; -const calculateDurationInMs = require('../utils').calculateDurationInMs; -const Query = require('../connection/commands').Query; -const TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support'); -const ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support'); -const BSON = require('../connection/utils').retrieveBSON(); -const createClientInfo = require('../topologies/shared').createClientInfo; -const Logger = require('../connection/logger'); -const ServerDescription = require('./server_description').ServerDescription; -const ReadPreference = require('../topologies/read_preference'); -const monitorServer = require('./monitoring').monitorServer; - -/** - * - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - */ -class Server extends EventEmitter { - /** - * Create a server - * - * @param {ServerDescription} description - * @param {Object} options - */ - constructor(description, options) { - super(); - - this.s = { - // the server description - description, - // a saved copy of the incoming options - options, - // the server logger - logger: Logger('Server', options), - // the bson parser - bson: options.bson || new BSON(), - // client metadata for the initial handshake - clientInfo: createClientInfo(options), - // state variable to determine if there is an active server check in progress - monitoring: false, - // the connection pool - pool: null - }; - } - - get description() { - return this.s.description; - } - - get name() { - return this.s.description.address; - } - - /** - * Initiate server connect - * - * @param {Array} [options.auth] Array of auth options to apply on connect - */ - connect(options) { - options = options || {}; - - // do not allow connect to be called on anything that's not disconnected - if (this.s.pool && !this.s.pool.isDisconnected() && !this.s.pool.isDestroyed()) { - throw new MongoError(`Server instance in invalid state ${this.s.pool.state}`); - } - - // create a pool - this.s.pool = new Pool(this, Object.assign(this.s.options, options, { bson: this.s.bson })); - - // Set up listeners - this.s.pool.on('connect', connectEventHandler(this)); - this.s.pool.on('close', closeEventHandler(this)); - - // this.s.pool.on('error', errorEventHandler(this)); - // this.s.pool.on('timeout', timeoutEventHandler(this)); - // this.s.pool.on('parseError', errorEventHandler(this)); - // this.s.pool.on('reconnect', reconnectEventHandler(this)); - // this.s.pool.on('reconnectFailed', errorEventHandler(this)); - - // relay all command monitoring events - relayEvents(this.s.pool, this, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // If auth settings have been provided, use them - if (options.auth) { - this.s.pool.connect.apply(this.s.pool, options.auth); - return; - } - - this.s.pool.connect(); - } - - /** - * Destroy the server connection - * - * @param {Boolean} [options.emitClose=false] Emit close event on destroy - * @param {Boolean} [options.emitDestroy=false] Emit destroy event on destroy - * @param {Boolean} [options.force=false] Force destroy the pool - */ - destroy(callback) { - if (typeof callback === 'function') { - callback(null, null); - } - } - - /** - * Immediately schedule monitoring of this server. If there already an attempt being made - * this will be a no-op. - */ - monitor() { - if (this.s.monitoring) return; - if (this.s.monitorId) clearTimeout(this.s.monitorId); - monitorServer(this); - } - - /** - * Execute a command - * - * @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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - const error = basicReadValidations(this, options); - if (error) { - return callback(error, null); - } - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (this.s.logger.isDebug()) { - this.s.logger.debug( - `executing command [${JSON.stringify({ ns, cmd, options })}] against ${this.name}` - ); - } - - // Check if we have collation support - if (this.description.maxWireVersion < 5 && cmd.collation) { - callback(new MongoError(`server ${this.name} does not support collation`)); - return; - } - - // Create the query object - const query = this.s.wireProtocolHandler.command(this, ns, cmd, {}, options); - // Set slave OK of the query - query.slaveOk = options.readPreference ? options.readPreference.slaveOk() : false; - - // write options - const writeOptions = { - raw: typeof options.raw === 'boolean' ? options.raw : false, - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - command: true, - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, - fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false, - requestId: query.requestId, - socketTimeout: typeof options.socketTimeout === 'number' ? options.socketTimeout : null, - session: options.session || null - }; - - // write the operation to the pool - this.s.pool.write(query, writeOptions, 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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: '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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: '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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); - } -} - -function basicWriteValidations(server) { - if (!server.s.pool) { - return new MongoError('server instance is not connected'); - } - - if (server.s.pool.isDestroyed()) { - return new MongoError('server instance pool was destroyed'); - } - - return null; -} - -function basicReadValidations(server, options) { - const error = basicWriteValidations(server, options); - if (error) { - return error; - } - - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - return new MongoError('readPreference must be an instance of ReadPreference'); - } -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const server = args.server; - const op = args.op; - const ns = args.ns; - const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; - - const error = basicWriteValidations(server, options); - if (error) { - callback(error, null); - return; - } - - // Check if we have collation support - if (server.description.maxWireVersion < 5 && options.collation) { - callback(new MongoError(`server ${this.name} does not support collation`)); - return; - } - - // Execute write - return server.s.wireProtocolHandler[op](server.s.pool, ns, server.s.bson, ops, options, callback); -} - -function saslSupportedMechs(options) { - if (!options) { - return {}; - } - - const authArray = options.auth || []; - const authMechanism = authArray[0] || options.authMechanism; - const authSource = authArray[1] || options.authSource || options.dbName || 'admin'; - const user = authArray[2] || options.user; - - if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { - return {}; - } - - if (!user) { - return {}; - } - - return { saslSupportedMechs: `${authSource}.${user}` }; -} - -function extractIsMasterError(err, result) { - if (err) return err; - if (result && result.result && result.result.ok === 0) { - return new MongoError(result.result); - } -} - -function executeServerHandshake(server, callback) { - // construct an `ismaster` query - const compressors = - server.s.options.compression && server.s.options.compression.compressors - ? server.s.options.compression.compressors - : []; - - const queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; - const query = new Query( - server.s.bson, - 'admin.$cmd', - Object.assign( - { ismaster: true, client: server.s.clientInfo, compression: compressors }, - saslSupportedMechs(server.s.options) - ), - queryOptions - ); - - // execute the query - server.s.pool.write( - query, - { socketTimeout: server.s.options.connectionTimeout || 2000 }, - callback - ); -} - -function configureWireProtocolHandler(ismaster) { - // 3.2 wire protocol handler - if (ismaster.maxWireVersion >= 4) { - return new ThreeTwoWireProtocolSupport(); - } - - // default to 2.6 wire protocol handler - return new TwoSixWireProtocolSupport(); -} - -function connectEventHandler(server) { - return function() { - // log information of received information if in info mode - // if (server.s.logger.isInfo()) { - // var object = err instanceof MongoError ? JSON.stringify(err) : {}; - // server.s.logger.info(`server ${server.name} fired event ${event} out with message ${object}`); - // } - - // begin initial server handshake - const start = process.hrtime(); - executeServerHandshake(server, (err, response) => { - // Set initial lastIsMasterMS - is this needed? - server.s.lastIsMasterMS = calculateDurationInMs(start); - - const serverError = extractIsMasterError(err, response); - if (serverError) { - server.emit('error', serverError); - return; - } - - // extract the ismaster from the server response - const isMaster = response.result; - - // compression negotation - if (isMaster && isMaster.compression) { - const localCompressionInfo = server.s.options.compression; - const localCompressors = localCompressionInfo.compressors; - for (var i = 0; i < localCompressors.length; i++) { - if (isMaster.compression.indexOf(localCompressors[i]) > -1) { - server.s.pool.options.agreedCompressor = localCompressors[i]; - break; - } - } - - if (localCompressionInfo.zlibCompressionLevel) { - server.s.pool.options.zlibCompressionLevel = localCompressionInfo.zlibCompressionLevel; - } - } - - // configure the wire protocol handler - server.s.wireProtocolHandler = configureWireProtocolHandler(isMaster); - - // log the connection event if requested - if (server.s.logger.isInfo()) { - server.s.logger.info( - `server ${server.name} connected with ismaster [${JSON.stringify(isMaster)}]` - ); - } - - // emit an event indicating that our description has changed - server.emit( - 'descriptionReceived', - new ServerDescription(server.description.address, isMaster) - ); - - // emit a connect event - server.emit('connect', isMaster); - }); - }; -} - -function closeEventHandler(server) { - return function() { - server.emit('close'); - }; -} - -module.exports = Server; diff --git a/node_modules/mongodb-core/lib/sdam/server_description.js b/node_modules/mongodb-core/lib/sdam/server_description.js deleted file mode 100644 index 558b8cf2da1489d0ebfdb7d44d35338d8b411ef7..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/sdam/server_description.js +++ /dev/null @@ -1,141 +0,0 @@ -'use strict'; - -// An enumeration of server types we know about -const ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -const WRITABLE_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.Standalone, - ServerType.Mongos -]); - -const ISMASTER_FIELDS = [ - 'minWireVersion', - 'maxWireVersion', - 'me', - 'hosts', - 'passives', - 'arbiters', - 'tags', - 'setName', - 'setVersion', - 'electionId', - 'primary', - 'logicalSessionTimeoutMinutes' -]; - -/** - * The client's view of a single server, based on the most recent ismaster outcome. - * - * Internal type, not meant to be directly instantiated - */ -class ServerDescription { - /** - * Create a ServerDescription - * @param {String} address The address of the server - * @param {Object} [ismaster] An optional ismaster response for this server - * @param {Object} [options] Optional settings - * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) - */ - constructor(address, ismaster, options) { - options = options || {}; - ismaster = Object.assign( - { - minWireVersion: 0, - maxWireVersion: 0, - hosts: [], - passives: [], - arbiters: [], - tags: [] - }, - ismaster - ); - - this.address = address; - this.error = null; - this.roundTripTime = options.roundTripTime || 0; - this.lastUpdateTime = Date.now(); - this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; - this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; - this.type = parseServerType(ismaster); - - // direct mappings - ISMASTER_FIELDS.forEach(field => { - if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; - }); - - // normalize case for hosts - this.hosts = this.hosts.map(host => host.toLowerCase()); - this.passives = this.passives.map(host => host.toLowerCase()); - this.arbiters = this.arbiters.map(host => host.toLowerCase()); - } - - get allHosts() { - return this.hosts.concat(this.arbiters).concat(this.passives); - } - - /** - * @return {Boolean} Is this server available for reads - */ - get isReadable() { - return this.type === ServerType.RSSecondary || this.isWritable; - } - - /** - * @return {Boolean} Is this server available for writes - */ - get isWritable() { - return WRITABLE_SERVER_TYPES.has(this.type); - } -} - -/** - * Parses an `ismaster` message and determines the server type - * - * @param {Object} ismaster The `ismaster` message to parse - * @return {ServerType} - */ -function parseServerType(ismaster) { - if (!ismaster || !ismaster.ok) { - return ServerType.Unknown; - } - - if (ismaster.isreplicaset) { - return ServerType.RSGhost; - } - - if (ismaster.msg && ismaster.msg === 'isdbgrid') { - return ServerType.Mongos; - } - - if (ismaster.setName) { - if (ismaster.hidden) { - return ServerType.RSOther; - } else if (ismaster.ismaster) { - return ServerType.RSPrimary; - } else if (ismaster.secondary) { - return ServerType.RSSecondary; - } else if (ismaster.arbiterOnly) { - return ServerType.RSArbiter; - } else { - return ServerType.RSOther; - } - } - - return ServerType.Standalone; -} - -module.exports = { - ServerDescription, - ServerType -}; diff --git a/node_modules/mongodb-core/lib/sdam/server_selectors.js b/node_modules/mongodb-core/lib/sdam/server_selectors.js deleted file mode 100644 index d082170f17ccd0ae913ed4d96b81e34d3cc16ad3..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/sdam/server_selectors.js +++ /dev/null @@ -1,206 +0,0 @@ -'use strict'; -const ServerType = require('./server_description').ServerType; -const TopologyType = require('./topology_description').TopologyType; -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; - -// max staleness constants -const IDLE_WRITE_PERIOD = 10000; -const SMALLEST_MAX_STALENESS_SECONDS = 90; - -function writableServerSelector() { - return function(topologyDescription, servers) { - return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable)); - }; -} - -// reducers -function maxStalenessReducer(readPreference, topologyDescription, servers) { - if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { - return servers; - } - - const maxStaleness = readPreference.maxStalenessSeconds; - const maxStalenessVariance = - (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; - if (maxStaleness < maxStalenessVariance) { - throw MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); - } - - if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { - throw new MongoError( - `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` - ); - } - - if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { - const primary = servers.filter(primaryFilter)[0]; - return servers.reduce((result, server) => { - const stalenessMS = - server.lastUpdateTime - - server.lastWriteDate - - (primary.lastUpdateTime - primary.lastWriteDate) + - topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } else if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { - const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); - return servers.reduce((result, server) => { - const stalenessMS = - sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } - - return servers; -} - -function tagSetMatch(tagSet, serverTags) { - const keys = Object.keys(tagSet); - const serverTagKeys = Object.keys(serverTags); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { - return false; - } - } - - return true; -} - -function tagSetReducer(readPreference, servers) { - if ( - readPreference.tags == null || - (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) - ) { - return servers; - } - - for (let i = 0; i < readPreference.tags.length; ++i) { - const tagSet = readPreference.tags[i]; - const serversMatchingTagset = servers.reduce((matched, server) => { - if (tagSetMatch(tagSet, server.tags)) matched.push(server); - return matched; - }, []); - - if (serversMatchingTagset.length) { - return serversMatchingTagset; - } - } - - return []; -} - -function latencyWindowReducer(topologyDescription, servers) { - const low = servers.reduce( - (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), - -1 - ); - - const high = low + topologyDescription.localThresholdMS; - - return servers.reduce((result, server) => { - if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); - return result; - }, []); -} - -// filters -function primaryFilter(server) { - return server.type === ServerType.RSPrimary; -} - -function secondaryFilter(server) { - return server.type === ServerType.RSSecondary; -} - -function nearestFilter(server) { - return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; -} - -function knownFilter(server) { - return server.type !== ServerType.Unknown; -} - -function readPreferenceServerSelector(readPreference) { - if (!readPreference.isValid()) { - throw new TypeError('Invalid read preference specified'); - } - - return function(topologyDescription, servers) { - const commonWireVersion = topologyDescription.commonWireVersion; - if ( - commonWireVersion && - (readPreference.minWireVersion && readPreference.minWireVersion > commonWireVersion) - ) { - throw new MongoError( - `Minimum wire version '${ - readPreference.minWireVersion - }' required, but found '${commonWireVersion}'` - ); - } - - if ( - topologyDescription.type === TopologyType.Single || - topologyDescription.type === TopologyType.Sharded - ) { - return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); - } - - if (readPreference.mode === ReadPreference.PRIMARY) { - return servers.filter(primaryFilter); - } - - if (readPreference.mode === ReadPreference.SECONDARY) { - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - } else if (readPreference.mode === ReadPreference.NEAREST) { - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(nearestFilter); - } else if (readPreference.mode === ReadPreference.SECONDARY_PREFERRED) { - const result = latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - - return result.length === 0 ? servers.filter(primaryFilter) : result; - } else if (readPreference.mode === ReadPreference.PRIMARY_PREFERRED) { - const result = servers.filter(primaryFilter); - if (result.length) { - return result; - } - - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - } - }; -} - -module.exports = { - writableServerSelector, - readPreferenceServerSelector -}; diff --git a/node_modules/mongodb-core/lib/sdam/topology.js b/node_modules/mongodb-core/lib/sdam/topology.js deleted file mode 100644 index bb43925e5d563ed51301cf4901a8cde987a7609d..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/sdam/topology.js +++ /dev/null @@ -1,666 +0,0 @@ -'use strict'; -const EventEmitter = require('events'); -const ServerDescription = require('./server_description').ServerDescription; -const TopologyDescription = require('./topology_description').TopologyDescription; -const TopologyType = require('./topology_description').TopologyType; -const monitoring = require('./monitoring'); -const calculateDurationInMs = require('../utils').calculateDurationInMs; -const MongoTimeoutError = require('../error').MongoTimeoutError; -const MongoNetworkError = require('../error').MongoNetworkError; -const Server = require('./server'); -const relayEvents = require('../utils').relayEvents; -const ReadPreference = require('../topologies/read_preference'); -const readPreferenceServerSelector = require('./server_selectors').readPreferenceServerSelector; -const writableServerSelector = require('./server_selectors').writableServerSelector; -const isRetryableWritesSupported = require('../topologies/shared').isRetryableWritesSupported; -const Cursor = require('./cursor'); -const deprecate = require('util').deprecate; -const BSON = require('../connection/utils').retrieveBSON(); -const createCompressionInfo = require('../topologies/shared').createCompressionInfo; - -// Global state -let globalTopologyCounter = 0; - -// Constants -const TOPOLOGY_DEFAULTS = { - localThresholdMS: 15, - serverSelectionTimeoutMS: 10000, - heartbeatFrequencyMS: 30000, - minHeartbeatIntervalMS: 500 -}; - -/** - * A container of server instances representing a connection to a MongoDB topology. - * - * @fires Topology#serverOpening - * @fires Topology#serverClosed - * @fires Topology#serverDescriptionChanged - * @fires Topology#topologyOpening - * @fires Topology#topologyClosed - * @fires Topology#topologyDescriptionChanged - * @fires Topology#serverHeartbeatStarted - * @fires Topology#serverHeartbeatSucceeded - * @fires Topology#serverHeartbeatFailed - */ -class Topology extends EventEmitter { - /** - * Create a topology - * - * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to - * @param {Object} [options] Optional settings - * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers - * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error - * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled - */ - constructor(seedlist, options) { - super(); - if (typeof options === 'undefined') { - options = seedlist; - seedlist = []; - - // this is for legacy single server constructor support - if (options.host) { - seedlist.push({ host: options.host, port: options.port }); - } - } - - seedlist = seedlist || []; - options = Object.assign({}, TOPOLOGY_DEFAULTS, options); - - const topologyType = topologyTypeFromSeedlist(seedlist, options); - const topologyId = globalTopologyCounter++; - const serverDescriptions = seedlist.reduce((result, seed) => { - const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; - result.set(address, new ServerDescription(address)); - return result; - }, new Map()); - - this.s = { - // the id of this topology - id: topologyId, - // passed in options - options: Object.assign({}, options), - // initial seedlist of servers to connect to - seedlist: seedlist, - // the topology description - description: new TopologyDescription( - topologyType, - serverDescriptions, - options.replicaSet, - null, - null, - options - ), - serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, - heartbeatFrequencyMS: options.heartbeatFrequencyMS, - minHeartbeatIntervalMS: options.minHeartbeatIntervalMS, - // allow users to override the cursor factory - Cursor: options.cursorFactory || Cursor, - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]) - }; - - // amend options for server instance creation - this.s.options.compression = { compressors: createCompressionInfo(options) }; - } - - /** - * @return A `TopologyDescription` for this topology - */ - get description() { - return this.s.description; - } - - /** - * All raw connections - * @method - * @return {Connection[]} - */ - connections() { - return Array.from(this.s.servers.values()).reduce((result, server) => { - return result.concat(server.s.pool.allConnections()); - }, []); - } - - /** - * Initiate server connect - * - * @param {Object} [options] Optional settings - * @param {Array} [options.auth=null] Array of auth options to apply on connect - */ - connect(/* options */) { - // emit SDAM monitoring events - this.emit('topologyOpening', new monitoring.TopologyOpeningEvent(this.s.id)); - - // emit an event for the topology change - this.emit( - 'topologyDescriptionChanged', - new monitoring.TopologyDescriptionChangedEvent( - this.s.id, - new TopologyDescription(TopologyType.Unknown), // initial is always Unknown - this.s.description - ) - ); - - connectServers(this, Array.from(this.s.description.servers.values())); - this.s.connected = true; - } - - /** - * Close this topology - */ - close(callback) { - // destroy all child servers - this.s.servers.forEach(server => server.destroy()); - - // emit an event for close - this.emit('topologyClosed', new monitoring.TopologyClosedEvent(this.s.id)); - - this.s.connected = false; - - if (typeof callback === 'function') { - callback(null, null); - } - } - - /** - * Selects a server according to the selection predicate provided - * - * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window - * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided - */ - selectServer(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign( - {}, - { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, - options - ); - - selectServers( - this, - selector, - options.serverSelectionTimeoutMS, - process.hrtime(), - (err, servers) => { - if (err) return callback(err, null); - callback(null, randomSelection(servers)); - } - ); - } - - /** - * Update the internal TopologyDescription with a ServerDescription - * - * @param {object} serverDescription The server to update in the internal list of server descriptions - */ - serverUpdateHandler(serverDescription) { - if (!this.s.description.hasServer(serverDescription.address)) { - return; - } - - // these will be used for monitoring events later - const previousTopologyDescription = this.s.description; - const previousServerDescription = this.s.description.servers.get(serverDescription.address); - - // first update the TopologyDescription - this.s.description = this.s.description.update(serverDescription); - - // emit monitoring events for this change - this.emit( - 'serverDescriptionChanged', - new monitoring.ServerDescriptionChangedEvent( - this.s.id, - serverDescription.address, - previousServerDescription, - this.s.description.servers.get(serverDescription.address) - ) - ); - - // update server list from updated descriptions - updateServers(this, serverDescription); - - this.emit( - 'topologyDescriptionChanged', - new monitoring.TopologyDescriptionChangedEvent( - this.s.id, - previousTopologyDescription, - this.s.description - ) - ); - } - - /** - * Authenticate using a specified mechanism - * - * @param {String} mechanism The auth mechanism used for authentication - * @param {String} db The db we are authenticating against - * @param {Object} options Optional settings for the authenticating mechanism - * @param {authResultCallback} callback A callback function - */ - auth(mechanism, db, options, callback) { - callback(null, null); - } - - /** - * Logout from a database - * - * @param {String} db The db we are logging out from - * @param {authResultCallback} callback A callback function - */ - logout(db, callback) { - callback(null, null); - } - - // Basic operation support. Eventually this should be moved into command construction - // during the command refactor. - - /** - * Insert one or more documents - * - * @param {String} ns The full qualified namespace for this operation - * @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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * - * @param {string} ns The fully qualified namespace for this operation - * @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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * - * @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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: '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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - const readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; - this.selectServer(readPreferenceServerSelector(readPreference), (err, server) => { - if (err) { - callback(err, null); - return; - } - - server.command(ns, cmd, options, callback); - }); - } - - /** - * Create a new cursor - * - * @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] Options for the cursor - * @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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ - cursor(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - const CursorClass = options.cursorFactory || this.s.Cursor; - - return new CursorClass(this.s.bson, ns, cmd, options, topology, this.s.options); - } -} - -// legacy aliases -Topology.prototype.destroy = deprecate( - Topology.prototype.close, - 'destroy() is deprecated, please use close() instead' -); - -function topologyTypeFromSeedlist(seedlist, options) { - if (seedlist.length === 1 && !options.replicaSet) return TopologyType.Single; - if (options.replicaSet) return TopologyType.ReplicaSetNoPrimary; - return TopologyType.Unknown; -} - -function randomSelection(array) { - return array[Math.floor(Math.random() * array.length)]; -} - -/** - * Selects servers using the provided selector - * - * @private - * @param {Topology} topology The topology to select servers from - * @param {function} selector The actual predicate used for selecting servers - * @param {Number} timeout The max time we are willing wait for selection - * @param {Number} start A high precision timestamp for the start of the selection process - * @param {function} callback The callback used to convey errors or the resultant servers - */ -function selectServers(topology, selector, timeout, start, callback) { - const serverDescriptions = Array.from(topology.description.servers.values()); - let descriptions; - - try { - descriptions = selector - ? selector(topology.description, serverDescriptions) - : serverDescriptions; - } catch (e) { - return callback(e, null); - } - - if (descriptions.length) { - const servers = descriptions.map(description => topology.s.servers.get(description.address)); - return callback(null, servers); - } - - const duration = calculateDurationInMs(start); - if (duration >= timeout) { - return callback(new MongoTimeoutError(`Server selection timed out after ${timeout} ms`)); - } - - const retrySelection = () => { - // ensure all server monitors attempt monitoring immediately - topology.s.servers.forEach(server => server.monitor()); - - const iterationTimer = setTimeout(() => { - callback(new MongoTimeoutError('Server selection timed out due to monitoring')); - }, topology.s.minHeartbeatIntervalMS); - - topology.once('topologyDescriptionChanged', () => { - // successful iteration, clear the check timer - clearTimeout(iterationTimer); - - // topology description has changed due to monitoring, reattempt server selection - selectServers(topology, selector, timeout, start, callback); - }); - }; - - // ensure we are connected - if (!topology.s.connected) { - topology.connect(); - - // we want to make sure we're still within the requested timeout window - const failToConnectTimer = setTimeout(() => { - callback(new MongoTimeoutError('Server selection timed out waiting to connect')); - }, timeout - duration); - - topology.once('connect', () => { - clearTimeout(failToConnectTimer); - retrySelection(); - }); - - return; - } - - retrySelection(); -} - -/** - * Create `Server` instances for all initially known servers, connect them, and assign - * them to the passed in `Topology`. - * - * @param {Topology} topology The topology responsible for the servers - * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect - */ -function connectServers(topology, serverDescriptions) { - topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { - // publish an open event for each ServerDescription created - topology.emit( - 'serverOpening', - new monitoring.ServerOpeningEvent(topology.s.id, serverDescription.address) - ); - - const server = new Server(serverDescription, topology.s.options); - relayEvents(server, topology, [ - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed' - ]); - - server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); - server.on('connect', serverConnectEventHandler(server, topology)); - servers.set(serverDescription.address, server); - server.connect(); - return servers; - }, new Map()); -} - -function updateServers(topology, currentServerDescription) { - // update the internal server's description - if (topology.s.servers.has(currentServerDescription.address)) { - const server = topology.s.servers.get(currentServerDescription.address); - server.s.description = currentServerDescription; - } - - // add new servers for all descriptions we currently don't know about locally - for (const serverDescription of topology.description.servers.values()) { - if (!topology.s.servers.has(serverDescription.address)) { - topology.emit( - 'serverOpening', - new monitoring.ServerOpeningEvent(topology.s.id, serverDescription.address) - ); - - const server = new Server(serverDescription, topology.s.options); - relayEvents(server, topology, [ - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed' - ]); - - server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); - server.on('connect', serverConnectEventHandler(server, topology)); - topology.s.servers.set(serverDescription.address, server); - server.connect(); - } - } - - // for all servers no longer known, remove their descriptions and destroy their instances - for (const entry of topology.s.servers) { - const serverAddress = entry[0]; - if (topology.description.hasServer(serverAddress)) { - continue; - } - - const server = topology.s.servers.get(serverAddress); - topology.s.servers.delete(serverAddress); - - server.destroy(() => - topology.emit('serverClosed', new monitoring.ServerClosedEvent(topology.s.id, serverAddress)) - ); - } -} - -function serverConnectEventHandler(server, topology) { - return function(/* ismaster */) { - topology.emit('connect', topology); - }; -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const topology = args.topology; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - const willRetryWrite = - !args.retrying && - options.retryWrites && - options.session && - isRetryableWritesSupported(topology) && - !options.session.inTransaction(); - - topology.selectServer(writableServerSelector(), (err, server) => { - if (err) { - callback(err, null); - return; - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!(err instanceof MongoNetworkError) && !err.message.match(/not master/)) { - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // execute the write operation - server[op](ns, ops, options, handler); - - // we need to increment the statement id if we're in a transaction - if (options.session && options.session.inTransaction()) { - options.session.incrementStatementId(ops.length); - } - }); -} - -/** - * A server opening SDAM monitoring event - * - * @event Topology#serverOpening - * @type {ServerOpeningEvent} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Topology#serverClosed - * @type {ServerClosedEvent} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Topology#serverDescriptionChanged - * @type {ServerDescriptionChangedEvent} - */ - -/** - * A topology open SDAM event - * - * @event Topology#topologyOpening - * @type {TopologyOpeningEvent} - */ - -/** - * A topology closed SDAM event - * - * @event Topology#topologyClosed - * @type {TopologyClosedEvent} - */ - -/** - * A topology structure SDAM change event - * - * @event Topology#topologyDescriptionChanged - * @type {TopologyDescriptionChangedEvent} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Topology#serverHeartbeatStarted - * @type {ServerHeartbeatStartedEvent} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Topology#serverHeartbeatFailed - * @type {ServerHearbeatFailedEvent} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Topology#serverHeartbeatSucceeded - * @type {ServerHeartbeatSucceededEvent} - */ - -module.exports = Topology; diff --git a/node_modules/mongodb-core/lib/sdam/topology_description.js b/node_modules/mongodb-core/lib/sdam/topology_description.js deleted file mode 100644 index cd4f8feadda89e5eb570ea5b20f9742d34e5c213..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/sdam/topology_description.js +++ /dev/null @@ -1,364 +0,0 @@ -'use strict'; -const ServerType = require('./server_description').ServerType; -const ServerDescription = require('./server_description').ServerDescription; -const ReadPreference = require('../topologies/read_preference'); - -// contstants related to compatability checks -const MIN_SUPPORTED_SERVER_VERSION = '2.6'; -const MIN_SUPPORTED_WIRE_VERSION = 2; -const MAX_SUPPORTED_WIRE_VERSION = 5; - -// An enumeration of topology types we know about -const TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -// Representation of a deployment of servers -class TopologyDescription { - /** - * Create a TopologyDescription - * - * @param {string} topologyType - * @param {Map<string, ServerDescription>} serverDescriptions the a map of address to ServerDescription - * @param {string} setName - * @param {number} maxSetVersion - * @param {ObjectId} maxElectionId - */ - constructor(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, options) { - options = options || {}; - - // TODO: consider assigning all these values to a temporary value `s` which - // we use `Object.freeze` on, ensuring the internal state of this type - // is immutable. - this.type = topologyType || TopologyType.Unknown; - this.setName = setName || null; - this.maxSetVersion = maxSetVersion || null; - this.maxElectionId = maxElectionId || null; - this.servers = serverDescriptions || new Map(); - this.stale = false; - this.compatible = true; - this.compatibilityError = null; - this.logicalSessionTimeoutMinutes = null; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; - this.localThresholdMS = options.localThresholdMS || 0; - this.options = options; - - // determine server compatibility - for (const serverDescription of this.servers.values()) { - if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${ - serverDescription.minWireVersion - }, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION}.`; - } - - if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${ - serverDescription.maxWireVersion - }, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; - break; - } - } - - // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set - // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes - // value among ServerDescriptions of all data-bearing server types. If any have a null - // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be - // set to null. - const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable); - this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => { - if (server.logicalSessionTimeoutMinutes == null) return null; - if (result == null) return server.logicalSessionTimeoutMinutes; - return Math.min(result, server.logicalSessionTimeoutMinutes); - }, null); - } - - /** - * @returns The minimum reported wire version of all known servers - */ - get commonWireVersion() { - return Array.from(this.servers.values()) - .filter(server => server.type !== ServerType.Unknown) - .reduce( - (min, server) => - min == null ? server.maxWireVersion : Math.min(min, server.maxWireVersion), - null - ); - } - - /** - * Returns a copy of this description updated with a given ServerDescription - * - * @param {ServerDescription} serverDescription - */ - update(serverDescription) { - const address = serverDescription.address; - // NOTE: there are a number of prime targets for refactoring here - // once we support destructuring assignments - - // potentially mutated values - let topologyType = this.type; - let setName = this.setName; - let maxSetVersion = this.maxSetVersion; - let maxElectionId = this.maxElectionId; - - const serverType = serverDescription.type; - let serverDescriptions = new Map(this.servers); - - // update the actual server description - serverDescriptions.set(address, serverDescription); - - if (topologyType === TopologyType.Single) { - // once we are defined as single, that never changes - return new TopologyDescription( - TopologyType.Single, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - this.options - ); - } - - if (topologyType === TopologyType.Unknown) { - if (serverType === ServerType.Standalone) { - serverDescriptions.delete(address); - } else { - topologyType = topologyTypeForServerType(serverType); - } - } - - if (topologyType === TopologyType.Sharded) { - if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { - serverDescriptions.delete(address); - } - } - - if (topologyType === TopologyType.ReplicaSetNoPrimary) { - if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - } - - if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); - (topologyType = result[0]), (setName = result[1]); - } - } - - if (topologyType === TopologyType.ReplicaSetWithPrimary) { - if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - topologyType = checkHasPrimary(serverDescriptions); - } else if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - topologyType = updateRsWithPrimaryFromMember( - serverDescriptions, - setName, - serverDescription - ); - } else { - topologyType = checkHasPrimary(serverDescriptions); - } - } - - return new TopologyDescription( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - this.options - ); - } - - /** - * Determines if the topology has a readable server available. See the table in the - * following section for behaviour rules. - * - * @param {ReadPreference} [readPreference] An optional read preference for determining if a readable server is present - * @return {Boolean} Whether there is a readable server in this topology - */ - hasReadableServer(/* readPreference */) { - // To be implemented when server selection is implemented - } - - /** - * Determines if the topology has a writable server available. See the table in the - * following section for behaviour rules. - * - * @return {Boolean} Whether there is a writable server in this topology - */ - hasWritableServer() { - return this.hasReadableServer(ReadPreference.primary); - } - - /** - * Determines if the topology has a definition for the provided address - * - * @param {String} address - * @return {Boolean} Whether the topology knows about this server - */ - hasServer(address) { - return this.servers.has(address); - } -} - -function topologyTypeForServerType(serverType) { - if (serverType === ServerType.Mongos) return TopologyType.Sharded; - if (serverType === ServerType.RSPrimary) return TopologyType.ReplicaSetWithPrimary; - return TopologyType.ReplicaSetNoPrimary; -} - -function updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId -) { - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - - const electionIdOID = serverDescription.electionId ? serverDescription.electionId.$oid : null; - const maxElectionIdOID = maxElectionId ? maxElectionId.$oid : null; - if (serverDescription.setVersion != null && electionIdOID != null) { - if (maxSetVersion != null && maxElectionIdOID != null) { - if (maxSetVersion > serverDescription.setVersion || maxElectionIdOID > electionIdOID) { - // this primary is stale, we must remove it - serverDescriptions.set( - serverDescription.address, - new ServerDescription(serverDescription.address) - ); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - } - - maxElectionId = serverDescription.electionId; - } - - if ( - serverDescription.setVersion != null && - (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) - ) { - maxSetVersion = serverDescription.setVersion; - } - - // We've heard from the primary. Is it the same primary as before? - for (const address of serverDescriptions.keys()) { - const server = serverDescriptions.get(address); - - if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { - // Reset old primary's type to Unknown. - serverDescriptions.set(address, new ServerDescription(server.address)); - - // There can only be one primary - break; - } - } - - // Discover new hosts from this primary's response. - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - // Remove hosts not in the response. - const currentAddresses = Array.from(serverDescriptions.keys()); - const responseAddresses = serverDescription.allHosts; - currentAddresses.filter(addr => responseAddresses.indexOf(addr) === -1).forEach(address => { - serverDescriptions.delete(address); - }); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; -} - -function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { - if (setName == null) { - throw new TypeError('setName is required'); - } - - if ( - setName !== serverDescription.setName || - (serverDescription.me && serverDescription.address !== serverDescription.me) - ) { - serverDescriptions.delete(serverDescription.address); - } - - return checkHasPrimary(serverDescriptions); -} - -function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { - let topologyType = TopologyType.ReplicaSetNoPrimary; - - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [topologyType, setName]; - } - - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - if (serverDescription.me && serverDescription.address !== serverDescription.me) { - serverDescriptions.delete(serverDescription.address); - } - - return [topologyType, setName]; -} - -function checkHasPrimary(serverDescriptions) { - for (const addr of serverDescriptions.keys()) { - if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { - return TopologyType.ReplicaSetWithPrimary; - } - } - - return TopologyType.ReplicaSetNoPrimary; -} - -module.exports = { - TopologyType, - TopologyDescription -}; diff --git a/node_modules/mongodb-core/lib/sessions.js b/node_modules/mongodb-core/lib/sessions.js deleted file mode 100644 index 429c06e5bd84eb5133fe16695b57e835c467592d..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/sessions.js +++ /dev/null @@ -1,459 +0,0 @@ -'use strict'; - -const retrieveBSON = require('./connection/utils').retrieveBSON; -const EventEmitter = require('events'); -const BSON = retrieveBSON(); -const Binary = BSON.Binary; -const uuidV4 = require('./utils').uuidV4; -const MongoError = require('./error').MongoError; -const isRetryableError = require('././error').isRetryableError; -const MongoNetworkError = require('./error').MongoNetworkError; -const MongoWriteConcernError = require('./error').MongoWriteConcernError; -const Transaction = require('./transactions').Transaction; -const TxnState = require('./transactions').TxnState; - -function assertAlive(session, callback) { - if (session.serverSession == null) { - const error = new MongoError('Cannot use a session that has ended'); - if (typeof callback === 'function') { - callback(error, null); - return false; - } - - throw error; - } - - return true; -} - -/** - * Options to pass when creating a Client Session - * @typedef {Object} SessionOptions - * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session - * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. - */ - -/** - * A BSON document reflecting the lsid of a {@link ClientSession} - * @typedef {Object} SessionId - */ - -/** - * A class representing a client session on the server - * WARNING: not meant to be instantiated directly. - * @class - * @hideconstructor - */ -class ClientSession extends EventEmitter { - /** - * Create a client session. - * WARNING: not meant to be instantiated directly - * - * @param {Topology} topology The current client's topology (Internal Class) - * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) - * @param {SessionOptions} [options] Optional settings - * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver - */ - constructor(topology, sessionPool, options, clientOptions) { - super(); - - if (topology == null) { - throw new Error('ClientSession requires a topology'); - } - - if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { - throw new Error('ClientSession requires a ServerSessionPool'); - } - - options = options || {}; - this.topology = topology; - this.sessionPool = sessionPool; - this.hasEnded = false; - this.serverSession = sessionPool.acquire(); - this.clientOptions = clientOptions; - - this.supports = { - causalConsistency: - typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true - }; - - options = options || {}; - if (typeof options.initialClusterTime !== 'undefined') { - this.clusterTime = options.initialClusterTime; - } else { - this.clusterTime = null; - } - - this.operationTime = null; - this.explicit = !!options.explicit; - this.owner = options.owner; - this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); - this.transaction = new Transaction(); - } - - /** - * The server id associated with this session - * @type {SessionId} - */ - get id() { - return this.serverSession.id; - } - - /** - * Ends this session on the server - * - * @param {Object} [options] Optional settings. Currently reserved for future use - * @param {Function} [callback] Optional callback for completion of this operation - */ - endSession(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (this.hasEnded) { - if (typeof callback === 'function') callback(null, null); - return; - } - - if (this.serverSession && this.inTransaction()) { - this.abortTransaction(); // pass in callback? - } - - // mark the session as ended, and emit a signal - this.hasEnded = true; - this.emit('ended', this); - - // release the server session back to the pool - this.sessionPool.release(this.serverSession); - - // spec indicates that we should ignore all errors for `endSessions` - if (typeof callback === 'function') callback(null, null); - } - - /** - * Advances the operationTime for a ClientSession. - * - * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to - */ - advanceOperationTime(operationTime) { - if (this.operationTime == null) { - this.operationTime = operationTime; - return; - } - - if (operationTime.greaterThan(this.operationTime)) { - this.operationTime = operationTime; - } - } - - /** - * Used to determine if this session equals another - * @param {ClientSession} session - * @return {boolean} true if the sessions are equal - */ - equals(session) { - if (!(session instanceof ClientSession)) { - return false; - } - - return this.id.id.buffer.equals(session.id.id.buffer); - } - - /** - * Increment the transaction number on the internal ServerSession - */ - incrementTransactionNumber() { - this.serverSession.txnNumber++; - } - - /** - * @returns {boolean} whether this session is currently in a transaction or not - */ - inTransaction() { - return this.transaction.isActive; - } - - /** - * Starts a new transaction with the given options. - * - * @param {TransactionOptions} options Options for the transaction - */ - startTransaction(options) { - assertAlive(this); - if (this.inTransaction()) { - throw new MongoError('Transaction already in progress'); - } - - // increment txnNumber - this.incrementTransactionNumber(); - - // create transaction state - this.transaction = new Transaction( - Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) - ); - - this.transaction.transition(TxnState.STARTING_TRANSACTION); - } - - /** - * Commits the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - commitTransaction(callback) { - if (typeof callback === 'function') { - endTransaction(this, 'commitTransaction', callback); - return; - } - - return new Promise((resolve, reject) => { - endTransaction( - this, - 'commitTransaction', - (err, reply) => (err ? reject(err) : resolve(reply)) - ); - }); - } - - /** - * Aborts the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - abortTransaction(callback) { - if (typeof callback === 'function') { - endTransaction(this, 'abortTransaction', callback); - return; - } - - return new Promise((resolve, reject) => { - endTransaction( - this, - 'abortTransaction', - (err, reply) => (err ? reject(err) : resolve(reply)) - ); - }); - } - - /** - * This is here to ensure that ClientSession is never serialized to BSON. - * @ignore - */ - toBSON() { - throw new Error('ClientSession cannot be serialized to BSON.'); - } -} - -function endTransaction(session, commandName, callback) { - if (!assertAlive(session, callback)) { - // checking result in case callback was called - return; - } - - // handle any initial problematic cases - let txnState = session.transaction.state; - - if (txnState === TxnState.NO_TRANSACTION) { - callback(new MongoError('No transaction started')); - return; - } - - if (commandName === 'commitTransaction') { - if ( - txnState === TxnState.STARTING_TRANSACTION || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); - return; - } - } else { - if (txnState === TxnState.STARTING_TRANSACTION) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call abortTransaction twice')); - return; - } - - if ( - txnState === TxnState.TRANSACTION_COMMITTED || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); - return; - } - } - - // construct and send the command - const command = { [commandName]: 1 }; - - // apply a writeConcern if specified - if (session.transaction.options.writeConcern) { - Object.assign(command, { writeConcern: session.transaction.options.writeConcern }); - } else if (session.clientOptions && session.clientOptions.w) { - Object.assign(command, { writeConcern: { w: session.clientOptions.w } }); - } - - function commandHandler(e, r) { - if (commandName === 'commitTransaction') { - session.transaction.transition(TxnState.TRANSACTION_COMMITTED); - - if ( - e && - (e instanceof MongoNetworkError || - e instanceof MongoWriteConcernError || - isRetryableError(e)) - ) { - if (e.errorLabels) { - const idx = e.errorLabels.indexOf('TransientTransactionError'); - if (idx !== -1) { - e.errorLabels.splice(idx, 1); - } - } else { - e.errorLabels = []; - } - - e.errorLabels.push('UnknownTransactionCommitResult'); - } - } else { - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - } - - callback(e, r); - } - - // The spec indicates that we should ignore all errors on `abortTransaction` - function transactionError(err) { - return commandName === 'commitTransaction' ? err : null; - } - - // send the command - session.topology.command('admin.$cmd', command, { session }, (err, reply) => { - if (err && isRetryableError(err)) { - return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => - commandHandler(transactionError(_err), _reply) - ); - } - - commandHandler(transactionError(err), reply); - }); -} - -/** - * Reflects the existence of a session on the server. Can be reused by the session pool. - * WARNING: not meant to be instantiated directly. For internal use only. - * @ignore - */ -class ServerSession { - constructor() { - this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; - this.lastUse = Date.now(); - this.txnNumber = 0; - } - - /** - * Determines if the server session has timed out. - * @ignore - * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" - * @return {boolean} true if the session has timed out. - */ - hasTimedOut(sessionTimeoutMinutes) { - // Take the difference of the lastUse timestamp and now, which will result in a value in - // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` - const idleTimeMinutes = Math.round( - (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000 - ); - - return idleTimeMinutes > sessionTimeoutMinutes - 1; - } -} - -/** - * Maintains a pool of Server Sessions. - * For internal use only - * @ignore - */ -class ServerSessionPool { - constructor(topology) { - if (topology == null) { - throw new Error('ServerSessionPool requires a topology'); - } - - this.topology = topology; - this.sessions = []; - } - - /** - * Ends all sessions in the session pool. - * @ignore - */ - endAllPooledSessions() { - if (this.sessions.length) { - this.topology.endSessions(this.sessions.map(session => session.id)); - this.sessions = []; - } - } - - /** - * Acquire a Server Session from the pool. - * Iterates through each session in the pool, removing any stale sessions - * along the way. The first non-stale session found is removed from the - * pool and returned. If no non-stale session is found, a new ServerSession - * is created. - * @ignore - * @returns {ServerSession} - */ - acquire() { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const session = this.sessions.shift(); - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - return session; - } - } - - return new ServerSession(); - } - - /** - * Release a session to the session pool - * Adds the session back to the session pool if the session has not timed out yet. - * This method also removes any stale sessions from the pool. - * @ignore - * @param {ServerSession} session The session to release to the pool - */ - release(session) { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const session = this.sessions[this.sessions.length - 1]; - if (session.hasTimedOut(sessionTimeoutMinutes)) { - this.sessions.pop(); - } else { - break; - } - } - - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - this.sessions.unshift(session); - } - } -} - -module.exports = { - ClientSession, - ServerSession, - ServerSessionPool, - TxnState -}; diff --git a/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/node_modules/mongodb-core/lib/tools/smoke_plugin.js deleted file mode 100644 index 22d0298627f4d062533b72ffd42e5a25e28d59db..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/tools/smoke_plugin.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -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/mongodb-core/lib/topologies/mongos.js b/node_modules/mongodb-core/lib/topologies/mongos.js deleted file mode 100644 index cd5110b05e84c05024ec608f83a3a4bfef10b3a6..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/topologies/mongos.js +++ /dev/null @@ -1,1504 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const BasicCursor = require('../cursor'); -const Logger = require('../connection/logger'); -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const clone = require('./shared').clone; -const diff = require('./shared').diff; -const cloneOptions = require('./shared').cloneOptions; -const createClientInfo = require('./shared').createClientInfo; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const isRetryableError = require('../error').isRetryableError; -const BSON = retrieveBSON(); - -/** - * @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(); - */ - -const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.logger.error( - f( - 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Mongos instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @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 {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection - * @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 {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation 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 {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @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 {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Mongos} A cursor instance - * @fires Mongos#connect - * @fires Mongos#reconnect - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#failed - * @fires Mongos#fullsetup - * @fires Mongos#all - * @fires Mongos#serverHeartbeatStarted - * @fires Mongos#serverHeartbeatSucceeded - * @fires Mongos#serverHeartbeatFailed - * @fires Mongos#topologyOpening - * @fires Mongos#topologyClosed - * @fires Mongos#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Mongos = function(seedlist, options) { - options = options || {}; - - // Get replSet Id - this.id = id++; - - // Internal state - this.s = { - options: Object.assign({}, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || BasicCursor, - // Logger instance - logger: Logger('Mongos', options), - // Seedlist - seedlist: seedlist, - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false, - // localThresholdMS - localThresholdMS: options.localThresholdMS || 15, - // Client info - clientInfo: createClientInfo(options), - // Authentication context - authenticationContexts: [] - }; - - // Set the client info - this.s.options.clientInfo = createClientInfo(options); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // All the authProviders - this.authProviders = options.authProviders || defaultAuthProviders(this.s.bson); - - // Disconnected state - this.state = DISCONNECTED; - - // Current proxies we are connecting to - this.connectingProxies = []; - // Currently connected proxies - this.connectedProxies = []; - // Disconnected proxies - this.disconnectedProxies = []; - // Are we authenticating - this.authenticating = false; - // Index of proxy to run operations against - this.index = 0; - // High availability timeout id - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - - // Description of the Replicaset - this.topologyDescription = { - topologyType: 'Unknown', - servers: [] - }; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; - - // Add event listener - EventEmitter.call(this); -}; - -inherits(Mongos, EventEmitter); -Object.assign(Mongos.prototype, SessionMixins); - -Object.defineProperty(Mongos.prototype, 'type', { - enumerable: true, - get: function() { - return 'mongos'; - } -}); - -Object.defineProperty(Mongos.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; -function destroyServer(server, options) { - options = options || {}; - SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - server.destroy(options); -} - -/** - * Initiate server connect - * @method - * @param {array} [options.auth=null] Array of auth options to apply on connect - */ -Mongos.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - const server = new Server( - Object.assign({}, self.s.options, x, options, { - authProviders: self.authProviders, - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - - relayEvents(server, self, ['serverDescriptionChanged']); - return server; - }); - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - - // Start all server connections - connectProxies(self, servers); -}; - -function handleEvent(self) { - return function() { - if (self.state === DESTROYED) return; - // Move to list of disconnectedProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Emit the left signal - self.emit('left', 'mongos', this); - // Emit the sdam event - self.emit('serverClosed', { - topologyId: self.id, - address: this.name - }); - }; -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - - // Destroy the instance - if (self.state === DESTROYED) { - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - return this.destroy(); - } - - // Check the type of server - if (event === 'connect') { - // Do we have authentication contexts that need to be applied - applyAuthenticationContexts(self, _this, function() { - // Get last known ismaster - self.ismaster = _this.lastIsMaster(); - - // Is this not a proxy, remove t - if (self.ismaster.msg === 'isdbgrid') { - // Add to the connectd list - for (var i = 0; i < self.connectedProxies.length; i++) { - if (self.connectedProxies[i].name === _this.name) { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - _this.destroy(); - return self.emit('failed', _this); - } - } - - // Remove the handlers - for (i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Move from connecting proxies connected - moveServerFrom(self.connectingProxies, self.connectedProxies, _this); - // Emit the joined event - self.emit('joined', 'mongos', _this); - } else { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; - // We have a standalone server - if (!self.ismaster.hosts) { - message = 'expected mongos proxy, but found standalone mongod for server %s'; - } - - self.s.logger.warn(f(message, _this.name)); - } - - // This is not a mongos proxy, remove it completely - removeProxyFrom(self.connectingProxies, _this); - // Emit the left event - self.emit('left', 'server', _this); - // Emit failed event - self.emit('failed', _this); - } - }); - } else { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - // Emit the left event - self.emit('left', 'mongos', this); - // Emit failed event - self.emit('failed', this); - } - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Trigger topologyMonitor - if (self.connectingProxies.length === 0) { - // Emit connected if we are connected - if (self.connectedProxies.length > 0 && self.state === CONNECTING) { - // Set the state to connected - stateTransition(self, CONNECTED); - // Emit the connect event - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.disconnectedProxies.length === 0) { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - self.s.logger.warn( - f('no mongos proxies found in seed list, did you mean to connect to a replicaset') - ); - } - - // Emit the error that no proxies were found - return self.emit('error', new MongoError('no mongos proxies found in seed list')); - } - - // Topology monitor - topologyMonitor(self, { firstConnect: true }); - } - }; -} - -function connectProxies(self, servers) { - // Update connectingProxies - self.connectingProxies = self.connectingProxies.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.id, - address: server.name - }); - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - // Start all the servers - while (servers.length > 0) { - connect(servers.shift(), timeoutInterval++); - } -} - -function pickProxy(self) { - // Get the currently connected Proxies - var connectedProxies = self.connectedProxies.slice(0); - - // Set lower bound - var lowerBoundLatency = Number.MAX_VALUE; - - // Determine the lower bound for the Proxies - for (var i = 0; i < connectedProxies.length; i++) { - if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { - lowerBoundLatency = connectedProxies[i].lastIsMasterMS; - } - } - - // Filter out the possible servers - connectedProxies = connectedProxies.filter(function(server) { - if ( - server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && - server.isConnected() - ) { - return true; - } - }); - - // We have no connectedProxies pick first of the connected ones - if (connectedProxies.length === 0) { - return self.connectedProxies[0]; - } - - // Get proxy - var proxy = connectedProxies[self.index % connectedProxies.length]; - // Update the index - self.index = (self.index + 1) % connectedProxies.length; - // Return the proxy - return proxy; -} - -function moveServerFrom(from, to, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } - - for (i = 0; i < to.length; i++) { - if (to[i].name === proxy.name) { - to.splice(i, 1); - } - } - - to.push(proxy); -} - -function removeProxyFrom(from, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } -} - -function reconnectProxies(self, proxies, callback) { - // Count lefts - var count = proxies.length; - - // Handle events - var _handleEvent = function(self, event) { - return function() { - var _self = this; - count = count - 1; - - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return this.destroy(); - } - - if (event === 'connect' && !self.authenticating) { - // Do we have authentication contexts that need to be applied - applyAuthenticationContexts(self, _self, function() { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return _self.destroy(); - } - - // Remove the handlers - for (var i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Move to the connected servers - moveServerFrom(self.connectingProxies, self.connectedProxies, _self); - // Emit topology Change - emitTopologyDescriptionChanged(self); - // Emit joined event - self.emit('joined', 'mongos', _self); - }); - } else { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - this.destroy(); - } - - // Are we done finish up callback - if (count === 0) { - callback(); - } - }; - }; - - // No new servers - if (count === 0) { - return callback(); - } - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.name.split(':')[0], - port: parseInt(_server.name.split(':')[1], 10), - authProviders: self.authProviders, - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - - destroyServer(_server); - removeProxyFrom(self.disconnectedProxies, _server); - - // Relay the server description change - relayEvents(server, self, ['serverDescriptionChanged']); - - // Emit opening server event - self.emit('serverOpening', { - topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, - address: server.name - }); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Connect to proxy - self.connectingProxies.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < proxies.length; i++) { - execute(proxies[i], i); - } -} - -function applyAuthenticationContexts(self, server, callback) { - if (self.s.authenticationContexts.length === 0) { - return callback(); - } - - // Copy contexts to ensure no modificiation in the middle of - // auth process. - var authContexts = self.s.authenticationContexts.slice(0); - - // Apply one of the contexts - function applyAuth(authContexts, server, callback) { - if (authContexts.length === 0) return callback(); - // Get the first auth context - var authContext = authContexts.shift(); - // Copy the params - var customAuthContext = authContext.slice(0); - // Push our callback handler - customAuthContext.push(function(/* err */) { - applyAuth(authContexts, server, callback); - }); - - // Attempt authentication - server.auth.apply(server, customAuthContext); - } - - // Apply all auth contexts - applyAuth(authContexts, server, callback); -} - -function topologyMonitor(self, options) { - options = options || {}; - - // Set momitoring timeout - self.haTimeoutId = setTimeout(function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.isConnected() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } - - // Get the connectingServers - var proxies = self.connectedProxies.slice(0); - // Get the count - var count = proxies.length; - - // If the count is zero schedule a new fast - function pingServer(_self, _server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); - - // Execute ismaster - _server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - // Move from connectingProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - _server.destroy(); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: _server.name - }); - // Move from connected proxies to disconnected proxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - } else { - // Update the server ismaster - _server.ismaster = r.result; - _server.lastIsMasterMS = latencyMS; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: _server.name - }); - } - - cb(err, r); - } - ); - } - - // No proxies initiate monitor again - if (proxies.length === 0) { - // Emit close event if any listeners registered - if (self.listeners('close').length > 0 && self.state === CONNECTING) { - self.emit('error', new MongoError('no mongos proxy available')); - } else { - self.emit('close', self); - } - - // Attempt to connect to any unknown servers - return reconnectProxies(self, self.disconnectedProxies, function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - - // Are we connected ? emit connect event - if (self.state === CONNECTING && options.firstConnect) { - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.isConnected()) { - self.emit('reconnect', self); - } else if (!self.isConnected() && self.listeners('close').length > 0) { - self.emit('close', self); - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - - // Ping all servers - for (var i = 0; i < proxies.length; i++) { - pingServer(self, proxies[i], function() { - count = count - 1; - - if (count === 0) { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - - // Attempt to connect to any unknown servers - reconnectProxies(self, self.disconnectedProxies, function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - // Perform topology monitor - topologyMonitor(self); - }); - } - }); - } - }, self.s.haInterval); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Mongos.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Mongos.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - // Get all proxies - var proxies = this.connectedProxies.concat(this.connectingProxies); - proxies.forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -Mongos.prototype.destroy = function(options) { - var self = this; - // Transition state - stateTransition(this, DESTROYED); - // Get all proxies - var proxies = this.connectedProxies.concat(this.connectingProxies); - // Clear out any monitoring process - if (this.haTimeoutId) clearTimeout(this.haTimeoutId); - // Clear out authentication contexts - this.s.authenticationContexts = []; - - // Destroy all connecting servers - proxies.forEach(function(server) { - // Emit the sdam event - self.emit('serverClosed', { - topologyId: self.id, - address: server.name - }); - - destroyServer(server, options); - - // Move to list of disconnectedProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, server); - }); - // Emit the final topology change - emitTopologyDescriptionChanged(self); - // Emit toplogy closing event - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Mongos.prototype.isConnected = function() { - return this.connectedProxies.length > 0; -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Mongos.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -// -// Operations -// - -// Execute write operation -var executeWriteOperation = function(self, op, ns, ops, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Pick a server - let server = pickProxy(self); - // No server found error out - if (!server) return callback(new MongoError('no mongos proxy available')); - - if (!options.retryWrites || !options.session || !isRetryableWritesSupported(self)) { - // Execute the command - return server[op](ns, ops, options, callback); - } - - // increment and assign txnNumber - options.willRetryWrite = true; - options.session.incrementTransactionNumber(); - - server[op](ns, ops, options, (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - // Pick another server - server = pickProxy(self); - - // No server found error out with original error - if (!server || !isRetryableWritesSupported(server)) { - return callback(err); - } - - // rerun the operation - server[op](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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.insert = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - 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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.update = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation(this, '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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.remove = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation(this, 'remove', ns, ops, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * 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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Pick a proxy - var server = pickProxy(self); - - // 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 ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // No server returned we had an error - if (server == null) { - return callback(new MongoError('no mongos proxy available')); - } - - // Cloned options - var clonedOptions = cloneOptions(options); - clonedOptions.topology = self; - - const willRetryWrite = - !options.retrying && - options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, clonedOptions, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, clonedOptions, cb); -}; - -/** - * Get a new cursor - * @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] Options for the cursor - * @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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Mongos.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(this.s.bson, ns, cmd, options, topology, 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(); - var currentContextIndex = 0; - - // If we don't have the mechanism fail - if (this.authProviders[mechanism] == null && mechanism !== 'default') { - return callback(new MongoError(f('auth provider %s does not exist', mechanism))); - } - - // Are we already authenticating, throw - if (this.authenticating) { - return callback(new MongoError('authentication or logout allready in process')); - } - - // 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) { - return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); - } - - // Set to authenticating - this.authenticating = true; - // All errors - var errors = []; - - // Get all the servers - var servers = this.connectedProxies.slice(0); - // No servers return - if (servers.length === 0) { - this.authenticating = false; - callback(null, true); - } - - // Authenticate - function auth(server) { - // Arguments without a callback - var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); - // Create arguments - var finalArguments = argsWithoutCallback.concat([ - function(err) { - count = count - 1; - // Save all the errors - if (err) errors.push({ name: server.name, err: err }); - // We are done - if (count === 0) { - // Auth is done - self.authenticating = false; - - // Return the auth error - if (errors.length) { - // Remove the entry from the stored authentication contexts - self.s.authenticationContexts.splice(currentContextIndex, 0); - // Return error - return callback( - new MongoError({ - message: 'authentication fail', - errors: errors - }), - false - ); - } - - // Successfully authenticated session - callback(null, self); - } - } - ]); - - // Execute the auth only against non arbiter servers - if (!server.lastIsMaster().arbiterOnly) { - server.auth.apply(server, finalArguments); - } - } - - // Save current context index - currentContextIndex = this.s.authenticationContexts.length; - // Store the auth context and return the last index - this.s.authenticationContexts.push([mechanism, db].concat(args.slice(0))); - - // Get total count - var count = servers.length; - // Authenticate against all servers - while (servers.length > 0) { - auth(servers.shift()); - } -}; - -/** - * Logout from a database - * @method - * @param {string} db The db we are logging out from - * @param {authResultCallback} callback A callback function - */ -Mongos.prototype.logout = function(dbName, callback) { - var self = this; - // Are we authenticating or logging out, throw - if (this.authenticating) { - throw new MongoError('authentication or logout allready in process'); - } - - // Ensure no new members are processed while logging out - this.authenticating = true; - - // Remove from all auth providers (avoid any reaplication of the auth details) - var providers = Object.keys(this.authProviders); - for (var i = 0; i < providers.length; i++) { - this.authProviders[providers[i]].logout(dbName); - } - - // Now logout all the servers - var servers = this.connectedProxies.slice(0); - var count = servers.length; - if (count === 0) return callback(); - var errors = []; - - function logoutServer(_server, cb) { - _server.logout(dbName, function(err) { - if (err) errors.push({ name: _server.name, err: err }); - cb(); - }); - } - - // Execute logout on all server instances - for (i = 0; i < servers.length; i++) { - logoutServer(servers[i], function() { - count = count - 1; - - if (count === 0) { - // Do not block new operations - self.authenticating = false; - // If we have one or more errors - if (errors.length) - return callback( - new MongoError({ - message: f('logout failed against db %s', dbName), - errors: errors - }), - false - ); - - // No errors - callback(); - } - }); - } -}; - -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {function} callback - */ -Mongos.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - options = options || {}; - - const server = pickProxy(this); - if (this.s.debug) this.emit('pickedServer', null, server); - callback(null, server); -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Mongos.prototype.connections = function() { - var connections = []; - - for (var i = 0; i < this.connectedProxies.length; i++) { - connections = connections.concat(this.connectedProxies[i].connections()); - } - - return connections; -}; - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - if (self.connectedProxies.length > 0) { - topology = 'Sharded'; - } - - // Generate description - var description = { - topologyType: topology, - servers: [] - }; - - // All proxies - var proxies = self.disconnectedProxies.concat(self.connectingProxies); - - // Add all the disconnected proxies - description.servers = description.servers.concat( - proxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Unknown'; - return description; - }) - ); - - // Add all the connected proxies - description.servers = description.servers.concat( - self.connectedProxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Mongos'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.topologyDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.topologyDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - if (diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - } - - // Set the new description - self.topologyDescription = description; - } -} - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * A mongos reconnect event, used to verify that the mongos topology has reconnected - * - * @event Mongos#reconnect - * @type {Mongos} - */ - -/** - * A mongos fullsetup event, used to signal that all topology members have been contacted. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * A mongos all event, used to signal that all topology members have been contacted. - * - * @event Mongos#all - * @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 - */ - -/** - * A server opening SDAM monitoring event - * - * @event Mongos#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Mongos#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Mongos#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Mongos#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Mongos#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Mongos#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Mongos#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Mongos#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Mongos#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/node_modules/mongodb-core/lib/topologies/read_preference.js b/node_modules/mongodb-core/lib/topologies/read_preference.js deleted file mode 100644 index dda610c5232a992e92db260d91607ecd45cacd38..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/topologies/read_preference.js +++ /dev/null @@ -1,193 +0,0 @@ -'use strict'; - -/** - * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * @class - * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @param {array} tags The tags object - * @param {object} [options] Additional read preference options - * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. - * @return {ReadPreference} - * @example - * const ReplSet = require('mongodb-core').ReplSet, - * ReadPreference = require('mongodb-core').ReadPreference, - * assert = require('assert'); - * - * const server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); - * // Wait for the connection event - * server.on('connect', function(server) { - * const cursor = server.cursor( - * 'db.test', - * { find: 'db.test', query: {} }, - * { readPreference: new ReadPreference('secondary') } - * ); - * - * cursor.next(function(err, doc) { - * server.destroy(); - * }); - * }); - * - * // Start connecting - * server.connect(); - * @see https://docs.mongodb.com/manual/core/read-preference/ - */ -const ReadPreference = function(mode, tags, options) { - // TODO(major): tags MUST be an array of tagsets - if (tags && !Array.isArray(tags)) { - console.warn( - 'ReadPreference tags must be an array, this will change in the next major version' - ); - - if (typeof tags.maxStalenessSeconds !== 'undefined') { - // this is likely an options object - options = tags; - tags = undefined; - } else { - tags = [tags]; - } - } - - this.mode = mode; - this.tags = tags; - - options = options || {}; - if (options.maxStalenessSeconds != null) { - if (options.maxStalenessSeconds <= 0) { - throw new TypeError('maxStalenessSeconds must be a positive integer'); - } - - this.maxStalenessSeconds = options.maxStalenessSeconds; - - // NOTE: The minimum required wire version is 5 for this read preference. If the existing - // topology has a lower value then a MongoError will be thrown during server selection. - this.minWireVersion = 5; - } - - if (this.mode === ReadPreference.PRIMARY || this.mode === true) { - if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { - throw new TypeError('Primary read preference cannot be combined with tags'); - } - - if (this.maxStalenessSeconds) { - throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); - } - } -}; - -// Support the deprecated `preference` property introduced in the porcelain layer -Object.defineProperty(ReadPreference.prototype, 'preference', { - enumerable: true, - get: function() { - return this.mode; - } -}); - -/* - * Read preference mode constants - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest'; - -const VALID_MODES = [ - ReadPreference.PRIMARY, - ReadPreference.PRIMARY_PREFERRED, - ReadPreference.SECONDARY, - ReadPreference.SECONDARY_PREFERRED, - ReadPreference.NEAREST, - true, - false, - null -]; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.isValid = function(mode) { - return VALID_MODES.indexOf(mode) !== -1; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.prototype.isValid = function(mode) { - return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); -}; - -const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; - -/** - * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire - * @method - * @return {boolean} - * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query - */ -ReadPreference.prototype.slaveOk = function() { - return needSlaveOk.indexOf(this.mode) !== -1; -}; - -/** - * Are the two read preference equal - * @method - * @param {ReadPreference} readPreference The read preference with which to check equality - * @return {boolean} True if the two ReadPreferences are equivalent - */ -ReadPreference.prototype.equals = function(readPreference) { - return readPreference.mode === this.mode; -}; - -/** - * Return JSON representation - * @method - * @return {Object} A JSON representation of the ReadPreference - */ -ReadPreference.prototype.toJSON = function() { - const readPreference = { mode: this.mode }; - if (Array.isArray(this.tags)) readPreference.tags = this.tags; - if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; - return readPreference; -}; - -/** - * Primary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primary = new ReadPreference('primary'); -/** - * Primary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); -/** - * Secondary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondary = new ReadPreference('secondary'); -/** - * Secondary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); -/** - * Nearest read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.nearest = new ReadPreference('nearest'); - -module.exports = ReadPreference; diff --git a/node_modules/mongodb-core/lib/topologies/replset.js b/node_modules/mongodb-core/lib/topologies/replset.js deleted file mode 100644 index dbb16044589214540b8192fd7d6f7944cf3a8d7d..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/topologies/replset.js +++ /dev/null @@ -1,1724 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const ReadPreference = require('./read_preference'); -const BasicCursor = require('../cursor'); -const retrieveBSON = require('../connection/utils').retrieveBSON; -const Logger = require('../connection/logger'); -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const ReplSetState = require('./replset_state'); -const clone = require('./shared').clone; -const Timeout = require('./shared').Timeout; -const Interval = require('./shared').Interval; -const createClientInfo = require('./shared').createClientInfo; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const isRetryableError = require('../error').isRetryableError; - -const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; - -var BSON = retrieveBSON(); - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * 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=10000] 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=10000] 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 {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation 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 {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @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 {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {ReplSet} A cursor instance - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#failed - * @fires ReplSet#fullsetup - * @fires ReplSet#all - * @fires ReplSet#error - * @fires ReplSet#serverHeartbeatStarted - * @fires ReplSet#serverHeartbeatSucceeded - * @fires ReplSet#serverHeartbeatFailed - * @fires ReplSet#topologyOpening - * @fires ReplSet#topologyClosed - * @fires ReplSet#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -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); - - // Get replSet Id - this.id = id++; - - // Get the localThresholdMS - var localThresholdMS = options.localThresholdMS || 15; - // Backward compatibility - if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; - - // Create a logger - var logger = Logger('ReplSet', options); - - // Internal state - this.s = { - options: Object.assign({}, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || BasicCursor, - // Logger instance - logger: logger, - // Seedlist - seedlist: seedlist, - // Replicaset state - replicaSetState: new ReplSetState({ - id: this.id, - setName: options.setName, - acceptableLatency: localThresholdMS, - heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, - logger: logger - }), - // Current servers we are connecting to - connectingServers: [], - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Minimum heartbeat frequency used if we detect a server close - minHeartbeatFrequencyMS: 500, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false, - // Client info - clientInfo: createClientInfo(options), - // Authentication context - authenticationContexts: [] - }; - - // Add handler for topology change - this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { - self.emit('topologyDescriptionChanged', r); - }); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // All the authProviders - this.authProviders = options.authProviders || defaultAuthProviders(this.s.bson); - - // Add forwarding of events from state handler - var types = ['joined', 'left']; - types.forEach(function(x) { - self.s.replicaSetState.on(x, function(t, s) { - self.emit(x, t, s); - }); - }); - - // Connect stat - this.initialConnectState = { - connect: false, - fullsetup: false, - all: false - }; - - // Disconnected state - this.state = DISCONNECTED; - this.haTimeoutId = null; - // Are we authenticating - this.authenticating = false; - // Last ismaster - this.ismaster = null; - // Contains the intervalId - this.intervalIds = []; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; -}; - -inherits(ReplSet, EventEmitter); -Object.assign(ReplSet.prototype, SessionMixins); - -Object.defineProperty(ReplSet.prototype, 'type', { - enumerable: true, - get: function() { - return 'replset'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; - } -}); - -function rexecuteOperations(self) { - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executePrimary: true }); - } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executeSecondary: true }); - } -} - -function connectNewServers(self, servers, callback) { - // Count lefts - var count = servers.length; - var error = null; - - // Handle events - var _handleEvent = function(self, event) { - return function(err) { - var _self = this; - count = count - 1; - - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return this.destroy({ force: true }); - } - - if (event === 'connect' && !self.authenticating) { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return _self.destroy({ force: true }); - } - - // Do we have authentication contexts that need to be applied - applyAuthenticationContexts(self, _self, function() { - // Destroy the instance - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return _self.destroy({ force: true }); - } - - // Update the state - var result = self.s.replicaSetState.update(_self); - // Update the state with the new server - if (result) { - // Primary lastIsMaster store it - if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { - self.ismaster = _self.lastIsMaster(); - } - - // Remove the handlers - for (var i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Enalbe the monitoring of the new server - monitorServer(_self.lastIsMaster().me, self, {}); - - // Rexecute any stalled operation - rexecuteOperations(self); - } else { - _self.destroy({ force: true }); - } - }); - } else if (event === 'connect' && self.authenticating) { - this.destroy({ force: true }); - } else if (event === 'error') { - error = err; - } - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Are we done finish up callback - if (count === 0) { - callback(error); - } - }; - }; - - // No new servers - if (count === 0) return callback(); - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.split(':')[0], - port: parseInt(_server.split(':')[1], 10), - authProviders: self.authProviders, - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < servers.length; i++) { - execute(servers[i], i); - } -} - -// Ping the server -var pingServer = function(self, server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); - - // Execute ismaster - // Set the socketTimeout for a monitoring message to a low number - // Ensuring ismaster calls are timed out quickly - server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - server.destroy({ force: true }); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - // Set the last updatedTime - var hrTime = process.hrtime(); - // Calculate the last update time - server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1] / 1000); - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: server.name - }); - - // Remove server from the state - self.s.replicaSetState.remove(server); - } else { - // Update the server ismaster - server.ismaster = r.result; - - // Check if we have a lastWriteDate convert it to MS - // and store on the server instance for later use - if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { - server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); - } - - // Do we have a brand new server - if (server.lastIsMasterMS === -1) { - server.lastIsMasterMS = latencyMS; - } else if (server.lastIsMasterMS) { - // After the first measurement, average RTT MUST be computed using an - // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. - // If the prior average is denoted old_rtt, then the new average (new_rtt) is - // computed from a new RTT measurement (x) using the following formula: - // alpha = 0.2 - // new_rtt = alpha * x + (1 - alpha) * old_rtt - server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; - } - - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: server.name - }); - } - - // Calculate the staleness for this server - self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); - - // Callback - cb(err, r); - } - ); -}; - -// Each server is monitored in parallel in their own timeout loop -var monitorServer = function(host, self, options) { - // If this is not the initial scan - // Is this server already being monitoried, then skip monitoring - if (!options.haInterval) { - for (var i = 0; i < self.intervalIds.length; i++) { - if (self.intervalIds[i].__host === host) { - return; - } - } - } - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - // Create the interval - var intervalId = new _process(function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - // clearInterval(intervalId); - intervalId.stop(); - return; - } - - // Do we already have server connection available for this host - var _server = self.s.replicaSetState.get(host); - - // Check if we have a known server connection and reuse - if (_server) { - // Ping the server - return pingServer(self, _server, function(err) { - if (err) { - // NOTE: should something happen here? - return; - } - - if (self.state === DESTROYED || self.state === UNREFERENCED) { - intervalId.stop(); - return; - } - - // Filter out all called intervaliIds - self.intervalIds = self.intervalIds.filter(function(intervalId) { - return intervalId.isRunning(); - }); - - // Initial sweep - if (_process === Timeout) { - if ( - self.state === CONNECTING && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - self.state = CONNECTED; - - // Emit connected sign - process.nextTick(function() { - self.emit('connect', self); - }); - - // Start topology interval check - topologyMonitor(self, {}); - } - } else { - if ( - self.state === DISCONNECTED && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - self.state = CONNECTED; - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Emit connected sign - process.nextTick(function() { - self.emit('reconnect', self); - }); - } - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - }); - } - }, _haInterval); - - // Start the interval - intervalId.start(); - // Add the intervalId host name - intervalId.__host = host; - // Add the intervalId to our list of intervalIds - self.intervalIds.push(intervalId); -}; - -function topologyMonitor(self, options) { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - options = options || {}; - - // Get the servers - var servers = Object.keys(self.s.replicaSetState.set); - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - if (_process === Timeout) { - return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { - // Don't emit errors if the connection was already - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no primary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } else if ( - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no secondary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } - - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - }); - } else { - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - } - - // Run the reconnect process - function executeReconnect(self) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - connectNewServers(self, self.s.replicaSetState.unknownServers, function() { - var monitoringFrequencey = self.s.replicaSetState.hasPrimary() - ? _haInterval - : self.s.minHeartbeatFrequencyMS; - - // Create a timeout - self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); - }); - }; - } - - // Decide what kind of interval to use - var intervalTime = !self.s.replicaSetState.hasPrimary() - ? self.s.minHeartbeatFrequencyMS - : _haInterval; - - self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); -} - -function addServerToList(list, server) { - for (var i = 0; i < list.length; i++) { - if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; - } - - list.push(server); -} - -function handleEvent(self, event) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) - ); - } - - // Remove from the replicaset state - self.s.replicaSetState.remove(this); - - // Are we in a destroyed state return - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - - // If no primary and secondary available - if ( - !self.s.replicaSetState.hasPrimary() && - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - stateTransition(self, DISCONNECTED); - } else if (!self.s.replicaSetState.hasPrimary()) { - stateTransition(self, DISCONNECTED); - } - - addServerToList(self.s.connectingServers, this); - }; -} - -function applyAuthenticationContexts(self, server, callback) { - if (self.s.authenticationContexts.length === 0) { - return callback(); - } - - // Do not apply any auth contexts if it's an arbiter - if (server.lastIsMaster() && server.lastIsMaster().arbiterOnly) { - return callback(); - } - - // Copy contexts to ensure no modificiation in the middle of - // auth process. - var authContexts = self.s.authenticationContexts.slice(0); - - // Apply one of the contexts - function applyAuth(authContexts, server, callback) { - if (authContexts.length === 0) return callback(); - // Get the first auth context - var authContext = authContexts.shift(); - // Copy the params - var customAuthContext = authContext.slice(0); - // Push our callback handler - customAuthContext.push(function(/* err */) { - applyAuth(authContexts, server, callback); - }); - - // Attempt authentication - server.auth.apply(server, customAuthContext); - } - - // Apply all auth contexts - applyAuth(authContexts, server, callback); -} - -function shouldTriggerConnect(self) { - const isConnecting = self.state === CONNECTING; - const hasPrimary = self.s.replicaSetState.hasPrimary(); - const hasSecondary = self.s.replicaSetState.hasSecondary(); - const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; - const readPreferenceSecondary = - self.s.connectOptions.readPreference && - self.s.connectOptions.readPreference.equals(ReadPreference.secondary); - - return ( - (isConnecting && - ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || - (hasSecondary && secondaryOnlyConnectionAllowed) - ); -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s', - event, - this.name, - self.id - ) - ); - } - - // Destroy the instance - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return this.destroy({ force: true }); - } - - // Check the type of server - if (event === 'connect') { - // Do we have authentication contexts that need to be applied - applyAuthenticationContexts(self, _this, function() { - // Destroy the instance - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return _this.destroy({ force: true }); - } - - // Update the state - var result = self.s.replicaSetState.update(_this); - if (result === true) { - // Primary lastIsMaster store it - if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { - self.ismaster = _this.lastIsMaster(); - } - - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', - event, - _this.name, - self.id, - JSON.stringify(self.s.replicaSetState.set) - ) - ); - } - - // Remove the handlers - for (var i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Do we have a primary or primaryAndSecondary - if (shouldTriggerConnect(self)) { - // We are connected - self.state = CONNECTED; - - // Set initial connect state - self.initialConnectState.connect = true; - // Emit connect event - process.nextTick(function() { - self.emit('connect', self); - }); - - topologyMonitor(self, {}); - } - } else if (result instanceof MongoError) { - _this.destroy({ force: true }); - self.destroy({ force: true }); - return self.emit('error', result); - } else { - _this.destroy({ force: true }); - } - }); - } else { - // Emit failure to connect - self.emit('failed', this); - - addServerToList(self.s.connectingServers, this); - // Remove from the state - self.s.replicaSetState.remove(this); - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - - // Remove from the list from connectingServers - for (var i = 0; i < self.s.connectingServers.length; i++) { - if (self.s.connectingServers[i].equals(this)) { - self.s.connectingServers.splice(i, 1); - } - } - - // Trigger topologyMonitor - if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { - topologyMonitor(self, { haInterval: 1 }); - } - }; -} - -function connectServers(self, servers) { - // Update connectingServers - self.s.connectingServers = self.s.connectingServers.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Add the server to the state - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - while (servers.length > 0) { - connect(servers.shift(), timeoutInterval++); - } -} - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -/** - * Initiate server connect - * @method - * @param {array} [options.auth=null] Array of auth options to apply on connect - */ -ReplSet.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - return new Server( - Object.assign({}, self.s.options, x, options, { - authProviders: self.authProviders, - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - }); - - // Error out as high availbility interval must be < than socketTimeout - if ( - this.s.options.socketTimeout > 0 && - this.s.options.socketTimeout <= this.s.options.haInterval - ) { - return self.emit( - 'error', - new MongoError( - f( - 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', - this.s.options.haInterval, - this.s.options.socketTimeout - ) - ) - ); - } - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - // Start all server connections - connectServers(self, servers); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -ReplSet.prototype.destroy = function(options) { - options = options || {}; - // Transition state - stateTransition(this, DESTROYED); - // Clear out any monitoring process - if (this.haTimeoutId) clearTimeout(this.haTimeoutId); - // Destroy the replicaset - this.s.replicaSetState.destroy(options); - // Clear out authentication contexts - this.s.authenticationContexts = []; - - // Destroy all connecting servers - this.s.connectingServers.forEach(function(x) { - x.destroy(options); - }); - - // Clear out all monitoring - for (var i = 0; i < this.intervalIds.length; i++) { - this.intervalIds[i].stop(); - } - - // Reset list of intervalIds - this.intervalIds = []; - - // Emit toplogy closing event - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); -}; - -/** - * Unref all connections belong to this server - * @method - */ -ReplSet.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - - this.s.replicaSetState.allServers().forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -ReplSet.prototype.lastIsMaster = function() { - // If secondaryOnlyConnectionAllowed and no primary but secondary - // return the secondaries ismaster result. - if ( - this.s.options.secondaryOnlyConnectionAllowed && - !this.s.replicaSetState.hasPrimary() && - this.s.replicaSetState.hasSecondary() - ) { - return this.s.replicaSetState.secondaries[0].lastIsMaster(); - } - - return this.s.replicaSetState.primary - ? this.s.replicaSetState.primary.lastIsMaster() - : this.ismaster; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -ReplSet.prototype.connections = function() { - var servers = this.s.replicaSetState.allServers(); - var connections = []; - for (var i = 0; i < servers.length; i++) { - connections = connections.concat(servers[i].connections()); - } - - return connections; -}; - -/** - * Figure out if the server is connected - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {boolean} - */ -ReplSet.prototype.isConnected = function(options) { - options = options || {}; - - // If we are authenticating signal not connected - // To avoid interleaving of operations - if (this.authenticating) return false; - - // 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.replicaSetState.hasSecondary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { - return this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { - return true; - } - - return this.s.replicaSetState.hasPrimary(); -}; - -/** - * Figure out if the replicaset instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -ReplSet.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {function} callback - */ -ReplSet.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - options = options || {}; - - const server = this.s.replicaSetState.pickServer(options.readPreference); - if (this.s.debug) this.emit('pickedServer', options.readPreference, server); - callback(null, server); -}; - -/** - * Get all connected servers - * @method - * @return {Server[]} - */ -ReplSet.prototype.getServers = function() { - return this.s.replicaSetState.allServers(); -}; - -// -// Execute write operation -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - if (self.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction(); - - if (!self.s.replicaSetState.hasPrimary()) { - if (self.s.disconnectHandler) { - // Not connected but we have a disconnecthandler - return self.s.disconnectHandler.add(op, ns, ops, options, callback); - } else if (!willRetryWrite) { - // No server returned we had an error - return callback(new MongoError('no primary server found')); - } - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - // Per SDAM, remove primary from replicaset - if (self.s.replicaSetState.primary) { - self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - self.s.replicaSetState.primary[op](ns, ops, options, handler); -} - -/** - * 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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.insert = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: '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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.update = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: '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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.remove = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * 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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Establish readPreference - var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; - - // If the readPreference is primary and we have no primary, store it - if ( - readPreference.preference === 'primary' && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference === 'secondary' && - !this.s.replicaSetState.hasSecondary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference !== 'primary' && - !this.s.replicaSetState.hasSecondary() && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // Pick a server - var server = this.s.replicaSetState.pickServer(readPreference); - // We received an error, return it - if (!(server instanceof Server)) return callback(server); - // Emit debug event - if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); - - // No server returned we had an error - if (server == null) { - return callback( - new MongoError( - f('no server found that matches the provided readPreference %s', readPreference) - ) - ); - } - - const willRetryWrite = - !options.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - // Per SDAM, remove primary from replicaset - if (this.s.replicaSetState.primary) { - this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, options, cb); -}; - -/** - * 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(); - var currentContextIndex = 0; - - // If we don't have the mechanism fail - if (this.authProviders[mechanism] == null && mechanism !== 'default') { - return callback(new MongoError(f('auth provider %s does not exist', mechanism))); - } - - // Are we already authenticating, throw - if (this.authenticating) { - return callback(new MongoError('authentication or logout allready in process')); - } - - // 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() && self.s.disconnectHandler != null) { - if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { - return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); - } else if ( - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); - } - } - - // Set to authenticating - this.authenticating = true; - // All errors - var errors = []; - - // Get all the servers - var servers = this.s.replicaSetState.allServers(); - // No servers return - if (servers.length === 0) { - this.authenticating = false; - callback(null, true); - } - - // Authenticate - function auth(server) { - // Arguments without a callback - var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); - // Create arguments - var finalArguments = argsWithoutCallback.concat([ - function(err) { - count = count - 1; - // Save all the errors - if (err) errors.push({ name: server.name, err: err }); - // We are done - if (count === 0) { - // Auth is done - self.authenticating = false; - - // Return the auth error - if (errors.length) { - // Remove the entry from the stored authentication contexts - self.s.authenticationContexts.splice(currentContextIndex, 0); - // Return error - return callback( - new MongoError({ - message: 'authentication fail', - errors: errors - }), - false - ); - } - - // Successfully authenticated session - callback(null, self); - } - } - ]); - - if (!server.lastIsMaster().arbiterOnly) { - // Execute the auth only against non arbiter servers - server.auth.apply(server, finalArguments); - } else { - // If we are authenticating against an arbiter just ignore it - finalArguments.pop()(null); - } - } - - // Get total count - var count = servers.length; - - // Save current context index - currentContextIndex = this.s.authenticationContexts.length; - - // Store the auth context and return the last index - this.s.authenticationContexts.push([mechanism, db].concat(args.slice(0))); - - // Authenticate against all servers - while (servers.length > 0) { - auth(servers.shift()); - } -}; - -/** - * Logout from a database - * @method - * @param {string} db The db we are logging out from - * @param {authResultCallback} callback A callback function - */ -ReplSet.prototype.logout = function(dbName, callback) { - var self = this; - // Are we authenticating or logging out, throw - if (this.authenticating) { - throw new MongoError('authentication or logout allready in process'); - } - - // Ensure no new members are processed while logging out - this.authenticating = true; - - // Remove from all auth providers (avoid any reaplication of the auth details) - var providers = Object.keys(this.authProviders); - for (var i = 0; i < providers.length; i++) { - this.authProviders[providers[i]].logout(dbName); - } - - // Clear out any contexts associated with the db - self.s.authenticationContexts = self.s.authenticationContexts.filter(function(context) { - return context[1] !== dbName; - }); - - // Now logout all the servers - var servers = this.s.replicaSetState.allServers(); - var count = servers.length; - if (count === 0) return callback(); - var errors = []; - - function logoutServer(_server, cb) { - _server.logout(dbName, function(err) { - if (err) errors.push({ name: _server.name, err: err }); - cb(); - }); - } - - // Execute logout on all server instances - for (i = 0; i < servers.length; i++) { - logoutServer(servers[i], function() { - count = count - 1; - - if (count === 0) { - // Do not block new operations - self.authenticating = false; - // If we have one or more errors - if (errors.length) - return callback( - new MongoError({ - message: f('logout failed against db %s', dbName), - errors: errors - }), - false - ); - - // No errors - callback(); - } - }); - } -}; - -/** - * Get a new cursor - * @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] Options for the cursor - * @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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -ReplSet.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); -}; - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * A replset reconnect event, used to verify that the topology reconnected - * - * @event ReplSet#reconnect - * @type {ReplSet} - */ - -/** - * A replset fullsetup event, used to signal that all topology members have been contacted. - * - * @event ReplSet#fullsetup - * @type {ReplSet} - */ - -/** - * A replset all event, used to signal that all topology members have been contacted. - * - * @event ReplSet#all - * @type {ReplSet} - */ - -/** - * A replset failed event, used to signal that initial replset connection failed. - * - * @event ReplSet#failed - * @type {ReplSet} - */ - -/** - * 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 - */ - -/** - * A server opening SDAM monitoring event - * - * @event ReplSet#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event ReplSet#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event ReplSet#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event ReplSet#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event ReplSet#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event ReplSet#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event ReplSet#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event ReplSet#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event ReplSet#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/node_modules/mongodb-core/lib/topologies/replset_state.js b/node_modules/mongodb-core/lib/topologies/replset_state.js deleted file mode 100644 index 474517359f8bf9c178390b17b222d6ae380ed24f..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/topologies/replset_state.js +++ /dev/null @@ -1,1099 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - diff = require('./shared').diff, - EventEmitter = require('events').EventEmitter, - Logger = require('../connection/logger'), - ReadPreference = require('./read_preference'), - MongoError = require('../error').MongoError, - Buffer = require('safe-buffer').Buffer; - -var TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -var ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -var ReplSetState = function(options) { - options = options || {}; - // Add event listener - EventEmitter.call(this); - // Topology state - this.topologyType = TopologyType.ReplicaSetNoPrimary; - this.setName = options.setName; - - // Server set - this.set = {}; - - // Unpacked options - this.id = options.id; - this.setName = options.setName; - - // Replicaset logger - this.logger = options.logger || Logger('ReplSet', options); - - // Server selection index - this.index = 0; - // Acceptable latency - this.acceptableLatency = options.acceptableLatency || 15; - - // heartbeatFrequencyMS - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - - // Server side - this.primary = null; - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - // Current unknown hosts - this.unknownServers = []; - // In set status - this.set = {}; - // Status - this.maxElectionId = null; - this.maxSetVersion = 0; - // Description of the Replicaset - this.replicasetDescription = { - topologyType: 'Unknown', - servers: [] - }; - - this.logicalSessionTimeoutMinutes = undefined; -}; - -inherits(ReplSetState, EventEmitter); - -ReplSetState.prototype.hasPrimaryAndSecondary = function() { - return this.primary != null && this.secondaries.length > 0; -}; - -ReplSetState.prototype.hasPrimaryOrSecondary = function() { - return this.hasPrimary() || this.hasSecondary(); -}; - -ReplSetState.prototype.hasPrimary = function() { - return this.primary != null; -}; - -ReplSetState.prototype.hasSecondary = function() { - return this.secondaries.length > 0; -}; - -ReplSetState.prototype.get = function(host) { - var servers = this.allServers(); - - for (var i = 0; i < servers.length; i++) { - if (servers[i].name.toLowerCase() === host.toLowerCase()) { - return servers[i]; - } - } - - return null; -}; - -ReplSetState.prototype.allServers = function(options) { - options = options || {}; - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - return servers; -}; - -ReplSetState.prototype.destroy = function(options) { - // Destroy all sockets - if (this.primary) this.primary.destroy(options); - this.secondaries.forEach(function(x) { - x.destroy(options); - }); - this.arbiters.forEach(function(x) { - x.destroy(options); - }); - this.passives.forEach(function(x) { - x.destroy(options); - }); - this.ghosts.forEach(function(x) { - x.destroy(options); - }); - // Clear out the complete state - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - this.unknownServers = []; - this.set = {}; - this.primary = null; - // Emit the topology changed - emitTopologyDescriptionChanged(this); -}; - -ReplSetState.prototype.remove = function(server, options) { - options = options || {}; - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // Only remove if the current server is not connected - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - - // Check if it's active and this is just a failed connection attempt - for (var i = 0; i < servers.length; i++) { - if ( - !options.force && - servers[i].equals(server) && - servers[i].isConnected && - servers[i].isConnected() - ) { - return; - } - } - - // If we have it in the set remove it - if (this.set[serverName]) { - this.set[serverName].type = ServerType.Unknown; - this.set[serverName].electionId = null; - this.set[serverName].setName = null; - this.set[serverName].setVersion = null; - } - - // Remove type - var removeType = null; - - // Remove from any lists - if (this.primary && this.primary.equals(server)) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - removeType = 'primary'; - } - - // Remove from any other server lists - removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; - removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; - removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; - removeFrom(server, this.ghosts); - removeFrom(server, this.unknownServers); - - // Push to unknownServers - this.unknownServers.push(serverName); - - // Do we have a removeType - if (removeType) { - this.emit('left', removeType, server); - } -}; - -const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; - -ReplSetState.prototype.update = function(server) { - var self = this; - // Get the current ismaster - var ismaster = server.lastIsMaster(); - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // - // Add any hosts - // - if (ismaster) { - // Join all the possible new hosts - var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; - hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); - hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); - hosts = hosts.map(function(s) { - return s.toLowerCase(); - }); - - // Add all hosts as unknownServers - for (var i = 0; i < hosts.length; i++) { - // Add to the list of unknown server - if ( - this.unknownServers.indexOf(hosts[i]) === -1 && - (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) - ) { - this.unknownServers.push(hosts[i].toLowerCase()); - } - - if (!this.set[hosts[i]]) { - this.set[hosts[i]] = { - type: ServerType.Unknown, - electionId: null, - setName: null, - setVersion: null - }; - } - } - } - - // - // Unknown server - // - if (!ismaster && !inList(ismaster, server, this.unknownServers)) { - self.set[serverName] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - // Update set information about the server instance - self.set[serverName].type = ServerType.Unknown; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - - if (self.unknownServers.indexOf(server.name) === -1) { - self.unknownServers.push(serverName); - } - - // Set the topology - return false; - } - - // Update logicalSessionTimeoutMinutes - if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { - if ( - self.logicalSessionTimeoutMinutes === undefined || - ismaster.logicalSessionTimeoutMinutes === null - ) { - self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; - } else { - self.logicalSessionTimeoutMinutes = Math.min( - self.logicalSessionTimeoutMinutes, - ismaster.logicalSessionTimeoutMinutes - ); - } - } - - // - // Is this a mongos - // - if (ismaster && ismaster.msg === 'isdbgrid') { - return false; - } - - // A RSOther instance - if ( - (ismaster.setName && ismaster.hidden) || - (ismaster.setName && - !ismaster.ismaster && - !ismaster.secondary && - !ismaster.arbiterOnly && - !ismaster.passive) - ) { - self.set[serverName] = { - type: ServerType.RSOther, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - return false; - } - - // A RSGhost instance - if (ismaster.isreplicaset) { - self.set[serverName] = { - type: ServerType.RSGhost, - setVersion: null, - electionId: null, - setName: null - }; - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - - // Set the topology - return false; - } - - // - // Standalone server, destroy and return - // - if (ismaster && ismaster.ismaster && !ismaster.setName) { - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; - this.remove(server, { force: true }); - return false; - } - - // - // Server in maintanance mode - // - if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { - this.remove(server, { force: true }); - return false; - } - - // - // If the .me field does not match the passed in server - // - if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { - if (this.logger.isWarn()) { - this.logger.warn( - f( - 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', - server.name, - ismaster.me - ) - ); - } - - // Delete from the set - delete this.set[serverName]; - // Delete unknown servers - removeFrom(server, self.unknownServers); - - // Destroy the instance - server.destroy(); - - // Set the type of topology we have - if (this.primary && !this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - // - // We have a potential primary - // - if (!this.primary && ismaster.primary) { - this.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setName: null, - electionId: null, - setVersion: null - }; - } - - return false; - } - - // - // Primary handling - // - if (!this.primary && ismaster.ismaster && ismaster.setName) { - var ismasterElectionId = server.lastIsMaster().electionId; - if (this.setName && this.setName !== ismaster.setName) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return new MongoError( - f( - 'setName from ismaster does not match provided connection setName [%s] != [%s]', - ismaster.setName, - this.setName - ) - ); - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - var result = compareObjectIds(this.maxElectionId, ismasterElectionId); - // Get the electionIds - var ismasterSetVersion = server.lastIsMaster().setVersion; - - if (result === 1) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } else if (result === 0 && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - } - - this.maxSetVersion = ismasterSetVersion; - this.maxElectionId = ismasterElectionId; - } - - // Hande normalization of server names - var normalizedHosts = ismaster.hosts.map(function(x) { - return x.toLowerCase(); - }); - var locationIndex = normalizedHosts.indexOf(serverName); - - // Validate that the server exists in the host list - if (locationIndex !== -1) { - self.primary = server; - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - emitTopologyDescriptionChanged(self); - return true; - } else if (ismaster.ismaster && ismaster.setName) { - // Get the electionIds - var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; - var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; - var currentSetName = self.set[self.primary.name.toLowerCase()].setName; - ismasterElectionId = server.lastIsMaster().electionId; - ismasterSetVersion = server.lastIsMaster().setVersion; - var ismasterSetName = server.lastIsMaster().setName; - - // Is it the same server instance - if (this.primary.equals(server) && currentSetName === ismasterSetName) { - return false; - } - - // If we do not have the same rs name - if (currentSetName && currentSetName !== ismasterSetName) { - if (!this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // Check if we need to replace the server - if (currentElectionId && ismasterElectionId) { - result = compareObjectIds(currentElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion > ismasterSetVersion) { - return false; - } - } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - result = compareObjectIds(this.maxElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } else { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - this.maxElectionId = ismasterElectionId; - this.maxSetVersion = ismasterSetVersion; - } else { - this.maxSetVersion = ismasterSetVersion; - } - - // Modify the entry to unknown - self.set[self.primary.name.toLowerCase()] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - - // Signal primary left - self.emit('left', 'primary', this.primary); - // Destroy the instance - self.primary.destroy(); - // Set the new instance - self.primary = server; - // Set the set information - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // A possible instance - if (!this.primary && ismaster.primary) { - self.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setVersion: null, - electionId: null, - setName: null - }; - } - - // - // Secondary handling - // - if ( - ismaster.secondary && - ismaster.setName && - !inList(ismaster, server, this.secondaries) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy(); - this.primary = null; - self.emit('left', 'primary', server); - } - - // Emit secondary joined replicaset - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Arbiter handling - // - if ( - isArbiter(ismaster) && - !inList(ismaster, server, this.arbiters) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - self.emit('joined', 'arbiter', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Passive handling - // - if ( - ismaster.passive && - ismaster.setName && - !inList(ismaster, server, this.passives) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy(); - this.primary = null; - self.emit('left', 'primary', server); - } - - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Remove the primary - // - if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { - self.emit('left', 'primary', this.primary); - this.primary.destroy(); - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - return false; -}; - -/** - * Recalculate single server max staleness - * @method - */ -ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { - // Locate the max secondary lastwrite - var max = 0; - // Go over all secondaries - for (var i = 0; i < this.secondaries.length; i++) { - max = Math.max(max, this.secondaries[i].lastWriteDate); - } - - // Perform this servers staleness calculation - if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { - server.staleness = - server.lastUpdateTime - - server.lastWriteDate - - (this.primary.lastUpdateTime - this.primary.lastWriteDate) + - haInterval; - } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { - server.staleness = max - server.lastWriteDate + haInterval; - } -}; - -/** - * Recalculate all the staleness values for secodaries - * @method - */ -ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { - for (var i = 0; i < this.secondaries.length; i++) { - this.updateServerMaxStaleness(this.secondaries[i], haInterval); - } -}; - -/** - * Pick a server by the passed in ReadPreference - * @method - * @param {ReadPreference} readPreference The ReadPreference instance to use - */ -ReplSetState.prototype.pickServer = function(readPreference) { - // If no read Preference set to primary by default - readPreference = readPreference || ReadPreference.primary; - - // maxStalenessSeconds is not allowed with a primary read - if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { - return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); - } - - // Check if we have any non compatible servers for maxStalenessSeconds - var allservers = this.primary ? [this.primary] : []; - allservers = allservers.concat(this.secondaries); - - // Does any of the servers not support the right wire protocol version - // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out - if (readPreference.maxStalenessSeconds != null) { - for (var i = 0; i < allservers.length; i++) { - if (allservers[i].ismaster.maxWireVersion < 5) { - return new MongoError( - 'maxStalenessSeconds not supported by at least one of the replicaset members' - ); - } - } - } - - // Do we have the nearest readPreference - if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { - return pickNearest(this, readPreference); - } else if ( - readPreference.preference === 'nearest' && - readPreference.maxStalenessSeconds != null - ) { - return pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Get all the secondaries - var secondaries = this.secondaries; - - // Check if we can satisfy and of the basic read Preferences - if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { - return new MongoError('no secondary server available'); - } - - if ( - readPreference.equals(ReadPreference.secondaryPreferred) && - secondaries.length === 0 && - this.primary == null - ) { - return new MongoError('no secondary or primary server available'); - } - - if (readPreference.equals(ReadPreference.primary) && this.primary == null) { - return new MongoError('no primary server available'); - } - - // Secondary preferred or just secondaries - if ( - readPreference.equals(ReadPreference.secondaryPreferred) || - readPreference.equals(ReadPreference.secondary) - ) { - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - // Pick nearest of any other servers available - var server = pickNearest(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - // Pick nearest of any other servers available - server = pickNearestMaxStalenessSeconds(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } - - if (readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.primary; - } - - return null; - } - - // Primary preferred - if (readPreference.equals(ReadPreference.primaryPreferred)) { - server = null; - - // We prefer the primary if it's available - if (this.primary) { - return this.primary; - } - - // Pick a secondary - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - server = pickNearest(this, readPreference); - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - server = pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Did we find a server - if (server) return server; - } - - // Return the primary - return this.primary; -}; - -// -// Filter serves by tags -var filterByTags = function(readPreference, servers) { - if (readPreference.tags == null) return servers; - var filteredServers = []; - var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; - - // Iterate over the tags - for (var j = 0; j < tagsArray.length; j++) { - var tags = tagsArray[j]; - - // 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; -}; - -function pickNearestMaxStalenessSeconds(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Get the maxStalenessMS - var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; - - // Check if the maxStalenessMS > 90 seconds - if (maxStalenessMS < 90 * 1000) { - return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); - } - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Filter by latency - servers = servers.filter(function(s) { - return s.staleness <= maxStalenessMS; - }); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function pickNearest(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // Locate lowest time (picked servers are lowest time + acceptable Latency margin) - var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; - - // Filter by latency - servers = servers.filter(function(s) { - return s.lastIsMasterMS <= lowest + self.acceptableLatency; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function inList(ismaster, server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) - return true; - } - - return false; -} - -function addToList(self, type, ismaster, server, list) { - var serverName = server.name.toLowerCase(); - // Update set information about the server instance - self.set[serverName].type = type; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - // Add to the list - list.push(server); -} - -function compareObjectIds(id1, id2) { - var a = Buffer.from(id1.toHexString(), 'hex'); - var b = Buffer.from(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; -} - -function removeFrom(server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i].equals && list[i].equals(server)) { - list.splice(i, 1); - return true; - } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { - list.splice(i, 1); - return true; - } - } - - return false; -} - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - var setName = self.setName; - - if (self.hasPrimaryAndSecondary()) { - topology = 'ReplicaSetWithPrimary'; - } else if (!self.hasPrimary() && self.hasSecondary()) { - topology = 'ReplicaSetNoPrimary'; - } - - // Generate description - var description = { - topologyType: topology, - setName: setName, - servers: [] - }; - - // Add the primary to the list - if (self.hasPrimary()) { - var desc = self.primary.getDescription(); - desc.type = 'RSPrimary'; - description.servers.push(desc); - } - - // Add all the secondaries - description.servers = description.servers.concat( - self.secondaries.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Add all the arbiters - description.servers = description.servers.concat( - self.arbiters.map(function(x) { - var description = x.getDescription(); - description.type = 'RSArbiter'; - return description; - }) - ); - - // Add all the passives - description.servers = description.servers.concat( - self.passives.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.replicasetDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.replicasetDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - // if(diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - // } - - // Set the new description - self.replicasetDescription = description; - } -} - -module.exports = ReplSetState; diff --git a/node_modules/mongodb-core/lib/topologies/server.js b/node_modules/mongodb-core/lib/topologies/server.js deleted file mode 100644 index 43d1cfc4e5a9fa48875a4fbb9d9c66fd2878987b..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/topologies/server.js +++ /dev/null @@ -1,1117 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - EventEmitter = require('events').EventEmitter, - ReadPreference = require('./read_preference'), - Logger = require('../connection/logger'), - debugOptions = require('../connection/utils').debugOptions, - retrieveBSON = require('../connection/utils').retrieveBSON, - Pool = require('../connection/pool'), - Query = require('../connection/commands').Query, - MongoError = require('../error').MongoError, - MongoNetworkError = require('../error').MongoNetworkError, - TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support'), - ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support'), - BasicCursor = require('../cursor'), - sdam = require('./shared'), - createClientInfo = require('./shared').createClientInfo, - createCompressionInfo = require('./shared').createCompressionInfo, - resolveClusterTime = require('./shared').resolveClusterTime, - SessionMixins = require('./shared').SessionMixins, - relayEvents = require('../utils').relayEvents; - -const collationNotSupported = require('../utils').collationNotSupported; - -function getSaslSupportedMechs(options) { - if (!options) { - return {}; - } - - const authArray = options.auth || []; - const authMechanism = authArray[0] || options.authMechanism; - const authSource = authArray[1] || options.authSource || options.dbName || 'admin'; - const user = authArray[2] || options.user; - - if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { - return {}; - } - - if (!user) { - return {}; - } - - return { saslSupportedMechs: `${authSource}.${user}` }; -} - -function getDefaultAuthMechanism(ismaster) { - if (ismaster) { - // If ismaster contains saslSupportedMechs, use scram-sha-256 - // if it is available, else scram-sha-1 - if (Array.isArray(ismaster.saslSupportedMechs)) { - return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 - ? 'scram-sha-256' - : 'scram-sha-1'; - } - - // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 - if (ismaster.maxWireVersion >= 3) { - return 'scram-sha-1'; - } - } - - // Default for wireprotocol < 3 - return 'mongocr'; -} - -function extractIsMasterError(err, result) { - if (err) { - return err; - } - - if (result && result.result && result.result.ok === 0) { - return new MongoError(result.result); - } -} - -// Used for filtering out fields for loggin -var debugFields = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'singleBufferSerializtion', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'servername' -]; - -// Server instance id -var id = 0; -var serverAccounting = false; -var servers = {}; -var BSON = retrieveBSON(); - -/** - * 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 {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) - * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. - * @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=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation 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 {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Server} A cursor instance - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#reconnectFailed - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - * @fires Server#topologyOpening - * @fires Server#topologyClosed - * @fires Server#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Server = function(options) { - options = options || {}; - - // Add event listener - EventEmitter.call(this); - - // Server instance id - this.id = id++; - - // Internal state - this.s = { - // Options - options: options, - // Logger - logger: Logger('Server', options), - // Factory overrides - Cursor: options.cursorFactory || BasicCursor, - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Pool - pool: null, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Monitor thread (keeps the connection alive) - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, - // Is the server in a topology - inTopology: !!options.parent, - // Monitoring timeout - monitoringInterval: - typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, - // Topology id - topologyId: -1, - compression: { compressors: createCompressionInfo(options) }, - // Optional parent topology - parent: options.parent - }; - - // If this is a single deployment we need to track the clusterTime here - if (!this.s.parent) { - this.s.clusterTime = null; - } - - // Curent ismaster - this.ismaster = null; - // Current ping time - this.lastIsMasterMS = -1; - // The monitoringProcessId - this.monitoringProcessId = null; - // Initial connection - this.initialConnect = true; - // Wire protocol handler, default to oldest known protocol handler - // this gets changed when the first ismaster is called. - this.wireProtocolHandler = new TwoSixWireProtocolSupport(); - // Default type - this._type = 'server'; - // Set the client info - this.clientInfo = createClientInfo(options); - - // Max Stalleness values - // last time we updated the ismaster state - this.lastUpdateTime = 0; - // Last write time - this.lastWriteDate = 0; - // Stalleness - this.staleness = 0; -}; - -inherits(Server, EventEmitter); -Object.assign(Server.prototype, SessionMixins); - -Object.defineProperty(Server.prototype, 'type', { - enumerable: true, - get: function() { - return this._type; - } -}); - -Object.defineProperty(Server.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -// In single server deployments we track the clusterTime directly on the topology, however -// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the -// tracking objects so we can ensure we are gossiping the maximum time received from the -// server. -Object.defineProperty(Server.prototype, 'clusterTime', { - enumerable: true, - set: function(clusterTime) { - const settings = this.s.parent ? this.s.parent : this.s; - resolveClusterTime(settings, clusterTime); - }, - get: function() { - const settings = this.s.parent ? this.s.parent : this.s; - return settings.clusterTime || null; - } -}); - -Server.enableServerAccounting = function() { - serverAccounting = true; - servers = {}; -}; - -Server.disableServerAccounting = function() { - serverAccounting = false; -}; - -Server.servers = function() { - return servers; -}; - -Object.defineProperty(Server.prototype, 'name', { - enumerable: true, - get: function() { - return this.s.options.host + ':' + this.s.options.port; - } -}); - -function isSupportedServer(response) { - return response && typeof response.maxWireVersion === 'number' && response.maxWireVersion >= 2; -} - -function configureWireProtocolHandler(self, ismaster) { - // 3.2 wire protocol handler - if (ismaster.maxWireVersion >= 4) { - return new ThreeTwoWireProtocolSupport(); - } - - // default to 2.6 wire protocol handler - return new TwoSixWireProtocolSupport(); -} - -function disconnectHandler(self, type, ns, cmd, options, callback) { - // 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.s.pool.isConnected() && - self.s.options.reconnect && - self.s.disconnectHandler != null && - !options.monitoring - ) { - self.s.disconnectHandler.add(type, ns, cmd, options, callback); - return true; - } - - // If we have no connection error - if (!self.s.pool.isConnected()) { - callback(new MongoError(f('no connection available to server %s', self.name))); - return true; - } -} - -function monitoringProcess(self) { - return function() { - // Pool was destroyed do not continue process - if (self.s.pool.isDestroyed()) return; - // Emit monitoring Process event - self.emit('monitoring', self); - // Perform ismaster call - // Query options - var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; - // Create a query instance - var query = new Query(self.s.bson, 'admin.$cmd', { ismaster: true }, queryOptions); - // Get start time - var start = new Date().getTime(); - - // Execute the ismaster query - self.s.pool.write( - query, - { - socketTimeout: - typeof self.s.options.connectionTimeout !== 'number' - ? 2000 - : self.s.options.connectionTimeout, - monitoring: true - }, - function(err, result) { - // Set initial lastIsMasterMS - self.lastIsMasterMS = new Date().getTime() - start; - if (self.s.pool.isDestroyed()) return; - // Update the ismaster view if we have a result - if (result) { - self.ismaster = result.result; - } - // Re-schedule the monitoring process - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - ); - }; -} - -var eventHandler = function(self, event) { - return function(err) { - // Log information of received information if in info mode - if (self.s.logger.isInfo()) { - var object = err instanceof MongoError ? JSON.stringify(err) : {}; - self.s.logger.info( - f('server %s fired event %s out with message %s', self.name, event, object) - ); - } - - // Handle connect event - if (event === 'connect') { - // Issue an ismaster command at connect - // Query options - var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; - // Create a query instance - var compressors = - self.s.compression && self.s.compression.compressors ? self.s.compression.compressors : []; - var query = new Query( - self.s.bson, - 'admin.$cmd', - Object.assign( - { ismaster: true, client: self.clientInfo, compression: compressors }, - getSaslSupportedMechs(self.s.options) - ), - queryOptions - ); - // Get start time - var start = new Date().getTime(); - // Execute the ismaster query - self.s.pool.write( - query, - { - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, result) { - // Set initial lastIsMasterMS - self.lastIsMasterMS = new Date().getTime() - start; - - const serverError = extractIsMasterError(err, result); - - if (serverError) { - self.destroy(); - return self.emit('error', serverError); - } - - if (!isSupportedServer(result.result)) { - self.destroy(); - const latestSupportedVersion = '2.6'; - const message = - 'Server at ' + - self.s.options.host + - ':' + - self.s.options.port + - ' reports wire version ' + - (result.result.maxWireVersion || 0) + - ', but this version of Node.js Driver requires at least 2 (MongoDB' + - latestSupportedVersion + - ').'; - return self.emit('error', new MongoError(message), self); - } - - // Determine whether the server is instructing us to use a compressor - if (result.result && result.result.compression) { - for (var i = 0; i < self.s.compression.compressors.length; i++) { - if (result.result.compression.indexOf(self.s.compression.compressors[i]) > -1) { - self.s.pool.options.agreedCompressor = self.s.compression.compressors[i]; - break; - } - } - - if (self.s.compression.zlibCompressionLevel) { - self.s.pool.options.zlibCompressionLevel = self.s.compression.zlibCompressionLevel; - } - } - - // Ensure no error emitted after initial connect when reconnecting - self.initialConnect = false; - // Save the ismaster - self.ismaster = result.result; - - // It's a proxy change the type so - // the wireprotocol will send $readPreference - if (self.ismaster.msg === 'isdbgrid') { - self._type = 'mongos'; - } - // Add the correct wire protocol handler - self.wireProtocolHandler = configureWireProtocolHandler(self, self.ismaster); - // Have we defined self monitoring - if (self.s.monitoring) { - self.monitoringProcessId = setTimeout( - monitoringProcess(self), - self.s.monitoringInterval - ); - } - - // Emit server description changed if something listening - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - - if (!self.s.inTopology) { - // Emit topology description changed if something listening - sdam.emitTopologyDescriptionChanged(self, { - topologyType: 'Single', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - } - ] - }); - } - - // Log the ismaster if available - if (self.s.logger.isInfo()) { - self.s.logger.info( - f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) - ); - } - - // Emit connect - self.emit('connect', self); - } - ); - } else if ( - event === 'error' || - event === 'parseError' || - event === 'close' || - event === 'timeout' || - event === 'reconnect' || - event === 'attemptReconnect' || - 'reconnectFailed' - ) { - // Remove server instance from accounting - if ( - serverAccounting && - ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 - ) { - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - self.emit('topologyOpening', { topologyId: self.id }); - } - - delete servers[self.id]; - } - - if (event === 'close') { - // Closing emits a server description changed event going to unknown. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }); - } - - // Reconnect failed return error - if (event === 'reconnectFailed') { - self.emit('reconnectFailed', err); - // Emit error if any listeners - if (self.listeners('error').length > 0) { - self.emit('error', err); - } - // Terminate - return; - } - - // On first connect fail - if ( - self.s.pool.state === 'disconnected' && - self.initialConnect && - ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 - ) { - self.initialConnect = false; - return self.emit( - 'error', - new MongoNetworkError( - f('failed to connect to server [%s] on first connect [%s]', self.name, err) - ) - ); - } - - // Reconnect event, emit the server - if (event === 'reconnect') { - // Reconnecting emits a server description changed event going from unknown to the - // current server type. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - return self.emit(event, self); - } - - // Emit the event - self.emit(event, err); - } - }; -}; - -/** - * Initiate server connect - * @method - * @param {array} [options.auth=null] Array of auth options to apply on connect - */ -Server.prototype.connect = function(options) { - var self = this; - options = options || {}; - - // Set the connections - if (serverAccounting) servers[this.id] = this; - - // Do not allow connect to be called on anything that's not disconnected - if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { - throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); - } - - // Create a pool - self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); - - // Set up listeners - self.s.pool.on('close', eventHandler(self, 'close')); - self.s.pool.on('error', eventHandler(self, 'error')); - self.s.pool.on('timeout', eventHandler(self, 'timeout')); - self.s.pool.on('parseError', eventHandler(self, 'parseError')); - self.s.pool.on('connect', eventHandler(self, 'connect')); - self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); - self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); - - // Set up listeners for command monitoring - relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - this.emit('topologyOpening', { topologyId: self.id }); - } - - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name - }); - - // Connect with optional auth settings - if (options.auth) { - self.s.pool.connect.apply(self.s.pool, options.auth); - } else { - self.s.pool.connect(); - } -}; - -/** - * Get the server description - * @method - * @return {object} - */ -Server.prototype.getDescription = function() { - var ismaster = this.ismaster || {}; - var description = { - type: sdam.getTopologyType(this), - address: this.name - }; - - // Add fields if available - if (ismaster.hosts) description.hosts = ismaster.hosts; - if (ismaster.arbiters) description.arbiters = ismaster.arbiters; - if (ismaster.passives) description.passives = ismaster.passives; - if (ismaster.setName) description.setName = ismaster.setName; - return description; -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Server.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Server.prototype.unref = function() { - this.s.pool.unref(); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Server.prototype.isConnected = function() { - if (!this.s.pool) return false; - return this.s.pool.isConnected(); -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Server.prototype.isDestroyed = function() { - if (!this.s.pool) return false; - return this.s.pool.isDestroyed(); -}; - -function basicWriteValidations(self) { - if (!self.s.pool) return new MongoError('server instance is not connected'); - if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); -} - -function basicReadValidations(self, options) { - basicWriteValidations(self, options); - - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - throw new Error('readPreference must be an instance of ReadPreference'); - } -} - -/** - * 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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.command = function(ns, cmd, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicReadValidations(self, options); - if (result) return callback(result); - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // 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 - ) - ); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - self.wireProtocolHandler.command(self, 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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.insert = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - - // Execute write - return self.wireProtocolHandler.insert(self, 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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.update = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return self.wireProtocolHandler.update(self, 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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.remove = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return self.wireProtocolHandler.remove(self, ns, ops, options, callback); -}; - -/** - * Get a new cursor - * @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] Options for the cursor - * @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 {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Server.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); -}; - -/** - * Logout from a database - * @method - * @param {string} db The db we are logging out from - * @param {authResultCallback} callback A callback function - */ -Server.prototype.logout = function(dbName, callback) { - this.s.pool.logout(dbName, 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; - - if (mechanism === 'default') { - mechanism = getDefaultAuthMechanism(self.ismaster); - } - - // Slice all the arguments off - var args = Array.prototype.slice.call(arguments, 0); - // Set the mechanism - args[0] = mechanism; - // Get the callback - var callback = args[args.length - 1]; - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'auth', db, args, {}, callback)) { - return; - } - - // Do not authenticate if we are an arbiter - if (this.lastIsMaster() && this.lastIsMaster().arbiterOnly) { - return callback(null, true); - } - - // Apply the arguments to the pool - self.s.pool.auth.apply(self.s.pool, args); -}; - -/** - * 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 this.name.toLowerCase() === server.toLowerCase(); - if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); - return false; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Server.prototype.connections = function() { - return this.s.pool.allConnections(); -}; - -/** - * Selects a server - * @return {Server} - */ -Server.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - - callback(null, this); -}; - -var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; - -/** - * Destroy the server connection - * @method - * @param {boolean} [options.emitClose=false] Emit close event on destroy - * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy - * @param {boolean} [options.force=false] Force destroy the pool - */ -Server.prototype.destroy = function(options) { - if (this._destroyed) return; - - options = options || {}; - var self = this; - - // Set the connections - if (serverAccounting) delete servers[this.id]; - - // Destroy the monitoring process if any - if (this.monitoringProcessId) { - clearTimeout(this.monitoringProcessId); - } - - // No pool, return - if (!self.s.pool) { - this._destroyed = true; - return; - } - - // Emit close event - if (options.emitClose) { - self.emit('close', self); - } - - // Emit destroy event - if (options.emitDestroy) { - self.emit('destroy', self); - } - - // Remove all listeners - listeners.forEach(function(event) { - self.s.pool.removeAllListeners(event); - }); - - // Emit opening server event - if (self.listeners('serverClosed').length > 0) - self.emit('serverClosed', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name - }); - - // Emit toplogy opening event if not in topology - if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { - self.emit('topologyClosed', { topologyId: self.id }); - } - - if (self.s.logger.isDebug()) { - self.s.logger.debug(f('destroy called on server %s', self.name)); - } - - // Destroy the pool - this.s.pool.destroy(options.force); - this._destroyed = true; -}; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Server#connect - * @type {Server} - */ - -/** - * A server reconnect event, used to verify that the server topology has reconnected - * - * @event Server#reconnect - * @type {Server} - */ - -/** - * A server opening SDAM monitoring event - * - * @event Server#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Server#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Server#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Server#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Server#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Server#topologyDescriptionChanged - * @type {object} - */ - -/** - * Server reconnect failed - * - * @event Server#reconnectFailed - * @type {Error} - */ - -/** - * Server connection pool closed - * - * @event Server#close - * @type {object} - */ - -/** - * Server connection pool caused an error - * - * @event Server#error - * @type {Error} - */ - -/** - * Server destroyed was called - * - * @event Server#destroy - * @type {Server} - */ - -module.exports = Server; diff --git a/node_modules/mongodb-core/lib/topologies/shared.js b/node_modules/mongodb-core/lib/topologies/shared.js deleted file mode 100644 index 4cb72ea0d304eaa79de19ebdaaf11fc1c146ce0b..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/topologies/shared.js +++ /dev/null @@ -1,434 +0,0 @@ -'use strict'; - -const os = require('os'); -const f = require('util').format; -const ReadPreference = require('./read_preference'); -const Buffer = require('safe-buffer').Buffer; - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -// Get package.json variable -var driverVersion = require('../../package.json').version; -var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); -var type = os.type(); -var name = process.platform; -var architecture = process.arch; -var release = os.release(); - -function createClientInfo(options) { - // Build default client information - var clientInfo = options.clientInfo - ? clone(options.clientInfo) - : { - driver: { - name: 'nodejs-core', - version: driverVersion - }, - os: { - type: type, - name: name, - architecture: architecture, - version: release - } - }; - - // Is platform specified - if (clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') === -1) { - clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion); - } else if (!clientInfo.platform) { - clientInfo.platform = nodejsversion; - } - - // Do we have an application specific string - if (options.appname) { - // Cut at 128 bytes - var buffer = Buffer.from(options.appname); - // Return the truncated appname - var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname; - // Add to the clientInfo - clientInfo.application = { name: appname }; - } - - return clientInfo; -} - -function createCompressionInfo(options) { - if (!options.compression || !options.compression.compressors) { - return []; - } - - // Check that all supplied compressors are valid - options.compression.compressors.forEach(function(compressor) { - if (compressor !== 'snappy' && compressor !== 'zlib') { - throw new Error('compressors must be at least one of snappy or zlib'); - } - }); - - return options.compression.compressors; -} - -function clone(object) { - return JSON.parse(JSON.stringify(object)); -} - -var getPreviousDescription = function(self) { - if (!self.s.serverDescription) { - self.s.serverDescription = { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }; - } - - return self.s.serverDescription; -}; - -var emitServerDescriptionChanged = function(self, description) { - if (self.listeners('serverDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('serverDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var getPreviousTopologyDescription = function(self) { - if (!self.s.topologyDescription) { - self.s.topologyDescription = { - topologyType: 'Unknown', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - } - ] - }; - } - - return self.s.topologyDescription; -}; - -var emitTopologyDescriptionChanged = function(self, description) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('topologyDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousTopologyDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var changedIsMaster = function(self, currentIsmaster, ismaster) { - var currentType = getTopologyType(self, currentIsmaster); - var newType = getTopologyType(self, ismaster); - if (newType !== currentType) return true; - return false; -}; - -var getTopologyType = function(self, ismaster) { - if (!ismaster) { - ismaster = self.ismaster; - } - - if (!ismaster) return 'Unknown'; - if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; - if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; - if (ismaster.ismaster) return 'RSPrimary'; - if (ismaster.secondary) return 'RSSecondary'; - if (ismaster.arbiterOnly) return 'RSArbiter'; - return 'Unknown'; -}; - -var inquireServerState = function(self) { - return function(callback) { - if (self.s.state === 'destroyed') return; - // Record response time - var start = new Date().getTime(); - - // emitSDAMEvent - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); - - // Attempt to execute ismaster command - self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { - if (!err) { - // Legacy event sender - self.emit('ismaster', r, self); - - // Calculate latencyMS - var latencyMS = new Date().getTime() - start; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: self.name - }); - - // Did the server change - if (changedIsMaster(self, self.s.ismaster, r.result)) { - // Emit server description changed if something listening - emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) - }); - } - - // Updat ismaster view - self.s.ismaster = r.result; - - // Set server response time - self.s.isMasterLatencyMS = latencyMS; - } else { - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: self.name - }); - } - - // Peforming an ismaster monitoring callback operation - if (typeof callback === 'function') { - return callback(err, r); - } - - // Perform another sweep - self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); - }); - }; -}; - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for (var name in options) { - opts[name] = options[name]; - } - return opts; -}; - -function Interval(fn, time) { - var timer = false; - - this.start = function() { - if (!this.isRunning()) { - timer = setInterval(fn, time); - } - - return this; - }; - - this.stop = function() { - clearInterval(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - return timer !== false; - }; -} - -function Timeout(fn, time) { - var timer = false; - - this.start = function() { - if (!this.isRunning()) { - timer = setTimeout(fn, time); - } - return this; - }; - - this.stop = function() { - clearTimeout(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - if (timer && timer._called) return false; - return timer !== false; - }; -} - -function diff(previous, current) { - // Difference document - var diff = { - servers: [] - }; - - // Previous entry - if (!previous) { - previous = { servers: [] }; - } - - // Check if we have any previous servers missing in the current ones - for (var i = 0; i < previous.servers.length; i++) { - var found = false; - - for (var j = 0; j < current.servers.length; j++) { - if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { - found = true; - break; - } - } - - if (!found) { - // Add to the diff - diff.servers.push({ - address: previous.servers[i].address, - from: previous.servers[i].type, - to: 'Unknown' - }); - } - } - - // Check if there are any severs that don't exist - for (j = 0; j < current.servers.length; j++) { - found = false; - - // Go over all the previous servers - for (i = 0; i < previous.servers.length; i++) { - if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { - found = true; - break; - } - } - - // Add the server to the diff - if (!found) { - diff.servers.push({ - address: current.servers[j].address, - from: 'Unknown', - to: current.servers[j].type - }); - } - } - - // Got through all the servers - for (i = 0; i < previous.servers.length; i++) { - var prevServer = previous.servers[i]; - - // Go through all current servers - for (j = 0; j < current.servers.length; j++) { - var currServer = current.servers[j]; - - // Matching server - if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { - // We had a change in state - if (prevServer.type !== currServer.type) { - diff.servers.push({ - address: prevServer.address, - from: prevServer.type, - to: currServer.type - }); - } - } - } - } - - // Return difference - return diff; -} - -/** - * Shared function to determine clusterTime for a given topology - * - * @param {*} topology - * @param {*} clusterTime - */ -function resolveClusterTime(topology, $clusterTime) { - if (topology.clusterTime == null) { - topology.clusterTime = $clusterTime; - } else { - if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { - topology.clusterTime = $clusterTime; - } - } -} - -// NOTE: this is a temporary move until the topologies can be more formally refactored -// to share code. -const SessionMixins = { - endSessions: function(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - // TODO: - // When connected to a sharded cluster the endSessions command - // can be sent to any mongos. When connected to a replica set the - // endSessions command MUST be sent to the primary if the primary - // is available, otherwise it MUST be sent to any available secondary. - // Is it enough to use: ReadPreference.primaryPreferred ? - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { readPreference: ReadPreference.primaryPreferred }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } -}; - -const RETRYABLE_WIRE_VERSION = 6; - -/** - * Determines whether the provided topology supports retryable writes - * - * @param {Mongos|Replset} topology - */ -const isRetryableWritesSupported = function(topology) { - const maxWireVersion = topology.lastIsMaster().maxWireVersion; - if (maxWireVersion < RETRYABLE_WIRE_VERSION) { - return false; - } - - if (!topology.logicalSessionTimeoutMinutes) { - return false; - } - - return true; -}; - -module.exports.SessionMixins = SessionMixins; -module.exports.resolveClusterTime = resolveClusterTime; -module.exports.inquireServerState = inquireServerState; -module.exports.getTopologyType = getTopologyType; -module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; -module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; -module.exports.cloneOptions = cloneOptions; -module.exports.createClientInfo = createClientInfo; -module.exports.createCompressionInfo = createCompressionInfo; -module.exports.clone = clone; -module.exports.diff = diff; -module.exports.Interval = Interval; -module.exports.Timeout = Timeout; -module.exports.isRetryableWritesSupported = isRetryableWritesSupported; diff --git a/node_modules/mongodb-core/lib/transactions.js b/node_modules/mongodb-core/lib/transactions.js deleted file mode 100644 index 6453aea6efddd53dbd376b26366cf741b31a1e7d..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/transactions.js +++ /dev/null @@ -1,134 +0,0 @@ -'use strict'; -const MongoError = require('./error').MongoError; - -let TxnState; -let stateMachine; - -(() => { - const NO_TRANSACTION = 'NO_TRANSACTION'; - const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; - const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; - const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; - const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; - const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; - - TxnState = { - NO_TRANSACTION, - STARTING_TRANSACTION, - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - }; - - stateMachine = { - [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], - [STARTING_TRANSACTION]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - ], - [TRANSACTION_IN_PROGRESS]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_ABORTED - ], - [TRANSACTION_COMMITTED]: [ - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - STARTING_TRANSACTION, - NO_TRANSACTION - ], - [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], - [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] - }; -})(); - -/** - * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties - * of the data read from replica sets and replica set shards. - * @typedef {Object} ReadConcern - * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level - * @see https://docs.mongodb.com/manual/reference/read-concern/ - */ - -/** - * A MongoDB WriteConcern, which describes the level of acknowledgement - * requested from MongoDB for write operations. - * @typedef {Object} WriteConcern - * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has - * propagated to a specified number of mongod hosts - * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has - * been written to the journal - * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/ - */ - -/** - * Configuration options for a transaction. - * @typedef {Object} TransactionOptions - * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction - * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction - * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction - */ - -/** - * A class maintaining state related to a server transaction. Internal Only - * @ignore - */ -class Transaction { - /** - * Create a transaction - * - * @ignore - * @param {TransactionOptions} [options] Optional settings - */ - constructor(options) { - options = options || {}; - - this.state = TxnState.NO_TRANSACTION; - this.options = {}; - - if (options.writeConcern || typeof options.w !== 'undefined') { - const w = options.writeConcern ? options.writeConcern.w : options.w; - if (w <= 0) { - throw new MongoError('Transactions do not support unacknowledged write concern'); - } - - this.options.writeConcern = options.writeConcern ? options.writeConcern : { w: options.w }; - } - - if (options.readConcern) this.options.readConcern = options.readConcern; - if (options.readPreference) this.options.readPreference = options.readPreference; - } - - /** - * @ignore - * @return Whether this session is presently in a transaction - */ - get isActive() { - return ( - [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 - ); - } - - /** - * Transition the transaction in the state machine - * @ignore - * @param {TxnState} state The new state to transition to - */ - transition(nextState) { - const nextStates = stateMachine[this.state]; - if (nextStates && nextStates.indexOf(nextState) !== -1) { - this.state = nextState; - return; - } - - throw new MongoError( - `Attempted illegal state transition from [${this.state}] to [${nextState}]` - ); - } -} - -module.exports = { TxnState, Transaction }; diff --git a/node_modules/mongodb-core/lib/uri_parser.js b/node_modules/mongodb-core/lib/uri_parser.js deleted file mode 100644 index 7da1641b5a88e8a6b0dbe74514980055ab68aeaa..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/uri_parser.js +++ /dev/null @@ -1,536 +0,0 @@ -'use strict'; -const URL = require('url'); -const qs = require('querystring'); -const dns = require('dns'); -const MongoParseError = require('./error').MongoParseError; -const ReadPreference = require('./topologies/read_preference'); - -/** - * The following regular expression validates a connection string and breaks the - * provide string into the following capture groups: [protocol, username, password, hosts] - */ -const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; - -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -/** - * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal - * connection string. - * - * @param {string} uri The connection string to parse - * @param {object} options Optional user provided connection string options - * @param {function} callback - */ -function parseSrvConnectionString(uri, options, callback) { - const result = URL.parse(uri, true); - - if (result.hostname.split('.').length < 3) { - return callback(new MongoParseError('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - if (result.pathname && result.pathname.match(',')) { - return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); - } - - // Resolve the SRV record and use the result as the list of hosts to connect to. - const lookupAddress = result.host; - dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new MongoParseError('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback( - new MongoParseError('Server record does not share hostname with parent URI') - ); - } - } - - // Convert the original URL to a non-SRV URL. - result.protocol = 'mongodb'; - result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); - - // Default to SSL true if it's not specified. - if ( - !('ssl' in options) && - (!result.search || !('ssl' in result.query) || result.query.ssl === null) - ) { - result.query.ssl = true; - } - - // Resolve TXT record and add options from there if they exist. - dns.resolveTxt(lookupAddress, (err, record) => { - if (err) { - if (err.code !== 'ENODATA') { - return callback(err); - } - record = null; - } - - if (record) { - if (record.length > 1) { - return callback(new MongoParseError('Multiple text records not allowed')); - } - - record = qs.parse(record[0].join('')); - if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { - return callback( - new MongoParseError('Text record must only set `authSource` or `replicaSet`') - ); - } - - Object.assign(result.query, record); - } - - // Set completed options back into the URL object. - result.search = qs.stringify(result.query); - - const finalString = URL.format(result); - parseConnectionString(finalString, options, callback); - }); - }); -} - -/** - * Parses a query string item according to the connection string spec - * - * @param {string} key The key for the parsed value - * @param {Array|String} value The value to parse - * @return {Array|Object|String} The parsed value - */ -function parseQueryStringItemValue(key, value) { - if (Array.isArray(value)) { - // deduplicate and simplify arrays - value = value.filter((v, idx) => value.indexOf(v) === idx); - if (value.length === 1) value = value[0]; - } else if (value.indexOf(':') > 0) { - value = value.split(',').reduce((result, pair) => { - const parts = pair.split(':'); - result[parts[0]] = parseQueryStringItemValue(key, parts[1]); - return result; - }, {}); - } else if (value.indexOf(',') > 0) { - value = value.split(',').map(v => { - return parseQueryStringItemValue(key, v); - }); - } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { - value = value.toLowerCase() === 'true'; - } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { - const numericValue = parseFloat(value); - if (!Number.isNaN(numericValue)) { - value = parseFloat(value); - } - } - - return value; -} - -// Options that are known boolean types -const BOOLEAN_OPTIONS = new Set([ - 'slaveok', - 'slave_ok', - 'sslvalidate', - 'fsync', - 'safe', - 'retrywrites', - 'j' -]); - -// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` -const STRING_OPTIONS = new Set(['authsource', 'replicaset']); - -// Supported text representations of auth mechanisms -// NOTE: this list exists in native already, if it is merged here we should deduplicate -const AUTH_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-X509', - 'MONGODB-CR', - 'DEFAULT', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256', - 'PLAIN' -]); - -// Lookup table used to translate normalized (lower-cased) forms of connection string -// options to their expected camelCase version -const CASE_TRANSLATION = { - replicaset: 'replicaSet', - connecttimeoutms: 'connectTimeoutMS', - sockettimeoutms: 'socketTimeoutMS', - maxpoolsize: 'maxPoolSize', - minpoolsize: 'minPoolSize', - maxidletimems: 'maxIdleTimeMS', - waitqueuemultiple: 'waitQueueMultiple', - waitqueuetimeoutms: 'waitQueueTimeoutMS', - wtimeoutms: 'wtimeoutMS', - readconcern: 'readConcern', - readconcernlevel: 'readConcernLevel', - readpreference: 'readPreference', - maxstalenessseconds: 'maxStalenessSeconds', - readpreferencetags: 'readPreferenceTags', - authsource: 'authSource', - authmechanism: 'authMechanism', - authmechanismproperties: 'authMechanismProperties', - gssapiservicename: 'gssapiServiceName', - localthresholdms: 'localThresholdMS', - serverselectiontimeoutms: 'serverSelectionTimeoutMS', - serverselectiontryonce: 'serverSelectionTryOnce', - heartbeatfrequencyms: 'heartbeatFrequencyMS', - appname: 'appName', - retrywrites: 'retryWrites', - uuidrepresentation: 'uuidRepresentation', - zlibcompressionlevel: 'zlibCompressionLevel' -}; - -/** - * Sets the value for `key`, allowing for any required translation - * - * @param {object} obj The object to set the key on - * @param {string} key The key to set the value for - * @param {*} value The value to set - * @param {object} options The options used for option parsing - */ -function applyConnectionStringOption(obj, key, value, options) { - // simple key translation - if (key === 'journal') { - key = 'j'; - } else if (key === 'wtimeoutms') { - key = 'wtimeout'; - } - - // more complicated translation - if (BOOLEAN_OPTIONS.has(key)) { - value = value === 'true' || value === true; - } else if (key === 'appname') { - value = decodeURIComponent(value); - } else if (key === 'readconcernlevel') { - key = 'readconcern'; - value = { level: value }; - } - - // simple validation - if (key === 'compressors') { - value = Array.isArray(value) ? value : [value]; - - if (!value.every(c => c === 'snappy' || c === 'zlib')) { - throw new MongoParseError( - 'Value for `compressors` must be at least one of: `snappy`, `zlib`' - ); - } - } - - if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { - throw new MongoParseError( - 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' - ); - } - - if (key === 'readpreference' && !ReadPreference.isValid(value)) { - throw new MongoParseError( - 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' - ); - } - - if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { - throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); - } - - // special cases - if (key === 'compressors' || key === 'zlibcompressionlevel') { - obj.compression = obj.compression || {}; - obj = obj.compression; - } - - if (key === 'authmechanismproperties') { - if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; - if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; - if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { - obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; - } - } - - // set the actual value - if (options.caseTranslate && CASE_TRANSLATION[key]) { - obj[CASE_TRANSLATION[key]] = value; - return; - } - - obj[key] = value; -} - -const USERNAME_REQUIRED_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-CR', - 'PLAIN', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256' -]); - -/** - * Modifies the parsed connection string object taking into account expectations we - * have for authentication-related options. - * - * @param {object} parsed The parsed connection string result - * @return The parsed connection string result possibly modified for auth expectations - */ -function applyAuthExpectations(parsed) { - if (parsed.options == null) { - return; - } - - const options = parsed.options; - const authSource = options.authsource || options.authSource; - if (authSource != null) { - parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); - } - - const authMechanism = options.authmechanism || options.authMechanism; - if (authMechanism != null) { - if ( - USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && - (!parsed.auth || parsed.auth.username == null) - ) { - throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); - } - - if (authMechanism === 'GSSAPI') { - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'MONGODB-X509') { - if (parsed.auth && parsed.auth.password != null) { - throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); - } - - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'PLAIN') { - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - } - } - - // default to `admin` if nothing else was resolved - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); - } - - return parsed; -} - -/** - * Parses a query string according the connection string spec. - * - * @param {String} query The query string to parse - * @param {object} [options] The options used for options parsing - * @return {Object|Error} The parsed query string as an object, or an error if one was encountered - */ -function parseQueryString(query, options) { - const result = {}; - let parsedQueryString = qs.parse(query); - - for (const key in parsedQueryString) { - const value = parsedQueryString[key]; - if (value === '' || value == null) { - throw new MongoParseError('Incomplete key value pair for option'); - } - - const normalizedKey = key.toLowerCase(); - const parsedValue = parseQueryStringItemValue(normalizedKey, value); - applyConnectionStringOption(result, normalizedKey, parsedValue, options); - } - - // special cases for known deprecated options - if (result.wtimeout && result.wtimeoutms) { - delete result.wtimeout; - console.warn('Unsupported option `wtimeout` specified'); - } - - return Object.keys(result).length ? result : null; -} - -const PROTOCOL_MONGODB = 'mongodb'; -const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; -const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; - -/** - * Parses a MongoDB connection string - * - * @param {*} uri the MongoDB connection string to parse - * @param {object} [options] Optional settings. - * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization - * @param {parseCallback} callback - */ -function parseConnectionString(uri, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { caseTranslate: true }, options); - - // Check for bad uris before we parse - try { - URL.parse(uri); - } catch (e) { - return callback(new MongoParseError('URI malformed, cannot be parsed')); - } - - const cap = uri.match(HOSTS_RX); - if (!cap) { - return callback(new MongoParseError('Invalid connection string')); - } - - const protocol = cap[1]; - if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { - return callback(new MongoParseError('Invalid protocol provided')); - } - - if (protocol === PROTOCOL_MONGODB_SRV) { - return parseSrvConnectionString(uri, options, callback); - } - - const dbAndQuery = cap[4].split('?'); - const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; - const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; - - let parsedOptions; - try { - parsedOptions = parseQueryString(query, options); - } catch (parseError) { - return callback(parseError); - } - - parsedOptions = Object.assign({}, parsedOptions, options); - const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; - if (parsedOptions.auth) { - // maintain support for legacy options passed into `MongoClient` - if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; - if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; - if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; - } - - if (cap[4].split('?')[0].indexOf('@') !== -1) { - return callback(new MongoParseError('Unescaped slash in userinfo section')); - } - - const authorityParts = cap[3].split('@'); - if (authorityParts.length > 2) { - return callback(new MongoParseError('Unescaped at-sign in authority section')); - } - - if (authorityParts.length > 1) { - const authParts = authorityParts.shift().split(':'); - if (authParts.length > 2) { - return callback(new MongoParseError('Unescaped colon in authority section')); - } - - auth.username = qs.unescape(authParts[0]); - auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; - } - - let hostParsingError = null; - const hosts = authorityParts - .shift() - .split(',') - .map(host => { - let parsedHost = URL.parse(`mongodb://${host}`); - if (parsedHost.path === '/:') { - hostParsingError = new MongoParseError('Double colon in host identifier'); - return null; - } - - // heuristically determine if we're working with a domain socket - if (host.match(/\.sock/)) { - parsedHost.hostname = qs.unescape(host); - parsedHost.port = null; - } - - if (Number.isNaN(parsedHost.port)) { - hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); - return; - } - - const result = { - host: parsedHost.hostname, - port: parsedHost.port ? parseInt(parsedHost.port) : 27017 - }; - - if (result.port === 0) { - hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); - return; - } - - if (result.port > 65535) { - hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); - return; - } - - if (result.port < 0) { - hostParsingError = new MongoParseError('Invalid port (negative number)'); - return; - } - - return result; - }) - .filter(host => !!host); - - if (hostParsingError) { - return callback(hostParsingError); - } - - if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { - return callback(new MongoParseError('No hostname or hostnames provided in connection string')); - } - - const result = { - hosts: hosts, - auth: auth.db || auth.username ? auth : null, - options: Object.keys(parsedOptions).length ? parsedOptions : null - }; - - if (result.auth && result.auth.db) { - result.defaultDatabase = result.auth.db; - } - - try { - applyAuthExpectations(result); - } catch (authError) { - return callback(authError); - } - - callback(null, result); -} - -module.exports = parseConnectionString; diff --git a/node_modules/mongodb-core/lib/utils.js b/node_modules/mongodb-core/lib/utils.js deleted file mode 100644 index 486e268f29b575eb7c58d52017267f60afb4b4ab..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/utils.js +++ /dev/null @@ -1,97 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const requireOptional = require('require_optional'); - -/** - * Generate a UUIDv4 - */ -const uuidV4 = () => { - const result = crypto.randomBytes(16); - result[6] = (result[6] & 0x0f) | 0x40; - result[8] = (result[8] & 0x3f) | 0x80; - return result; -}; - -/** - * Returns the duration calculated from two high resolution timers in milliseconds - * - * @param {Object} started A high resolution timestamp created from `process.hrtime()` - * @returns {Number} The duration in milliseconds - */ -const calculateDurationInMs = started => { - const hrtime = process.hrtime(started); - return (hrtime[0] * 1e9 + hrtime[1]) / 1e6; -}; - -/** - * Relays events for a given listener and emitter - * - * @param {EventEmitter} listener the EventEmitter to listen to the events from - * @param {EventEmitter} emitter the EventEmitter to relay the events to - */ -function relayEvents(listener, emitter, events) { - events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); -} - -function retrieveKerberos() { - let kerberos; - - try { - kerberos = requireOptional('kerberos'); - } catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - throw new Error('The `kerberos` module was not found. Please install it and try again.'); - } - - throw err; - } - - return kerberos; -} - -// Throw an error if an attempt to use EJSON is made when it is not installed -const noEJSONError = function() { - throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); -}; - -// Facilitate loading EJSON optionally -function retrieveEJSON() { - let EJSON = null; - try { - EJSON = requireOptional('mongodb-extjson'); - } catch (error) {} // eslint-disable-line - if (!EJSON) { - EJSON = { - parse: noEJSONError, - deserialize: noEJSONError, - serialize: noEJSONError, - stringify: noEJSONError, - setBSONModule: noEJSONError, - BSON: noEJSONError - }; - } - - return EJSON; -} - -/* - * Checks that collation is supported by server. - * - * @param {Server} [server] to check against - * @param {object} [cmd] object where collation may be specified - * @param {function} [callback] callback function - * @return true if server does not support collation - */ -function collationNotSupported(server, cmd) { - return cmd && cmd.collation && server.ismaster && server.ismaster.maxWireVersion < 5; -} - -module.exports = { - uuidV4, - calculateDurationInMs, - relayEvents, - collationNotSupported, - retrieveEJSON, - retrieveKerberos -}; diff --git a/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js deleted file mode 100644 index 931aadaf3f211054b61a252a80fee8c2609f35dd..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js +++ /dev/null @@ -1,267 +0,0 @@ -'use strict'; - -const retrieveBSON = require('../connection/utils').retrieveBSON; -const KillCursor = require('../connection/commands').KillCursor; -const GetMore = require('../connection/commands').GetMore; -const Query = require('../connection/commands').Query; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const isMongos = require('./shared').isMongos; -const databaseNamespace = require('./shared').databaseNamespace; -const collectionNamespace = require('./shared').collectionNamespace; - -const BSON = retrieveBSON(); -const Long = BSON.Long; - -class WireProtocol { - insert(server, ns, ops, options, callback) { - executeWrite(this, server, 'insert', 'documents', ns, ops, options, callback); - } - - update(server, ns, ops, options, callback) { - executeWrite(this, server, 'update', 'updates', ns, ops, options, callback); - } - - remove(server, ns, ops, options, callback) { - executeWrite(this, server, 'delete', 'deletes', ns, ops, options, callback); - } - - killCursor(server, ns, cursorState, callback) { - const bson = server.s.bson; - const pool = server.s.pool; - const cursorId = cursorState.cursorId; - const killCursor = new KillCursor(bson, ns, [cursorId]); - const options = { - immediateRelease: true, - noResponse: true - }; - - if (typeof cursorState.session === 'object') { - options.session = cursorState.session; - } - - if (pool && pool.isConnected()) { - try { - pool.write(killCursor, options, callback); - } catch (err) { - if (typeof callback === 'function') { - callback(err, null); - } else { - console.warn(err); - } - } - } - } - - getMore(server, ns, cursorState, batchSize, options, callback) { - const bson = server.s.bson; - const getMore = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); - function queryCallback(err, result) { - if (err) return callback(err); - const response = result.message; - - // If we have a timed out query or a cursor that was killed - if (response.cursorNotFound) { - return callback(new MongoError('Cursor does not exist, was killed, or timed out'), null); - } - - const cursorId = - typeof response.cursorId === 'number' - ? Long.fromNumber(response.cursorId) - : response.cursorId; - - cursorState.documents = response.documents; - cursorState.cursorId = cursorId; - - callback(null, null, response.connection); - } - - const queryOptions = applyCommonQueryOptions({}, cursorState); - server.s.pool.write(getMore, queryOptions, queryCallback); - } - - query(server, ns, cmd, cursorState, options, callback) { - if (cursorState.cursorId != null) { - return; - } - - const query = setupClassicFind(server, ns, cmd, cursorState, options); - const queryOptions = applyCommonQueryOptions({}, cursorState); - if (typeof query.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = query.documentsReturnedIn; - } - - server.s.pool.write(query, queryOptions, callback); - } - - command(server, ns, cmd, options, callback) { - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - options = options || {}; - const bson = server.s.bson; - const pool = server.s.pool; - const readPreference = getReadPreference(cmd, options); - - let finalCmd = Object.assign({}, cmd); - if (finalCmd.readConcern) { - if (finalCmd.readConcern.level !== 'local') { - return callback( - new MongoError( - `server ${JSON.stringify(finalCmd)} command does not support a readConcern level of ${ - finalCmd.readConcern.level - }` - ) - ); - } - - delete finalCmd['readConcern']; - } - - if (isMongos(server) && readPreference && readPreference.preference !== 'primary') { - finalCmd = { - $query: finalCmd, - $readPreference: readPreference.toJSON() - }; - } - - const commandOptions = Object.assign( - { - command: true, - numberToSkip: 0, - numberToReturn: -1, - checkKeys: false - }, - options - ); - - // This value is not overridable - commandOptions.slaveOk = readPreference.slaveOk(); - - try { - const query = new Query(bson, `${databaseNamespace(ns)}.$cmd`, finalCmd, commandOptions); - pool.write(query, commandOptions, callback); - } catch (err) { - callback(err); - } - } -} - -function executeWrite(handler, server, 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 = {}; - options = options || {}; - } - - const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; - const writeConcern = options.writeConcern; - - const writeCommand = {}; - writeCommand[type] = collectionNamespace(ns); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - - if (writeConcern && Object.keys(writeConcern).length > 0) { - writeCommand.writeConcern = writeConcern; - } - - if (options.bypassDocumentValidation === true) { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - const commandOptions = Object.assign( - { - checkKeys: type === 'insert', - numberToReturn: 1 - }, - options - ); - - handler.command(server, ns, writeCommand, commandOptions, callback); -} - -function setupClassicFind(server, ns, cmd, cursorState, options) { - options = options || {}; - const bson = server.s.bson; - const readPreference = getReadPreference(cmd, options); - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - - let numberToReturn = 0; - 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; - } - - const numberToSkip = cursorState.skip || 0; - - const findCmd = {}; - if (isMongos(server) && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - } - - if (cmd.sort) findCmd['$orderby'] = cmd.sort; - if (cmd.hint) findCmd['$hint'] = cmd.hint; - if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; - if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; - if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; - if (cmd.min) findCmd['$min'] = cmd.min; - if (cmd.max) findCmd['$max'] = cmd.max; - if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; - if (cmd.comment) findCmd['$comment'] = cmd.comment; - if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; - if (cmd.explain) { - // nToReturn must be 0 (match all) or negative (match N and close cursor) - // nToReturn > 0 will give explain results equivalent to limit(0) - numberToReturn = -Math.abs(cmd.limit || 0); - findCmd['$explain'] = true; - } - - findCmd['$query'] = cmd.query; - if (cmd.readConcern && cmd.readConcern.level !== 'local') { - throw new MongoError( - `server find command does not support a readConcern level of ${cmd.readConcern.level}` - ); - } - - if (cmd.readConcern) { - cmd = Object.assign({}, cmd); - delete cmd['readConcern']; - } - - const serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - - const query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, - numberToReturn: numberToReturn, - pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, - checkKeys: false, - returnFieldSelector: cmd.fields, - serializeFunctions: serializeFunctions, - ignoreUndefined: ignoreUndefined - }); - - 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.partial === 'boolean') query.partial = cmd.partial; - - query.slaveOk = readPreference.slaveOk(); - return query; -} - -module.exports = WireProtocol; diff --git a/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js deleted file mode 100644 index bba1d222885286cafabe2346895e07013386d22b..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js +++ /dev/null @@ -1,397 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const getReadPreference = require('./shared').getReadPreference; -const BSON = retrieveBSON(); -const Long = BSON.Long; -const ReadPreference = require('../topologies/read_preference'); -const TxnState = require('../transactions').TxnState; -const isMongos = require('./shared').isMongos; -const databaseNamespace = require('./shared').databaseNamespace; -const collectionNamespace = require('./shared').collectionNamespace; - -class WireProtocol { - insert(server, ns, ops, options, callback) { - executeWrite(this, server, 'insert', 'documents', ns, ops, options, callback); - } - - update(server, ns, ops, options, callback) { - executeWrite(this, server, 'update', 'updates', ns, ops, options, callback); - } - - remove(server, ns, ops, options, callback) { - executeWrite(this, server, 'delete', 'deletes', ns, ops, options, callback); - } - - killCursor(server, ns, cursorState, callback) { - callback = typeof callback === 'function' ? callback : () => {}; - const cursorId = cursorState.cursorId; - const killCursorCmd = { - killCursors: collectionNamespace(ns), - cursors: [cursorId] - }; - - const options = {}; - if (typeof cursorState.session === 'object') options.session = cursorState.session; - - this.command(server, ns, killCursorCmd, options, (err, result) => { - if (err) { - return callback(err); - } - - const response = result.message; - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (!Array.isArray(response.documents) || response.documents.length === 0) { - return callback( - new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) - ); - } - - callback(null, response.documents[0]); - }); - } - - getMore(server, ns, cursorState, batchSize, options, callback) { - options = options || {}; - const getMoreCmd = { - getMore: cursorState.cursorId, - collection: collectionNamespace(ns), - batchSize: Math.abs(batchSize) - }; - - if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { - getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; - } - - function queryCallback(err, result) { - if (err) return callback(err); - const response = result.message; - - // If we have a timed out query or a cursor that was killed - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - // Raw, return all the extracted documents - if (cursorState.raw) { - cursorState.documents = response.documents; - cursorState.cursorId = response.cursorId; - return callback(null, response.documents); - } - - // We have an error detected - if (response.documents[0].ok === 0) { - return callback(new MongoError(response.documents[0])); - } - - // Ensure we have a Long valid cursor id - const cursorId = - typeof response.documents[0].cursor.id === 'number' - ? Long.fromNumber(response.documents[0].cursor.id) - : response.documents[0].cursor.id; - - cursorState.documents = response.documents[0].cursor.nextBatch; - cursorState.cursorId = cursorId; - - callback(null, response.documents[0], response.connection); - } - - const commandOptions = Object.assign( - { - returnFieldSelector: null, - documentsReturnedIn: 'nextBatch' - }, - options - ); - - this.command(server, ns, getMoreCmd, commandOptions, queryCallback); - } - - query(server, ns, cmd, cursorState, options, callback) { - options = options || {}; - if (cursorState.cursorId != null) { - return callback(); - } - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - const readPreference = getReadPreference(cmd, options); - const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); - - // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this - // side-effect. Change this ASAP - cmd.virtual = false; - - const commandOptions = Object.assign( - { - documentsReturnedIn: 'firstBatch', - numberToReturn: 1, - slaveOk: readPreference.slaveOk() - }, - options - ); - - if (cmd.readPreference) commandOptions.readPreference = readPreference; - this.command(server, ns, findCmd, commandOptions, callback); - } - - command(server, ns, cmd, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - const bson = server.s.bson; - const pool = server.s.pool; - const readPreference = getReadPreference(cmd, options); - - let finalCmd = Object.assign({}, cmd); - if (isMongos(server) && readPreference && readPreference.preference !== 'primary') { - finalCmd = { - $query: finalCmd, - $readPreference: readPreference.toJSON() - }; - } - - const err = decorateWithSessionsData(finalCmd, options.session, options); - if (err) { - return callback(err); - } - - const commandOptions = Object.assign( - { - command: true, - numberToSkip: 0, - numberToReturn: -1, - checkKeys: false - }, - options - ); - - // This value is not overridable - commandOptions.slaveOk = readPreference.slaveOk(); - - try { - const query = new Query(bson, `${databaseNamespace(ns)}.$cmd`, finalCmd, commandOptions); - pool.write(query, commandOptions, callback); - } catch (err) { - callback(err); - } - } -} - -function isTransactionCommand(command) { - return !!(command.commitTransaction || command.abortTransaction); -} - -/** - * Optionally decorate a command with sessions specific keys - * - * @param {Object} command the command to decorate - * @param {ClientSession} session the session tracking transaction state - * @param {Object} [options] Optional settings passed to calling operation - * @param {Function} [callback] Optional callback passed from calling operation - * @return {MongoError|null} An error, if some error condition was met - */ -function decorateWithSessionsData(command, session, options) { - if (!session) { - return; - } - - // first apply non-transaction-specific sessions data - const serverSession = session.serverSession; - const inTransaction = session.inTransaction() || isTransactionCommand(command); - const isRetryableWrite = options.willRetryWrite; - - if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { - command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); - } - - // now attempt to apply transaction-specific sessions data - if (!inTransaction) { - if (session.transaction.state !== TxnState.NO_TRANSACTION) { - session.transaction.transition(TxnState.NO_TRANSACTION); - } - - // for causal consistency - if (session.supports.causalConsistency && session.operationTime) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - - return; - } - - if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { - return new MongoError( - `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` - ); - } - - // `autocommit` must always be false to differentiate from retryable writes - command.autocommit = false; - - if (session.transaction.state === TxnState.STARTING_TRANSACTION) { - session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); - command.startTransaction = true; - - const readConcern = - session.transaction.options.readConcern || session.clientOptions.readConcern; - if (readConcern) { - command.readConcern = readConcern; - } - - if (session.supports.causalConsistency && session.operationTime) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - } -} - -function executeWrite(handler, server, 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 = {}; - options = options || {}; - } - - const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; - const writeConcern = options.writeConcern; - - const writeCommand = {}; - writeCommand[type] = collectionNamespace(ns); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - - if (writeConcern && Object.keys(writeConcern).length > 0) { - writeCommand.writeConcern = writeConcern; - } - - if (options.collation) { - for (let i = 0; i < writeCommand[opsField].length; i++) { - if (!writeCommand[opsField][i].collation) { - writeCommand[opsField][i].collation = options.collation; - } - } - } - - if (options.bypassDocumentValidation === true) { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - const commandOptions = Object.assign( - { - checkKeys: type === 'insert', - numberToReturn: 1 - }, - options - ); - - handler.command(server, ns, writeCommand, commandOptions, callback); -} - -function prepareFindCommand(server, ns, cmd, cursorState) { - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - let findCmd = { - find: collectionNamespace(ns) - }; - - if (cmd.query) { - if (cmd.query['$query']) { - findCmd.filter = cmd.query['$query']; - } else { - findCmd.filter = cmd.query; - } - } - - let sortValue = cmd.sort; - if (Array.isArray(sortValue)) { - const sortObject = {}; - - if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { - let sortDirection = sortValue[1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[0]] = sortDirection; - } else { - for (let i = 0; i < sortValue.length; i++) { - let sortDirection = sortValue[i][1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[i][0]] = sortDirection; - } - } - - sortValue = sortObject; - } - - if (cmd.sort) findCmd.sort = sortValue; - if (cmd.fields) findCmd.projection = cmd.fields; - if (cmd.hint) findCmd.hint = cmd.hint; - if (cmd.skip) findCmd.skip = cmd.skip; - if (cmd.limit) findCmd.limit = cmd.limit; - if (cmd.limit < 0) { - findCmd.limit = Math.abs(cmd.limit); - findCmd.singleBatch = true; - } - - if (typeof cmd.batchSize === 'number') { - if (cmd.batchSize < 0) { - if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { - findCmd.limit = Math.abs(cmd.batchSize); - } - - findCmd.singleBatch = true; - } - - findCmd.batchSize = Math.abs(cmd.batchSize); - } - - if (cmd.comment) findCmd.comment = cmd.comment; - if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; - if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; - if (cmd.min) findCmd.min = cmd.min; - if (cmd.max) findCmd.max = cmd.max; - findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false; - findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false; - if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; - if (cmd.tailable) findCmd.tailable = cmd.tailable; - if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; - if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; - if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; - if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; - if (cmd.partial) findCmd.partial = cmd.partial; - if (cmd.collation) findCmd.collation = cmd.collation; - if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; - - // If we have explain, we need to rewrite the find command - // to wrap it in the explain command - if (cmd.explain) { - findCmd = { - explain: findCmd - }; - } - - return findCmd; -} - -module.exports = WireProtocol; diff --git a/node_modules/mongodb-core/lib/wireprotocol/compression.js b/node_modules/mongodb-core/lib/wireprotocol/compression.js deleted file mode 100644 index 4b908e630270d44d92e775f61a6cb3c3f95cb115..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/wireprotocol/compression.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -var Snappy = require('../connection/utils').retrieveSnappy(), - zlib = require('zlib'); - -var compressorIDs = { - snappy: 1, - zlib: 2 -}; - -var uncompressibleCommands = [ - 'ismaster', - 'saslStart', - 'saslContinue', - 'getnonce', - 'authenticate', - 'createUser', - 'updateUser', - 'copydbSaslStart', - 'copydbgetnonce', - 'copydb' -]; - -// Facilitate compressing a message using an agreed compressor -var compress = function(self, dataToBeCompressed, callback) { - switch (self.options.agreedCompressor) { - case 'snappy': - Snappy.compress(dataToBeCompressed, callback); - break; - case 'zlib': - // Determine zlibCompressionLevel - var zlibOptions = {}; - if (self.options.zlibCompressionLevel) { - zlibOptions.level = self.options.zlibCompressionLevel; - } - zlib.deflate(dataToBeCompressed, zlibOptions, callback); - break; - default: - throw new Error( - 'Attempt to compress message using unknown compressor "' + - self.options.agreedCompressor + - '".' - ); - } -}; - -// Decompress a message using the given compressor -var decompress = function(compressorID, compressedData, callback) { - if (compressorID < 0 || compressorID > compressorIDs.length) { - throw new Error( - 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + - compressorID + - ')' - ); - } - switch (compressorID) { - case compressorIDs.snappy: - Snappy.uncompress(compressedData, callback); - break; - case compressorIDs.zlib: - zlib.inflate(compressedData, callback); - break; - default: - callback(null, compressedData); - } -}; - -module.exports = { - compressorIDs: compressorIDs, - uncompressibleCommands: uncompressibleCommands, - compress: compress, - decompress: decompress -}; diff --git a/node_modules/mongodb-core/lib/wireprotocol/shared.js b/node_modules/mongodb-core/lib/wireprotocol/shared.js deleted file mode 100644 index 23da8b95dd7186252368c7e9d00abe122dccda41..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/lib/wireprotocol/shared.js +++ /dev/null @@ -1,101 +0,0 @@ -'use strict'; - -var ReadPreference = require('../topologies/read_preference'), - MongoError = require('../error').MongoError; - -var MESSAGE_HEADER_SIZE = 16; - -// OPCODE Numbers -// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes -var opcodes = { - OP_REPLY: 1, - OP_UPDATE: 2001, - OP_INSERT: 2002, - OP_QUERY: 2004, - OP_GETMORE: 2005, - OP_DELETE: 2006, - OP_KILL_CURSORS: 2007, - OP_COMPRESSED: 2012 -}; - -var getReadPreference = function(cmd, options) { - // Default to command version of the readPreference - var readPreference = cmd.readPreference || new ReadPreference('primary'); - // If we have an option readPreference override the command one - if (options.readPreference) { - readPreference = options.readPreference; - } - - if (typeof readPreference === 'string') { - readPreference = new ReadPreference(readPreference); - } - - if (!(readPreference instanceof ReadPreference)) { - throw new MongoError('read preference must be a ReadPreference instance'); - } - - return readPreference; -}; - -// Parses the header of a wire protocol message -var parseHeader = function(message) { - return { - length: message.readInt32LE(0), - requestId: message.readInt32LE(4), - responseTo: message.readInt32LE(8), - opCode: message.readInt32LE(12) - }; -}; - -function applyCommonQueryOptions(queryOptions, options) { - Object.assign(queryOptions, { - raw: typeof options.raw === 'boolean' ? options.raw : false, - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, - fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false - }); - - if (typeof options.socketTimeout === 'number') { - queryOptions.socketTimeout = options.socketTimeout; - } - - if (options.session) { - queryOptions.session = options.session; - } - - if (typeof options.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = options.documentsReturnedIn; - } - - return queryOptions; -} - -function isMongos(server) { - if (server.type === 'mongos') return true; - if (server.parent && server.parent.type === 'mongos') return true; - // NOTE: handle unified topology - return false; -} - -function databaseNamespace(ns) { - return ns.split('.')[0]; -} -function collectionNamespace(ns) { - return ns - .split('.') - .slice(1) - .join('.'); -} - -module.exports = { - getReadPreference, - MESSAGE_HEADER_SIZE, - opcodes, - parseHeader, - applyCommonQueryOptions, - isMongos, - databaseNamespace, - collectionNamespace -}; diff --git a/node_modules/mongodb-core/package.json b/node_modules/mongodb-core/package.json deleted file mode 100644 index 00a65d1f559129e8a266c56ebf3a881f3df5e679..0000000000000000000000000000000000000000 --- a/node_modules/mongodb-core/package.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "_from": "mongodb-core@3.1.11", - "_id": "mongodb-core@3.1.11", - "_inBundle": false, - "_integrity": "sha512-rD2US2s5qk/ckbiiGFHeu+yKYDXdJ1G87F6CG3YdaZpzdOm5zpoAZd/EKbPmFO6cQZ+XVXBXBJ660sSI0gc6qg==", - "_location": "/mongodb-core", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mongodb-core@3.1.11", - "name": "mongodb-core", - "escapedName": "mongodb-core", - "rawSpec": "3.1.11", - "saveSpec": null, - "fetchSpec": "3.1.11" - }, - "_requiredBy": [ - "/mongodb", - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-3.1.11.tgz", - "_shasum": "b253038dbb4d7329f3d1c2ee5400bb0c9221fde5", - "_spec": "mongodb-core@3.1.11", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongoose", - "author": { - "name": "Christian Kvalheim" - }, - "bugs": { - "url": "https://github.com/mongodb-js/mongodb-core/issues" - }, - "bundleDependencies": false, - "dependencies": { - "bson": "^1.1.0", - "require_optional": "^1.0.1", - "safe-buffer": "^5.1.2", - "saslprep": "^1.0.0" - }, - "deprecated": false, - "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", - "devDependencies": { - "chai": "^4.1.2", - "chai-subset": "^1.6.0", - "co": "^4.6.0", - "eslint": "^4.6.1", - "eslint-plugin-prettier": "^2.2.0", - "jsdoc": "3.5.4", - "mongodb-extjson": "^2.1.2", - "mongodb-mock-server": "^1.0.0", - "mongodb-test-runner": "^1.1.18", - "prettier": "~1.12.0", - "sinon": "^6.0.0", - "snappy": "^6.1.1", - "standard-version": "^4.4.0" - }, - "files": [ - "index.js", - "lib" - ], - "homepage": "https://github.com/mongodb-js/mongodb-core", - "keywords": [ - "mongodb", - "core" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "mongodb-core", - "optionalDependencies": { - "saslprep": "^1.0.0" - }, - "peerOptionalDependencies": { - "kerberos": "^1.0.0", - "mongodb-extjson": "^2.1.2", - "snappy": "^6.1.1", - "bson-ext": "^2.0.0" - }, - "repository": { - "type": "git", - "url": "git://github.com/mongodb-js/mongodb-core.git" - }, - "scripts": { - "atlas": "node ./test/atlas.js", - "changelog": "conventional-changelog -p angular -i HISTORY.md -s", - "coverage": "nyc node test/runner.js -t functional -l && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write index.js test/**/*.js lib/**/*.js", - "lint": "eslint index.js lib test", - "release": "standard-version -i HISTORY.md", - "test": "npm run lint && mongodb-test-runner -t 60000 test/tests" - }, - "version": "3.1.11" -} diff --git a/node_modules/mongodb/HISTORY.md b/node_modules/mongodb/HISTORY.md deleted file mode 100644 index 2e19fb919de6106a230a9104dde96393ad098026..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/HISTORY.md +++ /dev/null @@ -1,2226 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -<a name="3.1.13"></a> -## [3.1.13](https://github.com/mongodb/node-mongodb-native/compare/v3.1.12...v3.1.13) (2019-01-23) - - -### Bug Fixes - -* restore ability to webpack by removing `makeLazyLoader` ([050267d](https://github.com/mongodb/node-mongodb-native/commit/050267d)) -* **bulk:** honor ignoreUndefined in initializeUnorderedBulkOp ([e806be4](https://github.com/mongodb/node-mongodb-native/commit/e806be4)) -* **changeStream:** properly handle changeStream event mid-close ([#1902](https://github.com/mongodb/node-mongodb-native/issues/1902)) ([5ad9fa9](https://github.com/mongodb/node-mongodb-native/commit/5ad9fa9)) -* **db_ops:** ensure we async resolve errors in createCollection ([210c71d](https://github.com/mongodb/node-mongodb-native/commit/210c71d)) - - - -<a name="3.1.12"></a> -## [3.1.12](https://github.com/mongodb/node-mongodb-native/compare/v3.1.11...v3.1.12) (2019-01-16) - - -### Features - -* **core:** update to mongodb-core v3.1.11 ([9bef6e7](https://github.com/mongodb/node-mongodb-native/commit/9bef6e7)) - - - -<a name="3.1.11"></a> -## [3.1.11](https://github.com/mongodb/node-mongodb-native/compare/v3.1.10...v3.1.11) (2019-01-15) - - -### Bug Fixes - -* **bulk:** fix error propagation in empty bulk.execute ([a3adb3f](https://github.com/mongodb/node-mongodb-native/commit/a3adb3f)) -* **bulk:** make sure that any error in bulk write is propagated ([bedc2d2](https://github.com/mongodb/node-mongodb-native/commit/bedc2d2)) -* **bulk:** properly calculate batch size for bulk writes ([aafe71b](https://github.com/mongodb/node-mongodb-native/commit/aafe71b)) -* **operations:** do not call require in a hot path ([ff82ff4](https://github.com/mongodb/node-mongodb-native/commit/ff82ff4)) - - - -<a name="3.1.10"></a> -## [3.1.10](https://github.com/mongodb/node-mongodb-native/compare/v3.1.9...v3.1.10) (2018-11-16) - - -### Bug Fixes - -* **auth:** remember to default to admin database ([c7dec28](https://github.com/mongodb/node-mongodb-native/commit/c7dec28)) - - -### Features - -* **core:** update to mongodb-core v3.1.9 ([bd3355b](https://github.com/mongodb/node-mongodb-native/commit/bd3355b)) - - - -<a name="3.1.9"></a> -## [3.1.9](https://github.com/mongodb/node-mongodb-native/compare/v3.1.8...v3.1.9) (2018-11-06) - - -### Bug Fixes - -* **db:** move db constants to other file to avoid circular ref ([#1858](https://github.com/mongodb/node-mongodb-native/issues/1858)) ([239036f](https://github.com/mongodb/node-mongodb-native/commit/239036f)) -* **estimated-document-count:** support options other than maxTimeMs ([36c3c7d](https://github.com/mongodb/node-mongodb-native/commit/36c3c7d)) - - -### Features - -* **core:** update to mongodb-core v3.1.8 ([80d7c79](https://github.com/mongodb/node-mongodb-native/commit/80d7c79)) - - - -<a name="3.1.8"></a> -## [3.1.8](https://github.com/mongodb/node-mongodb-native/compare/v3.1.7...v3.1.8) (2018-10-10) - - -### Bug Fixes - -* **connect:** use reported default databse from new uri parser ([811f8f8](https://github.com/mongodb/node-mongodb-native/commit/811f8f8)) - - -### Features - -* **core:** update to mongodb-core v3.1.7 ([dbfc905](https://github.com/mongodb/node-mongodb-native/commit/dbfc905)) - - - -<a name="3.1.7"></a> -## [3.1.7](https://github.com/mongodb/node-mongodb-native/compare/v3.1.6...v3.1.7) (2018-10-09) - - -### Features - -* **core:** update mongodb-core to v3.1.6 ([61b054e](https://github.com/mongodb/node-mongodb-native/commit/61b054e)) - - - -<a name="3.1.6"></a> -## [3.1.6](https://github.com/mongodb/node-mongodb-native/compare/v3.1.5...v3.1.6) (2018-09-15) - - -### Features - -* **core:** update to core v3.1.5 ([c5f823d](https://github.com/mongodb/node-mongodb-native/commit/c5f823d)) - - - -<a name="3.1.5"></a> -## [3.1.5](https://github.com/mongodb/node-mongodb-native/compare/v3.1.4...v3.1.5) (2018-09-14) - - -### Bug Fixes - -* **cursor:** allow `$meta` based sort when passing an array to `sort()` ([f93a8c3](https://github.com/mongodb/node-mongodb-native/commit/f93a8c3)) -* **utils:** only set retryWrites to true for valid operations ([3b725ef](https://github.com/mongodb/node-mongodb-native/commit/3b725ef)) - - -### Features - -* **core:** bump core to v3.1.4 ([805d58a](https://github.com/mongodb/node-mongodb-native/commit/805d58a)) - - - -<a name="3.1.4"></a> -## [3.1.4](https://github.com/mongodb/node-mongodb-native/compare/v3.1.3...v3.1.4) (2018-08-25) - - -### Bug Fixes - -* **buffer:** use safe-buffer polyfill to maintain compatibility ([327da95](https://github.com/mongodb/node-mongodb-native/commit/327da95)) -* **change-stream:** properly support resumablity in stream mode ([c43a34b](https://github.com/mongodb/node-mongodb-native/commit/c43a34b)) -* **connect:** correct replacement of topology on connect callback ([918a1e0](https://github.com/mongodb/node-mongodb-native/commit/918a1e0)) -* **cursor:** remove deprecated notice on forEach ([a474158](https://github.com/mongodb/node-mongodb-native/commit/a474158)) -* **url-parser:** bail early on validation when using domain socket ([3cb3da3](https://github.com/mongodb/node-mongodb-native/commit/3cb3da3)) - - -### Features - -* **client-ops:** allow bypassing creation of topologies on connect ([fe39b93](https://github.com/mongodb/node-mongodb-native/commit/fe39b93)) -* **core:** update mongodb-core to 3.1.3 ([a029047](https://github.com/mongodb/node-mongodb-native/commit/a029047)) -* **test:** use connection strings for all calls to `newClient` ([1dac18f](https://github.com/mongodb/node-mongodb-native/commit/1dac18f)) - - - -<a name="3.1.3"></a> -## [3.1.3](https://github.com/mongodb/node-mongodb-native/compare/v3.1.2...v3.1.3) (2018-08-13) - - -### Features - -* **core:** update to mongodb-core 3.1.2 ([337cb79](https://github.com/mongodb/node-mongodb-native/commit/337cb79)) - - - -<a name="3.1.2"></a> -## [3.1.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.2) (2018-08-13) - - -### Bug Fixes - -* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) -* **buffer:** replace deprecated Buffer constructor ([759dd85](https://github.com/mongodb/node-mongodb-native/commit/759dd85)) -* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) -* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) -* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) -* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) -* **client-ops:** return transform map to map rather than function ([cfb7d83](https://github.com/mongodb/node-mongodb-native/commit/cfb7d83)) -* **collection:** correctly shallow clone passed in options ([7727700](https://github.com/mongodb/node-mongodb-native/commit/7727700)) -* **collection:** countDocuments throws error when query doesn't match docs ([09c7d8e](https://github.com/mongodb/node-mongodb-native/commit/09c7d8e)) -* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) -* **collection:** ensure findAndModify always use readPreference primary ([86344f4](https://github.com/mongodb/node-mongodb-native/commit/86344f4)) -* **collection:** isCapped returns false instead of undefined ([b8471f1](https://github.com/mongodb/node-mongodb-native/commit/b8471f1)) -* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) -* **count-documents:** return callback on error case ([fca1185](https://github.com/mongodb/node-mongodb-native/commit/fca1185)) -* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) -* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) -* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) -* **cursor:** set readPreference for cursor.count ([13d776f](https://github.com/mongodb/node-mongodb-native/commit/13d776f)) -* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) -* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) -* **db_ops:** call collection.find() with correct parameters ([#1795](https://github.com/mongodb/node-mongodb-native/issues/1795)) ([36e92f1](https://github.com/mongodb/node-mongodb-native/commit/36e92f1)) -* **db_ops:** fix two incorrectly named variables ([15dc808](https://github.com/mongodb/node-mongodb-native/commit/15dc808)) -* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) -* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) -* **mongo_client:** translate options for connectWithUrl ([78f6977](https://github.com/mongodb/node-mongodb-native/commit/78f6977)) -* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) -* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) -* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) -* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) -* **server:** remove unnecessary print statement ([2bcbc12](https://github.com/mongodb/node-mongodb-native/commit/2bcbc12)) -* **teardown:** properly destroy a topology when initial connect fails ([b8d2f1d](https://github.com/mongodb/node-mongodb-native/commit/b8d2f1d)) -* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) -* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) -* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) - - -### Features - -* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) -* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) -* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) -* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) -* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) -* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) -* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) -* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) -* **core:** bump core dependency to v3.1.0 ([4937240](https://github.com/mongodb/node-mongodb-native/commit/4937240)) -* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) -* **deprecation:** create deprecation function ([4f907a0](https://github.com/mongodb/node-mongodb-native/commit/4f907a0)) -* **deprecation:** wrap deprecated functions ([a5d0f1d](https://github.com/mongodb/node-mongodb-native/commit/a5d0f1d)) -* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) -* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) -* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) -* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) -* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) -* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) -* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) - - -### Reverts - -* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) - - - -<a name="3.1.0"></a> -# [3.1.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.0) (2018-06-27) - - -### Bug Fixes - -* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) -* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) -* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) -* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) -* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) -* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) -* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) -* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) -* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) -* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) -* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) -* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) -* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) -* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) -* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) -* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) -* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) -* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) -* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) -* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) -* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) - - -### Features - -* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) -* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) -* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) -* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) -* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) -* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) -* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) -* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) -* **core:** bump core dependency to v3.1.0 ([855bfdb](https://github.com/mongodb/node-mongodb-native/commit/855bfdb)) -* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) -* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) -* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) -* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) -* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) -* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) -* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) -* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) - - -### Reverts - -* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) - - - -<a name="3.0.6"></a> -## [3.0.6](https://github.com/mongodb/node-mongodb-native/compare/v3.0.5...v3.0.6) (2018-04-09) - - -### Bug Fixes - -* **db:** ensure `dropDatabase` always uses primary read preference ([e62e5c9](https://github.com/mongodb/node-mongodb-native/commit/e62e5c9)) -* **driverBench:** driverBench has default options object now ([c557817](https://github.com/mongodb/node-mongodb-native/commit/c557817)) - - -### Features - -* **command-monitoring:** support enabling command monitoring ([5903680](https://github.com/mongodb/node-mongodb-native/commit/5903680)) -* **core:** update to mongodb-core v3.0.6 ([cfdd0ae](https://github.com/mongodb/node-mongodb-native/commit/cfdd0ae)) -* **driverBench:** Implementing DriverBench ([d10fbad](https://github.com/mongodb/node-mongodb-native/commit/d10fbad)) - - - -<a name="3.0.5"></a> -## [3.0.5](https://github.com/mongodb/node-mongodb-native/compare/v3.0.4...v3.0.5) (2018-03-23) - - -### Bug Fixes - -* **AggregationCursor:** adding session tracking to AggregationCursor ([baca5b7](https://github.com/mongodb/node-mongodb-native/commit/baca5b7)) -* **Collection:** fix session leak in parallelCollectonScan ([3331ec9](https://github.com/mongodb/node-mongodb-native/commit/3331ec9)) -* **comments:** adding fixes for PR comments ([ee110ac](https://github.com/mongodb/node-mongodb-native/commit/ee110ac)) -* **url_parser:** support a default database on mongodb+srv uris ([6d39b2a](https://github.com/mongodb/node-mongodb-native/commit/6d39b2a)) - - -### Features - -* **sessions:** adding implicit cursor session support ([a81245b](https://github.com/mongodb/node-mongodb-native/commit/a81245b)) - - - -<a name="3.0.4"></a> -## [3.0.4](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.4) (2018-03-05) - - -### Bug Fixes - -* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) -* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) -* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) -* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) -* **utils:** fixes executeOperation to clean up sessions ([04e6ef6](https://github.com/mongodb/node-mongodb-native/commit/04e6ef6)) - - -### Features - -* **default-db:** use dbName from uri if none provided ([23b1938](https://github.com/mongodb/node-mongodb-native/commit/23b1938)) -* **mongodb-core:** update to mongodb-core 3.0.4 ([1fdbaa5](https://github.com/mongodb/node-mongodb-native/commit/1fdbaa5)) - - - -<a name="3.0.3"></a> -## [3.0.3](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.3) (2018-02-23) - - -### Bug Fixes - -* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) -* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) -* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) -* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) - - - -<a name="3.0.2"></a> -## [3.0.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.1...v3.0.2) (2018-01-29) - - -### Bug Fixes - -* **collection:** ensure dynamic require of `db` is wrapped in parentheses ([efa78f0](https://github.com/mongodb/node-mongodb-native/commit/efa78f0)) -* **db:** only callback with MongoError NODE-1293 ([#1652](https://github.com/mongodb/node-mongodb-native/issues/1652)) ([45bc722](https://github.com/mongodb/node-mongodb-native/commit/45bc722)) -* **topology base:** allow more than 10 event listeners ([#1630](https://github.com/mongodb/node-mongodb-native/issues/1630)) ([d9fb750](https://github.com/mongodb/node-mongodb-native/commit/d9fb750)) -* **url parser:** preserve auth creds when composing conn string ([#1640](https://github.com/mongodb/node-mongodb-native/issues/1640)) ([eddca5e](https://github.com/mongodb/node-mongodb-native/commit/eddca5e)) - - -### Features - -* **bulk:** forward 'checkKeys' option for ordered and unordered bulk operations ([421a6b2](https://github.com/mongodb/node-mongodb-native/commit/421a6b2)) -* **collection:** expose `dbName` property of collection ([6fd05c1](https://github.com/mongodb/node-mongodb-native/commit/6fd05c1)) - - - -<a name="3.0.1"></a> -## [3.0.1](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0...v3.0.1) (2017-12-24) - -* update mongodb-core to 3.0.1 - -<a name="3.0.0"></a> -# [3.0.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0-rc0...v3.0.0) (2017-12-24) - - -### Bug Fixes - -* **aggregate:** remove support for inline results for aggregate ([#1620](https://github.com/mongodb/node-mongodb-native/issues/1620)) ([84457ec](https://github.com/mongodb/node-mongodb-native/commit/84457ec)) -* **topologies:** unify topologies connect API ([#1615](https://github.com/mongodb/node-mongodb-native/issues/1615)) ([0fb4658](https://github.com/mongodb/node-mongodb-native/commit/0fb4658)) - - -### Features - -* **keepAlive:** make keepAlive options consistent ([#1612](https://github.com/mongodb/node-mongodb-native/issues/1612)) ([f608f44](https://github.com/mongodb/node-mongodb-native/commit/f608f44)) - - -### BREAKING CHANGES - -* **topologies:** Function signature for `.connect` method on replset and mongos has changed. You shouldn't have been using this anyway, but if you were, you only should pass `options` and `callback`. - -Part of NODE-1089 -* **keepAlive:** option `keepAlive` is now split into boolean `keepAlive` and -number `keepAliveInitialDelay` - -Fixes NODE-998 - - - -<a name="3.0.0-rc0"></a> -# [3.0.0-rc0](https://github.com/mongodb/node-mongodb-native/compare/v2.2.31...v3.0.0-rc0) (2017-12-05) - - -### Bug Fixes - -* **aggregation:** ensure that the `cursor` key is always present ([f16f314](https://github.com/mongodb/node-mongodb-native/commit/f16f314)) -* **apm:** give users access to raw server responses ([88b206b](https://github.com/mongodb/node-mongodb-native/commit/88b206b)) -* **apm:** only rebuilt cursor if reply is non-null ([96052c8](https://github.com/mongodb/node-mongodb-native/commit/96052c8)) -* **apm:** rebuild lost `cursor` info on pre-OP_QUERY responses ([4242d49](https://github.com/mongodb/node-mongodb-native/commit/4242d49)) -* **bulk-unordered:** add check for ignoreUndefined ([f38641a](https://github.com/mongodb/node-mongodb-native/commit/f38641a)) -* **change stream examples:** use timeouts, cleanup ([c5fec5f](https://github.com/mongodb/node-mongodb-native/commit/c5fec5f)) -* **change-streams:** ensure a majority read concern on initial agg ([23011e9](https://github.com/mongodb/node-mongodb-native/commit/23011e9)) -* **changeStreams:** fixing node4 issue with util.inherits ([#1587](https://github.com/mongodb/node-mongodb-native/issues/1587)) ([168bb3d](https://github.com/mongodb/node-mongodb-native/commit/168bb3d)) -* **collection:** allow { upsert: 1 } for findOneAndUpdate() and update() ([5bcedd6](https://github.com/mongodb/node-mongodb-native/commit/5bcedd6)) -* **collection:** allow passing `noCursorTimeout` as an option to `find()` ([e9c4ffc](https://github.com/mongodb/node-mongodb-native/commit/e9c4ffc)) -* **collection:** make the parameters of findOne very explicit ([3054f1a](https://github.com/mongodb/node-mongodb-native/commit/3054f1a)) -* **cursor:** `hasNext` should propagate errors when using callback ([6339625](https://github.com/mongodb/node-mongodb-native/commit/6339625)) -* **cursor:** close readable on `null` response for dead cursor ([6aca2c5](https://github.com/mongodb/node-mongodb-native/commit/6aca2c5)) -* **dns txt records:** check options are set ([e5caf4f](https://github.com/mongodb/node-mongodb-native/commit/e5caf4f)) -* **docs:** Represent each valid option in docs in both places ([fde6e5d](https://github.com/mongodb/node-mongodb-native/commit/fde6e5d)) -* **grid-store:** add missing callback ([66a9a05](https://github.com/mongodb/node-mongodb-native/commit/66a9a05)) -* **grid-store:** move into callback scope ([b53f65f](https://github.com/mongodb/node-mongodb-native/commit/b53f65f)) -* **GridFS:** fix TypeError: doc.data.length is not a function ([#1570](https://github.com/mongodb/node-mongodb-native/issues/1570)) ([22a4628](https://github.com/mongodb/node-mongodb-native/commit/22a4628)) -* **list-collections:** ensure default of primary ReadPreference ([4a0cfeb](https://github.com/mongodb/node-mongodb-native/commit/4a0cfeb)) -* **mongo client:** close client before calling done ([c828aab](https://github.com/mongodb/node-mongodb-native/commit/c828aab)) -* **mongo client:** do not connect if url parse error ([cd10084](https://github.com/mongodb/node-mongodb-native/commit/cd10084)) -* **mongo client:** send error to cb ([eafc9e2](https://github.com/mongodb/node-mongodb-native/commit/eafc9e2)) -* **mongo-client:** move to inside of callback ([68b0fca](https://github.com/mongodb/node-mongodb-native/commit/68b0fca)) -* **mongo-client:** options should not be passed to `connect` ([474ac65](https://github.com/mongodb/node-mongodb-native/commit/474ac65)) -* **tests:** migrate 2.x tests to 3.x ([3a5232a](https://github.com/mongodb/node-mongodb-native/commit/3a5232a)) -* **updateOne/updateMany:** ensure that update documents contain atomic operators ([8b4255a](https://github.com/mongodb/node-mongodb-native/commit/8b4255a)) -* **url parser:** add check for options as cb ([52b6039](https://github.com/mongodb/node-mongodb-native/commit/52b6039)) -* **url parser:** compare srv address and parent domains ([daa186d](https://github.com/mongodb/node-mongodb-native/commit/daa186d)) -* **url parser:** compare string from first period on ([9e5d77e](https://github.com/mongodb/node-mongodb-native/commit/9e5d77e)) -* **url parser:** default to ssl true for mongodb+srv ([0fbca4b](https://github.com/mongodb/node-mongodb-native/commit/0fbca4b)) -* **url parser:** error when multiple hostnames used ([c1aa681](https://github.com/mongodb/node-mongodb-native/commit/c1aa681)) -* **url parser:** keep original uri options and default to ssl true ([e876a72](https://github.com/mongodb/node-mongodb-native/commit/e876a72)) -* **url parser:** log instead of throw error for unsupported url options ([155de2d](https://github.com/mongodb/node-mongodb-native/commit/155de2d)) -* **url parser:** make sure uri has 3 parts ([aa9871b](https://github.com/mongodb/node-mongodb-native/commit/aa9871b)) -* **url parser:** only 1 txt record allowed with 2 possible options ([d9f4218](https://github.com/mongodb/node-mongodb-native/commit/d9f4218)) -* **url parser:** only check for multiple hostnames with srv protocol ([5542bcc](https://github.com/mongodb/node-mongodb-native/commit/5542bcc)) -* **url parser:** remove .only from test ([642e39e](https://github.com/mongodb/node-mongodb-native/commit/642e39e)) -* **url parser:** return callback ([6096afc](https://github.com/mongodb/node-mongodb-native/commit/6096afc)) -* **url parser:** support single text record with multiple strings ([356fa57](https://github.com/mongodb/node-mongodb-native/commit/356fa57)) -* **url parser:** try catch bug, not actually returning from try loop ([758892b](https://github.com/mongodb/node-mongodb-native/commit/758892b)) -* **url parser:** use warn instead of info ([40ed27d](https://github.com/mongodb/node-mongodb-native/commit/40ed27d)) -* **url-parser:** remove comment, send error to cb ([d44420b](https://github.com/mongodb/node-mongodb-native/commit/d44420b)) - - -### Features - -* **aggregate:** support hit field for aggregate command ([aa7da15](https://github.com/mongodb/node-mongodb-native/commit/aa7da15)) -* **aggregation:** adds support for comment in aggregation command ([#1571](https://github.com/mongodb/node-mongodb-native/issues/1571)) ([4ac475c](https://github.com/mongodb/node-mongodb-native/commit/4ac475c)) -* **aggregation:** fail aggregation on explain + readConcern/writeConcern ([e0ca1b4](https://github.com/mongodb/node-mongodb-native/commit/e0ca1b4)) -* **causal-consistency:** support `afterClusterTime` in readConcern ([a9097f7](https://github.com/mongodb/node-mongodb-native/commit/a9097f7)) -* **change-streams:** add support for change streams ([c02d25c](https://github.com/mongodb/node-mongodb-native/commit/c02d25c)) -* **collection:** updating find API ([f26362d](https://github.com/mongodb/node-mongodb-native/commit/f26362d)) -* **execute-operation:** implementation for common op execution ([67c344f](https://github.com/mongodb/node-mongodb-native/commit/67c344f)) -* **listDatabases:** add support for nameOnly option to listDatabases ([eb79b5a](https://github.com/mongodb/node-mongodb-native/commit/eb79b5a)) -* **maxTimeMS:** adding maxTimeMS option to createIndexes and dropIndexes ([90d4a63](https://github.com/mongodb/node-mongodb-native/commit/90d4a63)) -* **mongo-client:** implement `MongoClient.prototype.startSession` ([bce5adf](https://github.com/mongodb/node-mongodb-native/commit/bce5adf)) -* **retryable-writes:** add support for `retryWrites` cs option ([2321870](https://github.com/mongodb/node-mongodb-native/commit/2321870)) -* **sessions:** MongoClient will now track sessions and release ([6829f47](https://github.com/mongodb/node-mongodb-native/commit/6829f47)) -* **sessions:** support passing sessions via objects in all methods ([a531f05](https://github.com/mongodb/node-mongodb-native/commit/a531f05)) -* **shared:** add helper utilities for assertion and suite setup ([b6cc34e](https://github.com/mongodb/node-mongodb-native/commit/b6cc34e)) -* **ssl:** adds missing ssl options ssl options for `ciphers` and `ecdhCurve` ([441b7b1](https://github.com/mongodb/node-mongodb-native/commit/441b7b1)) -* **test-shared:** add `notEqual` assertion ([41d93fd](https://github.com/mongodb/node-mongodb-native/commit/41d93fd)) -* **test-shared:** add `strictEqual` assertion method ([cad8e19](https://github.com/mongodb/node-mongodb-native/commit/cad8e19)) -* **topologies:** expose underlaying `logicalSessionTimeoutMinutes' ([1609a37](https://github.com/mongodb/node-mongodb-native/commit/1609a37)) -* **url parser:** better error message for slash in hostname ([457bc29](https://github.com/mongodb/node-mongodb-native/commit/457bc29)) - - -### BREAKING CHANGES - -* **aggregation:** If you use aggregation, and try to use the explain flag while you -have a readConcern or writeConcern, your query will fail -* **collection:** `find` and `findOne` no longer support the `fields` parameter. -You can achieve the same results as the `fields` parameter by -either using `Cursor.prototype.project`, or by passing the `projection` -property in on the `options` object. Additionally, `find` does not -support individual options like `skip` and `limit` as positional -parameters. You must pass in these parameters in the `options` object - - - -3.0.0 2017-??-?? ----------------- -* NODE-1043 URI-escaping authentication and hostname details in connection string - -2.2.31 2017-08-08 ------------------ -* update mongodb-core to 2.2.15 -* allow auth option in MongoClient.connect -* remove duplicate option `promoteLongs` from MongoClient's `connect` -* bulk operations should not throw an error on empty batch - -2.2.30 2017-07-07 ------------------ -* Update mongodb-core to 2.2.14 -* MongoClient - * add `appname` to list of valid option names - * added test for passing appname as option -* NODE-1052 ensure user options are applied while parsing connection string uris - -2.2.29 2017-06-19 ------------------ -* Update mongodb-core to 2.1.13 - * NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. - * Use actual server type in standalone SDAM events. -* Allow multiple map calls (Issue #1521, https://github.com/Robbilie). -* Clone insertMany options before mutating (Issue #1522, https://github.com/vkarpov15). -* NODE-1034 Fix GridStore issue caused by Node 8.0.0 breaking backward compatible fs.read API. -* NODE-1026, use operator instead of skip function in order to avoid useless fetch stage. - -2.2.28 2017-06-02 ------------------ -* Update mongodb-core to 2.1.12 - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. - * Minor fix to report the correct state on error. - * NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). - * Fix require_optional loading of bson-ext. - * Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. - * NODE-999 SDAM fixes for Mongos and single Server event emitting. - * NODE-1014 Set socketTimeout to default to 360 seconds. - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. -* Just handle Collection name errors distinctly from general callback errors avoiding double callbacks in Db.collection. -* NODE-999 SDAM fixes for Mongos and single Server event emitting. -* NODE-1000 Added guard condition for upload.js checkDone function in case of race condition caused by late arriving chunk write. - -2.2.27 2017-05-22 ------------------ -* Updated mongodb-core to 2.1.11 - * NODE-987 Clear out old intervalIds on when calling topologyMonitor. - * NODE-987 Moved filtering to pingServer method and added test case. - * Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). - * NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interval. -* NODE-985 Deprecated Db.authenticate and Admin.authenticate and moved auth methods into authenticate.js to ensure MongoClient.connect does not print deprecation warnings. -* NODE-988 Merged readConcern and hint correctly on collection(...).find(...).count() -* Fix passing the readConcern option to MongoClient.connect (Issue #1514, https://github.com/bausmeier). -* NODE-996 Propegate all events up to a MongoClient instance. -* Allow saving doc with null `_id` (Issue #1517, https://github.com/vkarpov15). -* NODE-993 Expose hasNext for command cursor and add docs for both CommandCursor and Aggregation Cursor. - -2.2.26 2017-04-18 ------------------ -* Updated mongodb-core to 2.1.10 - * NODE-981 delegate auth to replset/mongos if inTopology is set. - * NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. - * Remove dynamic require (Issue #175, https://github.com/tellnes). - * NODE-696 Handle interrupted error for createIndexes. - * Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. - * NODE-966 promoteValues not being promoted correctly to getMore. - * Merged in fix for flushing out monitoring operations. -* NODE-983 Add cursorId to aggregate and listCollections commands (Issue, #1510). -* Mark group and profilingInfo as deprecated methods -* NODE-956 DOCS Examples. -* Update readable-stream to version 2.2.7. -* NODE-978 Added test case to uncover connection.end issue for node 0.10.x. -* NODE-972 Fix(db): don't remove database name if collectionName == dbName (Issue, #1502) -* Fixed merging of writeConcerns on db.collection method. -* NODE-970 mix in readPreference for strict mode listCollections callback. -* NODE-966 added testcase for promoteValues being applied to getMore commands. -* NODE-962 Merge in ignoreUndefined from collection level for find/findOne. -* Remove multi option from updateMany tests/docs (Issue #1499, https://github.com/spratt). -* NODE-963 Correctly handle cursor.count when using APM. - -2.2.25 2017-03-17 ------------------ -* Don't rely on global toString() for checking if object (Issue #1494, https://github.com/vkarpov15). -* Remove obsolete option uri_decode_auth (Issue #1488, https://github.com/kamagatos). -* NODE-936 Correctly translate ReadPreference to CoreReadPreference for mongos queries. -* Exposed BSONRegExp type. -* NODE-950 push correct index for INSERT ops (https://github.com/mbroadst). -* NODE-951 Added support for sslCRL option and added a test case for it. -* NODE-953 Made batchSize issue general at cursor level. -* NODE-954 Remove write concern from reindex helper as it will not be supported in 3.6. -* Updated mongodb-core to 2.1.9. - * Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. - * Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. - * Ensure SSL error propegates better for Replset connections when there is a SSL validation error. - * NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. - * NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. - -2.2.24 2017-02-14 ------------------ -* NODE-935, NODE-931 Make MongoClient strict options validation optional and instead print annoying console.warn entries. - -2.2.23 2017-02-13 ------------------ -* Updated mongodb-core to 2.1.8. - * NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. - * NODE-927 fixes issue where authentication was performed against arbiter instances. - * NODE-915 Normalize all host names to avoid comparison issues. - * Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. -* NODE-931 Validates all the options for MongoClient.connect and fixes missing connection settings. -* NODE-929 Update SSL tutorial to correctly reflect the non-need for server/mongos/replset subobjects -* Fix sensitive command check (Issue #1473, https://github.com/Annoraaq) - -2.2.22 2017-01-24 ------------------ -* Updated mongodb-core to 2.1.7. - * NODE-919 ReplicaSet connection does not close immediately (Issue #156). - * NODE-901 Fixed bug when normalizing host names. - * NODE-909 Fixed readPreference issue caused by direct connection to primary. - * NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. -* Add missing unref implementations for replset, mongos (Issue #1455, https://github.com/zbjornson) - -2.2.21 2017-01-13 ------------------ -* Updated mongodb-core to 2.1.6. - * NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. - -2.2.20 2017-01-11 ------------------ -* Updated mongodb-core to 2.1.5 to include bson 1.0.4 and bson-ext 1.0.4 due to Buffer.from being broken in early node 4.x versions. - -2.2.19 2017-01-03 ------------------ -* Corrupted Npm release fix. - -2.2.18 2017-01-03 ------------------ -* Updated mongodb-core to 2.1.4 to fix bson ObjectId toString issue with utils.inspect messing with toString parameters in node 6. - -2.2.17 2017-01-02 ------------------ -* updated createCollection doc options and linked to create command. -* Updated mongodb-core to 2.1.3. - * Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining - * Moved replicaset monitoring away from serial mode and to parallel mode. - * updated bson and bson-ext dependencies to 1.0.2. - -2.2.16 2016-12-13 ------------------ -* NODE-899 reversed upsertedId change to bring back old behavior. - -2.2.15 2016-12-10 ------------------ -* Updated mongodb-core to 2.1.2. - * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. - * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). - -2.2.14 2016-12-08 ------------------ -* Updated mongodb-core to 2.1.1. -* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. - -2.2.13 2016-12-05 ------------------ -* Updated mongodb-core to 2.1.0. -* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. -* Expose parserType as property on topology objects. - -2.2.12 2016-11-29 ------------------ -* Updated mongodb-core to 2.0.14. - * Updated bson library to 0.5.7. - * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). - * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). - * Only check isConnected against availableConnections (Issue #142). - * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. - * Set default servername to host is not passed through for sni. - * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). - * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. - * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. - * NODE-850 Update Max Staleness implementation. - * NODE-849 username no longer required for MONGODB-X509 auth. - * NODE-848 BSON Regex flags must be alphabetically ordered. - * NODE-846 Create notice for all third party libraries. - * NODE-843 Executing bulk operations overwrites write concern parameter. - * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. - * NODE-840 Resync CRUD spec tests. - * Unescapable while(true) loop (Issue #152). -* NODE-864 close event not emits during network issues using single server topology. -* Introduced maxStalenessSeconds. -* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. -* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). - -2.2.11 2016-10-21 ------------------ -* Updated mongodb-core to 2.0.13. - - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). - - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). - - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). - - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). -* Updated bson library to 0.5.6. - - Included cyclic dependency detection -* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). -* NODE-824, readPreference "nearest" does not work when specified at collection level. -* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. -* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. -* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. - -2.2.10 2016-09-15 ------------------ -* Updated mongodb-core to 2.0.12. -* fix debug logging message not printing server name. -* fixed application metadata being sent by wrong ismaster. -* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. -* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". -* Updated bson library to 0.5.5. -* Added DBPointer up conversion to DBRef. -* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. -* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. -* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. -* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. - -2.2.9 2016-08-29 ----------------- -* Updated mongodb-core to 2.0.11. -* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. -* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). -* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. -* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). - -2.2.8 2016-08-23 ----------------- -* Updated mongodb-core to 2.0.10. -* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. -* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). - -2.2.7 2016-08-19 ----------------- -* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). -* Updated mongodb-core to 2.0.9. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* NODE-798 Driver hangs on count command in replica set with one member. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* Allow passing in servername for TLS connections for SNI support. - -2.2.6 2016-08-16 ----------------- -* Updated mongodb-core to 2.0.8. -* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). -* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. -* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) -* Added hashed connection names and fullResult. -* Updated bson library to 0.5.3. -* Enable maxTimeMS in count, distinct, findAndModify. - -2.2.5 2016-07-28 ----------------- -* Updated mongodb-core to 2.0.7. -* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). -* Added better warnings when passing in illegal seed list members to a Mongos topology. -* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. -* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) -* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. - -2.2.4 2016-07-19 ----------------- -* NPM corrupted upload fix. - -2.2.3 2016-07-19 ----------------- -* Updated mongodb-core to 2.0.6. -* Destroy connection on socket timeout due to newer node versions not closing the socket. - -2.2.2 2016-07-15 ----------------- -* Updated mongodb-core to 2.0.5. -* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. -* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. -* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. -* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. - -2.2.1 2016-07-11 ----------------- -* Updated mongodb-core to 2.0.4. -* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. -* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. -* NODE-746 Improves replicaset errors for wrong setName. - -2.2.0 2016-07-05 ----------------- -* Updated mongodb-core to 2.0.3. -* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. -* All authentication methods now handle both auth/reauthenticate and logout events. -* Introduced logout method to get rid of onAll option for logout command. -* Updated bson to 0.5.0 that includes Decimal128 support. -* Fixed logger error serialization issue. -* Documentation fixes. -* Implemented Server Selection Specification test suite. -* Added warning level to logger. -* Added warning message when sockeTimeout < haInterval for Replset/Mongos. -* Mongos emits close event on no proxies available or when reconnect attempt fails. -* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. -* Don't throw in auth methods but return error in callback. - -2.1.21 2016-05-30 ------------------ -* Updated mongodb-core to 1.3.21. -* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). -* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. -* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. -* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). -* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. -* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. - -2.1.20 2016-05-25 ------------------ -* Refactored MongoClient options handling to simplify the logic, unifying it. -* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. -* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. -* Updated mongodb-core to 1.3.20. -* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. -* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. -* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. - -2.1.19 2016-05-17 ----------------- -* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. -* Ensure replicaset topology destroy is never called by SDAM. -* Ensure all paths are correctly returned on inspectServer in replset. -* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. - -2.1.18 2016-04-27 ------------------ -* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. - -2.1.17 2016-04-26 ------------------ -* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. -* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. -* Fix timeout issue using new flags #1361. -* Updated mongodb-core to 1.3.17. -* Better handling of unique createIndex error. -* Emit error only if db instance has an error listener. -* DEFAULT authMechanism; don't throw error if explicitly set by user. - -2.1.16 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.16. - -2.1.15 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.15. -* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). -- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. -- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. - -2.1.14 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.13. -* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. - -2.1.13 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.12. - -2.1.12 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.11. -* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. -* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. -* isConnected method for mongos uses same selection code as getServer. -* Exceptions in cursor getServer trapped and correctly delegated to high level handler. - -2.1.11 2016-03-23 ------------------ -* Updated mongodb-core to 1.3.10. -* Introducing simplified connections settings. - -2.1.10 2016-03-21 ------------------ -* Updated mongodb-core to 1.3.9. -* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) -* Forwards SDAM monitoring events from mongodb-core. - -2.1.9 2016-03-16 ----------------- -* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. -* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. - -2.1.8 2016-03-14 ----------------- -* Updated mongodb-core to 1.3.5. -* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. -* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. -* Ensure RequestId can never be larger than Max Number integer size. -* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. -* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). -* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. -* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. -* NODE-663 added lookup helper on aggregation cursor. -* NODE-585 Result object specified incorrectly for findAndModify?. -* NODE-666 harden validation for findAndModify CRUD methods. - -2.1.7 2016-02-09 ----------------- -* NODE-656 fixed corner case where cursor count command could be left without a connection available. -* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. -* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). -* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). -* NODE-657 insertOne don`t return promise in some cases. -* Added destroy alias for abort function on GridFSBucketWriteStream. - -2.1.6 2016-02-05 ----------------- -* Updated mongodb-core to 1.3.1. - -2.1.5 2016-02-04 ----------------- -* Updated mongodb-core to 1.3.0. -* Added raw support for the command function on topologies. -* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) -* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) -* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. -* NODE-638, Cannot authenticate database user with utf-8 password. -* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. -* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. -* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. -* Switched to using Array.push instead of concat for use cases of a lot of documents. -* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. -* Added peer optional dependencies support using require_optional module. -* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) -* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) - -2.1.4 2016-01-12 ----------------- -* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). -* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). -* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). - -2.1.3 2016-01-04 ----------------- -* Updated mongodb-core to 1.2.31. -* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) - -2.1.2 2015-12-23 ----------------- -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.1.1 2015-12-13 ----------------- -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.1.0 2015-12-06 ----------------- -* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. -* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. -* Full MongoDB 3.2 support. -* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Updated mongodb-core to 1.2.26. -* Return destination in GridStore pipe function. -* NODE-606 better error handling on destroyed topology for db.js methods. -* Added isDestroyed method to server, replset and mongos topologies. -* Upgraded test suite to run using mongodb-topology-manager. - -2.0.53 2015-12-23 ------------------ -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.0.52 2015-12-14 ------------------ -* removed remove from Gridstore.close. - -2.0.51 2015-12-13 ------------------ -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.0.50 2015-12-06 ------------------ -* Updated mongodb-core to 1.2.26. - -2.0.49 2015-11-20 ------------------ -* Updated mongodb-core to 1.2.24 with several fixes. - * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). - * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. - * ismaster runs against admin.$cmd instead of system.$cmd. - * Fixes to handle getMore command errors for MongoDB 3.2 - * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. - -2.0.48 2015-11-07 ------------------ -* GridFS no longer performs any deletes when writing a brand new file that does not have any previous <db>.fs.chunks or <db>.fs.files documents. -* Updated mongodb-core to 1.2.21. -* Hardened the checking for replicaset equality checks. -* OpReplay flag correctly set on Wire protocol query. -* Mongos load balancing added, introduced localThresholdMS to control the feature. -* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. - -2.0.47 2015-10-28 ------------------ -* Updated mongodb-core to 1.2.20. -* Fixed bug in arbiter connection capping code. -* NODE-599 correctly handle arrays of server tags in order of priority. -* Fix for 2.6 wire protocol handler related to readPreference handling. -* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). - -2.0.46 2015-10-15 ------------------ -* Updated mongodb-core to 1.2.19. -* NODE-578 Order of sort fields is lost for numeric field names. -* Expose BSON Map (ES6 Map or polyfill). -* Minor fixes for APM support to pass extended APM test suite. - -2.0.45 2015-09-30 ------------------ -* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. - -2.0.44 2015-09-28 ------------------ -* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. -* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. -* Updated mongodb-core to 1.2.14. -* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. -* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) -* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. -* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. -* NODE-572 Remove examples that use the second parameter to `find()`. - -2.0.43 2015-09-14 ------------------ -* Propagate timeout event correctly to db instances. -* Application Monitoring API (APM) implemented. -* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. -* Updated mongodb-core to 1.2.12. -* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. -* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) -* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) -* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) - -2.0.42 2015-08-18 ------------------ -* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. - -2.0.41 2015-08-14 ------------------ -* Added missing Mongos.prototype.parserType function. -* Updated mongodb-core to 1.2.10. - -2.0.40 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. -* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -* NODE-518 connectTimeoutMS is doubled in 2.0.39. -* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). -* NODE-526 Unique index not throwing duplicate key error. -* NODE-528 Ignore undefined fields in Collection.find(). -* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. - -2.0.39 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.6 for NODE-505. - -2.0.38 2015-07-14 ------------------ -* NODE-505 Query fails to find records that have a 'result' property with an array value. - -2.0.37 2015-07-14 ------------------ -* NODE-504 Collection * Default options when using promiseLibrary. -* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. -* Updated mongodb-core to 1.2.5 to fix NODE-492. - -2.0.36 2015-07-07 ------------------ -* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). -* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. - -2.0.35 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. - -2.0.34 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. -* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. -* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -2.0.33 2015-05-20 ------------------ -* Bumped mongodb-core to 1.1.32. - -2.0.32 2015-05-19 ------------------ -* 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 2015-05-08 ------------------ -* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. - -2.0.30 2015-05-07 ------------------ -* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. - -2.0.29 2015-05-07 ------------------ -* 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 2015-04-24 ------------------ -* 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 2015-04-07 ------------------ -* 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 2015-04-07 ------------------ -* 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 2015-03-26 ------------------ -* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. - -2.0.24 2015-03-24 ------------------ -* 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 '\<Object\>' 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/mongodb/LICENSE.md b/node_modules/mongodb/LICENSE.md deleted file mode 100644 index ad410e11302107da9aa47ce3d46bd5ad011c4c43..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ -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/mongodb/README.md b/node_modules/mongodb/README.md deleted file mode 100644 index 596708c096d278d2f99c184bb2fd1aaf64ef5e89..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/README.md +++ /dev/null @@ -1,493 +0,0 @@ -[](https://nodei.co/npm/mongodb/) [](https://nodei.co/npm/mongodb/) - -[](http://travis-ci.org/mongodb/node-mongodb-native) -[](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) -[](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -# Description - -The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. - -**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).** - -## MongoDB Node.JS Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native | -| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org | - -### 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 [jira.mongodb.org](https://jira.mongodb.org). -- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). -- 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: [groups.google.com/forum/#!forum/node-mongodb-native](https://groups.google.com/forum/#!forum/node-mongodb-native) - * JIRA: [jira.mongodb.org](http://jira.mongodb.org) - -### Change Log - -Change history can be found in [`HISTORY.md`](HISTORY.md). - -# Installation - -The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project. - -## MongoDB Driver - -Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command. - -```bash -npm install mongodb --save -``` - -This will download the MongoDB driver and add a dependency entry in your `package.json` file. - -You can also use the [Yarn](https://yarnpkg.com/en) package manager. - -## Troubleshooting - -The MongoDB driver depends on several other packages. These are: - -* [mongodb-core](https://github.com/mongodb-js/mongodb-core) -* [bson](https://github.com/mongodb/js-bson) -* [kerberos](https://github.com/mongodb-js/kerberos) -* [node-gyp](https://github.com/nodejs/node-gyp) - -The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install. - -**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.** - -### Diagnosing on UNIX - -If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps. - -```bash -git clone https://github.com/mongodb-js/kerberos -cd kerberos -npm install -``` - -If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally: - -```bash -npm install -g node-gyp -``` - -If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command. - -```bash -cd yourproject -npm install mongodb --save -``` - -If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. - -```bash -npm --loglevel verbose install mongodb -``` - -This will print out all the steps npm is performing while trying to install the module. - -### Diagnosing on Windows - -A compiler tool chain known to work for compiling `kerberos` on Windows is the following. - -* Visual Studio C++ 2010 (do not use higher versions) -* Windows 7 64bit SDK -* Python 2.7 or higher - -Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`. - -```bash -npm install -g node-gyp -``` - -Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild: - -```bash -git clone https://github.com/christkv/kerberos.git -cd kerberos -npm install -node-gyp rebuild -``` - -This should rebuild the driver successfully if you have everything set up correctly. - -### Other possible issues - -Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there). - -Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed. - -## Quick Start - -This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md). - -### Create the `package.json` file - -First, create a directory where your application will live. - -```bash -mkdir myproject -cd myproject -``` - -Enter the following command and answer the questions to create the initial structure for your new project: - -```bash -npm init -``` - -Next, install the driver dependency. - -```bash -npm install mongodb --save -``` - -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. - -### Start a MongoDB Server - -For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). - -1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) -2. Create a database directory (in this case under **/data**). -3. Install and start a ``mongod`` process. - -```bash -mongod --dbpath=/data -``` - -You should see the **mongod** process start up and print some status information. - -### Connect to MongoDB - -Create a new **app.js** file and add the following code to try out some basic CRUD -operations using the MongoDB driver. - -Add code to connect to the server and the database **myproject**: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - client.close(); -}); -``` - -Run your app from the command line with: - -```bash -node app.js -``` - -The application should print **Connected successfully to server** to the console. - -### Insert a Document - -Add to **app.js** the following function which uses the **insertMany** -method to add three documents to the **documents** collection. - -```js -const insertDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Insert some documents - collection.insertMany([ - {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 collection"); - callback(result); - }); -} -``` - -The **insert** command returns an object with the following fields: - -* **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 - -Add the following code to call the **insertDocuments** function: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - client.close(); - }); -}); -``` - -Run the updated **app.js** file: - -```bash -node app.js -``` - -The operation returns the following output: - -```bash -Connected successfully to server -Inserted 3 documents into the collection -``` - -### Find All Documents - -Add a query that returns all the documents. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({}).toArray(function(err, docs) { - assert.equal(err, null); - console.log("Found the following records"); - console.log(docs) - callback(docs); - }); -} -``` - -This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - findDocuments(db, function() { - client.close(); - }); - }); -}); -``` - -### Find Documents with a Query Filter - -Add a query filter to find only documents which meet the query criteria. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({'a': 3}).toArray(function(err, docs) { - assert.equal(err, null); - console.log("Found the following records"); - console.log(docs); - callback(docs); - }); -} -``` - -Only the documents which match ``'a' : 3`` should be returned. - -### Update a document - -The following operation updates a document in the **documents** collection. - -```js -const updateDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Update document where a is 2, set b equal to 1 - collection.updateOne({ 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 updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - client.close(); - }); - }); -}); -``` - -### Remove a document - -Remove the document where the field **a** is equal to **3**. - -```js -const removeDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Delete document where a is 3 - collection.deleteOne({ 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); - }); -} -``` - -Add the new method to the **MongoClient.connect** callback function. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - removeDocument(db, function() { - client.close(); - }); - }); - }); -}); -``` - -### Index a Collection - -[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's -performance. The following function creates an index on the **a** field in the -**documents** collection. - -```js -const indexCollection = function(db, callback) { - db.collection('documents').createIndex( - { "a": 1 }, - null, - function(err, results) { - console.log(results); - callback(); - } - ); -}; -``` - -Add the ``indexCollection`` method to your app: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - indexCollection(db, function() { - client.close(); - }); - }); -}); -``` - -For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md). - -## Next Steps - - * [MongoDB Documentation](http://mongodb.org) - * [Read about Schemas](http://learnmongodbthehardway.com) - * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) - -## License - -[Apache 2.0](LICENSE.md) - -© 2009-2012 Christian Amor Kvalheim -© 2012-present MongoDB [Contributors](CONTRIBUTORS.md) diff --git a/node_modules/mongodb/index.js b/node_modules/mongodb/index.js deleted file mode 100644 index fe305d6a2c6b9e23ae37e53a11b22ab29653930a..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/index.js +++ /dev/null @@ -1,67 +0,0 @@ -'use strict'; - -// Core module -const core = require('mongodb-core'); -const Instrumentation = require('./lib/apm'); - -// Set up the connect function -const connect = require('./lib/mongo_client').connect; - -// Expose error class -connect.MongoError = core.MongoError; -connect.MongoNetworkError = core.MongoNetworkError; - -// Actual driver classes exported -connect.Admin = require('./lib/admin'); -connect.MongoClient = require('./lib/mongo_client'); -connect.Db = require('./lib/db'); -connect.Collection = require('./lib/collection'); -connect.Server = require('./lib/topologies/server'); -connect.ReplSet = require('./lib/topologies/replset'); -connect.Mongos = require('./lib/topologies/mongos'); -connect.ReadPreference = require('mongodb-core').ReadPreference; -connect.GridStore = require('./lib/gridfs/grid_store'); -connect.Chunk = require('./lib/gridfs/chunk'); -connect.Logger = core.Logger; -connect.AggregationCursor = require('./lib/aggregation_cursor'); -connect.CommandCursor = require('./lib/command_cursor'); -connect.Cursor = require('./lib/cursor'); -connect.GridFSBucket = require('./lib/gridfs-stream'); -// Exported to be used in tests not to be used anywhere else -connect.CoreServer = require('mongodb-core').Server; -connect.CoreConnection = require('mongodb-core').Connection; - -// BSON types exported -connect.Binary = core.BSON.Binary; -connect.Code = core.BSON.Code; -connect.Map = core.BSON.Map; -connect.DBRef = core.BSON.DBRef; -connect.Double = core.BSON.Double; -connect.Int32 = core.BSON.Int32; -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; -connect.BSONRegExp = core.BSON.BSONRegExp; -connect.Decimal128 = core.BSON.Decimal128; - -// Add connect method -connect.connect = connect; - -// Set up the instrumentation method -connect.instrument = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - const instrumentation = new Instrumentation(); - instrumentation.instrument(connect.MongoClient, callback); - return instrumentation; -}; - -// Set our exports to be the connect function -module.exports = connect; diff --git a/node_modules/mongodb/lib/admin.js b/node_modules/mongodb/lib/admin.js deleted file mode 100644 index 8fb4cac56a0a7695476e4ac9db79d704008481f9..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/admin.js +++ /dev/null @@ -1,293 +0,0 @@ -'use strict'; - -const executeOperation = require('./utils').executeOperation; -const applyWriteConcern = require('./utils').applyWriteConcern; - -const addUser = require('./operations/db_ops').addUser; -const executeDbAdminCommand = require('./operations/db_ops').executeDbAdminCommand; -const removeUser = require('./operations/db_ops').removeUser; -const replSetGetStatus = require('./operations/admin_ops').replSetGetStatus; -const serverStatus = require('./operations/admin_ops').serverStatus; -const validateCollection = require('./operations/admin_ops').validateCollection; - -/** - * @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 - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Use the admin database for the operation - * const adminDb = client.db(dbName).admin(); - * - * // List all the available databases - * adminDb.listDatabases(function(err, dbs) { - * test.equal(null, err); - * test.ok(dbs.databases.length > 0); - * client.close(); - * }); - * }); - */ - -/** - * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {Admin} a collection instance. - */ -function Admin(db, topology, promiseLibrary) { - if (!(this instanceof Admin)) return new Admin(db, topology); - - // Internal state - this.s = { - db: db, - topology: topology, - promiseLibrary: promiseLibrary - }; -} - -/** - * 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.command = function(command, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - - return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ - this.s.db, - command, - options, - callback - ]); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.buildInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ - this.s.db, - cmd, - options, - callback - ]); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ - this.s.db, - cmd, - options, - callback - ]); -}; - -/** - * Retrieve this db's server status. - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.db.s.topology, serverStatus, [this, options, callback]); -}; - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.ping = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { ping: 1 }; - return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ - this.s.db, - cmd, - options, - callback - ]); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.addUser = function(username, password, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name to admin - options.dbName = 'admin'; - - return executeOperation(this.s.db.s.topology, addUser, [ - this.s.db, - username, - password, - options, - callback - ]); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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 {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.removeUser = function(username, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name - options.dbName = 'admin'; - - return executeOperation(this.s.db.s.topology, removeUser, [ - this.s.db, - username, - options, - callback - ]); -}; - -/** - * Validate an existing collection - * - * @param {string} collectionName The name of the collection to validate. - * @param {object} [options] Optional settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.db.s.topology, validateCollection, [ - this, - collectionName, - options, - callback - ]); -}; - -/** - * List the available databases - * - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.listDatabases = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { listDatabases: 1 }; - if (options.nameOnly) cmd.nameOnly = Number(cmd.nameOnly); - return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ - this.s.db, - cmd, - options, - callback - ]); -}; - -/** - * Get ReplicaSet status - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.replSetGetStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.db.s.topology, replSetGetStatus, [this, options, callback]); -}; - -module.exports = Admin; diff --git a/node_modules/mongodb/lib/aggregation_cursor.js b/node_modules/mongodb/lib/aggregation_cursor.js deleted file mode 100644 index e1bff13ef671ebda799f2feccf2e6e246f605404..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/aggregation_cursor.js +++ /dev/null @@ -1,407 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const MongoError = require('mongodb-core').MongoError; -const Readable = require('stream').Readable; -const CoreCursor = require('./cursor'); - -/** - * @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 4.X - * or higher stream - * - * **AGGREGATIONCURSOR Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).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); - * client.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 state = AggregationCursor.INIT; - var streamOptions = {}; - - // MaxTimeMS - var maxTimeMS = null; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary || Promise; - - // Set up - Readable.call(this, { objectMode: true }); - - // Internal state - this.s = { - // MaxTimeMS - maxTimeMS: maxTimeMS, - // 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, - // Promise library - promiseLibrary: promiseLibrary, - // Optional ClientSession - session: options.session - }; -}; - -/** - * 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); - -// 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 MongoError.create({ message: 'Cursor is closed', driver: true }); - if (typeof value !== 'number') - throw MongoError.create({ message: 'batchSize requires an integer', drvier: true }); - 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 lookup stage to the aggregation pipeline - * @method - * @param {object} document The lookup stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.lookup = function(document) { - this.s.cmd.pipeline.push({ $lookup: 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; -}; - -/** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ -AggregationCursor.prototype.getLogger = function() { - return this.logger; -}; - -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 {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function AggregationCursor.prototype.hasNext - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * 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 {Promise} returns Promise if no callback passed - */ - -/** - * 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 {Promise} returns Promise if no callback passed - */ - -/** - * 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 {Promise} returns Promise if no callback passed - */ - -/** - * 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; diff --git a/node_modules/mongodb/lib/apm.js b/node_modules/mongodb/lib/apm.js deleted file mode 100644 index f78e4aaff621ac70a0dc46896a84aa4ee16042cd..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/apm.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; -const EventEmitter = require('events').EventEmitter; - -class Instrumentation extends EventEmitter { - constructor() { - super(); - } - - instrument(MongoClient, callback) { - // store a reference to the original functions - this.$MongoClient = MongoClient; - const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); - - const instrumentation = this; - MongoClient.prototype.connect = function(callback) { - this.s.options.monitorCommands = true; - this.on('commandStarted', event => instrumentation.emit('started', event)); - this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); - this.on('commandFailed', event => instrumentation.emit('failed', event)); - return $prototypeConnect.call(this, callback); - }; - - if (typeof callback === 'function') callback(null, this); - } - - uninstrument() { - this.$MongoClient.prototype.connect = this.$prototypeConnect; - } -} - -module.exports = Instrumentation; diff --git a/node_modules/mongodb/lib/authenticate.js b/node_modules/mongodb/lib/authenticate.js deleted file mode 100644 index 35c92b426747eaef4a2be775c61812fb162752a9..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/authenticate.js +++ /dev/null @@ -1,136 +0,0 @@ -'use strict'; - -var shallowClone = require('./utils').shallowClone, - handleCallback = require('./utils').handleCallback, - MongoError = require('mongodb-core').MongoError, - f = require('util').format; - -var authenticate = function(client, username, password, options, callback) { - // Did the user destroy the topology - if (client.topology && client.topology.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // the default db to authenticate against is 'self' - // if authententicate is called from a retry context, it may be another one, like admin - var authdb = options.dbName; - authdb = options.authdb ? options.authdb : authdb; - authdb = options.authSource ? options.authSource : authdb; - - // Callback - var _callback = function(err, result) { - if (client.listeners('authenticated').length > 0) { - client.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') { - client.topology.auth('mongocr', authdb, username, password, function(err) { - if (err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if (authMechanism === 'PLAIN') { - client.topology.auth('plain', authdb, username, password, function(err) { - if (err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if (authMechanism === 'MONGODB-X509') { - client.topology.auth('x509', authdb, username, password, function(err) { - if (err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if (authMechanism === 'SCRAM-SHA-1') { - client.topology.auth('scram-sha-1', authdb, username, password, function(err) { - if (err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if (authMechanism === 'SCRAM-SHA-256') { - client.topology.auth('scram-sha-256', authdb, username, password, function(err) { - if (err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if (authMechanism === 'GSSAPI') { - if (process.platform === 'win32') { - client.topology.auth('sspi', authdb, username, password, options, function(err) { - if (err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else { - client.topology.auth('gssapi', authdb, username, password, options, function(err) { - if (err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } - } else if (authMechanism === 'DEFAULT') { - client.topology.auth('default', authdb, username, password, function(err) { - if (err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else { - handleCallback( - callback, - MongoError.create({ - message: f('authentication mechanism %s not supported', options.authMechanism), - driver: true - }) - ); - } -}; - -module.exports = function(self, username, password, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Shallow copy the options - options = shallowClone(options); - - // Set default mechanism - if (!options.authMechanism) { - options.authMechanism = 'DEFAULT'; - } else if ( - options.authMechanism !== 'GSSAPI' && - options.authMechanism !== 'DEFAULT' && - options.authMechanism !== 'MONGODB-CR' && - options.authMechanism !== 'MONGODB-X509' && - options.authMechanism !== 'SCRAM-SHA-1' && - options.authMechanism !== 'SCRAM-SHA-256' && - options.authMechanism !== 'PLAIN' - ) { - return handleCallback( - callback, - MongoError.create({ - message: - 'only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism', - driver: true - }) - ); - } - - // If we have a callback fallback - if (typeof callback === 'function') - return authenticate(self, username, password, options, function(err, r) { - // Support failed auth method - if (err && err.message && err.message.indexOf('saslStart') !== -1) err.code = 59; - // Reject error - if (err) return callback(err, r); - callback(null, r); - }); - - // Return a promise - return new self.s.promiseLibrary(function(resolve, reject) { - authenticate(self, username, password, options, function(err, r) { - // Support failed auth method - if (err && err.message && err.message.indexOf('saslStart') !== -1) err.code = 59; - // Reject error - if (err) return reject(err); - resolve(r); - }); - }); -}; diff --git a/node_modules/mongodb/lib/bulk/common.js b/node_modules/mongodb/lib/bulk/common.js deleted file mode 100644 index 18c9ccf9fd1384a78b6891b93b533a587ad1f012..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/bulk/common.js +++ /dev/null @@ -1,1113 +0,0 @@ -'use strict'; - -const Long = require('mongodb-core').BSON.Long; -const MongoError = require('mongodb-core').MongoError; -const toError = require('../utils').toError; -const handleCallback = require('../utils').handleCallback; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const ObjectID = require('mongodb-core').BSON.ObjectID; -const BSON = require('mongodb-core').BSON; - -// Error codes -const UNKNOWN_ERROR = 8; -const INVALID_BSON_ERROR = 22; -const WRITE_CONCERN_ERROR = 64; -const MULTIPLE_ERROR = 65; - -// Insert types -const INSERT = 1; -const UPDATE = 2; -const REMOVE = 3; - -const bson = new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp -]); - -/** - * Keeps the state of a unordered batch so we can rewrite the results - * correctly after command execution - * @ignore - */ -class Batch { - constructor(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 - */ -class LegacyOp { - constructor(batchType, operation, index) { - this.batchType = batchType; - this.index = index; - this.operation = operation; - } -} - -/** - * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @return {BulkWriteResult} a BulkWriteResult instance - */ -class BulkWriteResult { - constructor(bulkResult) { - this.result = bulkResult; - } - - /** - * @return {boolean} ok Did bulk operation correctly execute - */ - get ok() { - return this.result.ok; - } - - /** - * @return {number} nInserted number of inserted documents - */ - get nInserted() { - return this.result.nInserted; - } - - /** - * @return {number} nUpserted Number of upserted documents - */ - get nUpserted() { - return this.result.nUpserted; - } - - /** - * @return {number} nMatched Number of matched documents - */ - get nMatched() { - return this.result.nMatched; - } - - /** - * @return {number} nModified Number of documents updated physically on disk - */ - get nModified() { - return this.result.nModified; - } - - /** - * @return {number} nRemoved Number of removed documents - */ - get nRemoved() { - return this.result.nRemoved; - } - - /** - * Return an array of inserted ids - * - * @return {object[]} - */ - getInsertedIds() { - return this.result.insertedIds; - } - - /** - * Return an array of upserted ids - * - * @return {object[]} - */ - getUpsertedIds() { - return this.result.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} - */ - getUpsertedIdAt(index) { - return this.result.upserted[index]; - } - - /** - * Return raw internal result - * - * @return {object} - */ - getRawResponse() { - return this.result; - } - - /** - * Returns true if the bulk operation contains a write error - * - * @return {boolean} - */ - hasWriteErrors() { - return this.result.writeErrors.length > 0; - } - - /** - * Returns the number of write errors off the bulk operation - * - * @return {number} - */ - getWriteErrorCount() { - return this.result.writeErrors.length; - } - - /** - * Returns a specific write error object - * - * @param {number} index of the write error to return, returns null if there is no result for passed in index - * @return {WriteError} - */ - getWriteErrorAt(index) { - if (index < this.result.writeErrors.length) { - return this.result.writeErrors[index]; - } - return null; - } - - /** - * Retrieve all write errors - * - * @return {object[]} - */ - getWriteErrors() { - return this.result.writeErrors; - } - - /** - * Retrieve lastOp if available - * - * @return {object} - */ - getLastOp() { - return this.result.lastOp; - } - - /** - * Retrieve the write concern error if any - * - * @return {WriteConcernError} - */ - getWriteConcernError() { - if (this.result.writeConcernErrors.length === 0) { - return null; - } else if (this.result.writeConcernErrors.length === 1) { - // Return the error - return this.result.writeConcernErrors[0]; - } else { - // Combine the errors - let errmsg = ''; - for (let i = 0; i < this.result.writeConcernErrors.length; i++) { - const err = this.result.writeConcernErrors[i]; - errmsg = errmsg + err.errmsg; - - // TODO: Something better - if (i === 0) errmsg = errmsg + ' and '; - } - - return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); - } - } - - /** - * @return {BulkWriteResult} a BulkWriteResult instance - */ - toJSON() { - return this.result; - } - - /** - * @return {string} - */ - toString() { - return `BulkWriteResult(${this.toJSON(this.result)})`; - } - - /** - * @return {boolean} - */ - isOk() { - return this.result.ok === 1; - } -} - -/** - * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @return {WriteConcernError} a WriteConcernError instance - */ -class WriteConcernError { - constructor(err) { - this.err = err; - } - - /** - * @return {number} code Write concern error code. - */ - get code() { - return this.err.code; - } - - /** - * @return {string} errmsg Write concern error message. - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, errmsg: this.err.errmsg }; - } - - /** - * @return {string} - */ - toString() { - return `WriteConcernError(${this.err.errmsg})`; - } -} - -/** - * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @return {WriteConcernError} a WriteConcernError instance - */ -class WriteError { - constructor(err) { - this.err = err; - } - - /** - * @return {number} code Write concern error code. - */ - get code() { - return this.err.code; - } - - /** - * @return {number} index Write concern error original bulk operation index. - */ - get index() { - return this.err.index; - } - - /** - * @return {string} errmsg Write concern error message. - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * Define access methods - * @return {object} - */ - getOperation() { - return this.err.op; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; - } - - /** - * @return {string} - */ - toString() { - return `WriteError(${JSON.stringify(this.toJSON())})`; - } -} - -/** - * Merges results into shared data structure - * @ignore - */ -function mergeBatchResults(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; - - const 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; - } - - // Deal with opTime if available - if (result.opTime || result.lastOp) { - const opTime = result.lastOp || result.opTime; - let lastOpTS = null; - let lastOpT = null; - - // We have a time stamp - if (opTime && opTime._bsontype === 'Timestamp') { - if (bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if (opTime.greaterThan(bulkResult.lastOp)) { - bulkResult.lastOp = opTime; - } - } else { - // Existing TS - if (bulkResult.lastOp) { - lastOpTS = - typeof bulkResult.lastOp.ts === 'number' - ? Long.fromNumber(bulkResult.lastOp.ts) - : bulkResult.lastOp.ts; - lastOpT = - typeof bulkResult.lastOp.t === 'number' - ? Long.fromNumber(bulkResult.lastOp.t) - : bulkResult.lastOp.t; - } - - // Current OpTime TS - const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; - const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; - - // Compare the opTime's - if (bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.greaterThan(lastOpTS)) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.equals(lastOpTS)) { - if (opTimeT.greaterThan(lastOpT)) { - bulkResult.lastOp = opTime; - } - } - } - } - - // 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; - } - - let 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 (let 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) { - const 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 (let i = 0; i < result.writeErrors.length; i++) { - const 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)); - } -} - -/** - * handles write concern error - * - * @param {object} batch - * @param {object} bulkResult - * @param {boolean} ordered - * @param {WriteConcernError} err - * @param {function} callback - */ -function handleMongoWriteConcernError(batch, bulkResult, ordered, err, callback) { - mergeBatchResults(ordered, batch, bulkResult, null, err.result); - - const wrappedWriteConcernError = new WriteConcernError({ - errmsg: err.result.writeConcernError.errmsg, - code: err.result.writeConcernError.result - }); - return handleCallback( - callback, - new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), - null - ); -} - -/** - * Creates a new BulkWriteError - * - * @class - * @param {Error|string|object} message The error message - * @param {BulkWriteResult} result The result of the bulk write operation - * @return {BulkWriteError} A BulkWriteError instance - * @extends {MongoError} - */ -class BulkWriteError extends MongoError { - constructor(error, result) { - const message = error.err || error.errmsg || error.errMessage || error; - super(message); - - Object.assign(this, error); - - this.name = 'BulkWriteError'; - this.result = result; - } -} - -/** - * Handles the find operators for the bulk operations - * @class - */ -class FindOperators { - /** - * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation - */ - constructor(bulkOperation) { - this.s = bulkOperation.s; - } - - /** - * Add a single update document to the bulk operation - * - * @method - * @param {object} updateDocument update operations - * @throws {MongoError} - * @return {OrderedBulkOperation|UnordedBulkOperation} - */ - update(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: true, - upsert: upsert - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a single update one document to the bulk operation - * - * @method - * @param {object} updateDocument update operations - * @throws {MongoError} - * @return {OrderedBulkOperation|UnordedBulkOperation} - */ - updateOne(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: false, - upsert: upsert - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} updateDocument the new document to replace the existing one with - * @throws {MongoError} - * @return {OrderedBulkOperation|UnorderedBulkOperation} - */ - replaceOne(updateDocument) { - this.updateOne(updateDocument); - } - - /** - * Upsert modifier for update bulk operation - * - * @method - * @throws {MongoError} - * @return {FindOperators} - */ - upsert() { - this.s.currentOp.upsert = true; - return this; - } - - /** - * Add a delete one operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {OrderedBulkOperation|UnordedBulkOperation} - */ - deleteOne() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 1 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * Add a delete operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {OrderedBulkOperation|UnordedBulkOperation} - */ - delete() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 0 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * backwards compatability for deleteOne - */ - removeOne() { - return this.deleteOne(); - } - - /** - * backwards compatability for delete - */ - remove() { - return this.delete(); - } -} - -/** - * Parent class to OrderedBulkOperation and UnorderedBulkOperation - * @class - */ -class BulkOperationBase { - /** - * Create a new OrderedBulkOperation or UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {number} length Get the number of operations in the bulk. - * @return {OrderedBulkOperation|UnordedBulkOperation} - */ - constructor(topology, collection, options, isOrdered) { - // determine whether bulkOperation is ordered or unordered - this.isOrdered = isOrdered; - - options = options == null ? {} : options; - // TODO Bring from driver information in isMaster - // Get the namespace for the write operations - const namespace = collection.collectionName; - // Used to mark operation as executed - const executed = false; - - // Current item - const currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - const bson = topology.bson; - - // Set max byte size - const isMaster = topology.lastIsMaster(); - const maxBatchSizeBytes = - isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; - const maxWriteBatchSize = - isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; - - // Calculates the largest possible size of an Array key, represented as a BSON string - // element. This calculation: - // 1 byte for BSON type - // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) - // + 1 bytes for null terminator - const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, collection.s.db); - finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); - const writeConcern = finalOptions.writeConcern; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Final results - const 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, - // ordered specific - currentBatchSize: 0, - currentBatchSizeBytes: 0, - // unordered specific - currentInsertBatch: null, - currentUpdateBatch: null, - currentRemoveBatch: null, - batches: [], - // Write concern - writeConcern: writeConcern, - // Max batch size options - maxBatchSizeBytes: maxBatchSizeBytes, - maxWriteBatchSize: maxWriteBatchSize, - maxKeySize, - // Namespace - namespace: namespace, - // BSON - bson: bson, - // Topology - topology: topology, - // Options - options: finalOptions, - // Current operation - currentOp: currentOp, - // Executed - executed: executed, - // Collection - collection: collection, - // Promise Library - promiseLibrary: promiseLibrary, - // Fundamental error - err: null, - // check keys - checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true - }; - - // bypass Validation - if (options.bypassDocumentValidation === true) { - this.s.bypassDocumentValidation = true; - } - } - - /** - * Add a single insert document to the bulk operation - * - * @param {object} document the document to insert - * @throws {MongoError} - * @return {OrderedBulkOperation|UnorderedBulkOperation} - */ - insert(document) { - if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) - document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, 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} - */ - find(selector) { - if (!selector) { - throw toError('Bulk find operation must specify a selector'); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - }; - - return new FindOperators(this); - } - - /** - * Raw performs the bulk operation - * - * @method - * @param {object} op operation - * @return {OrderedBulkOperation|UnorderedBulkOperation} - */ - raw(op) { - const key = Object.keys(op)[0]; - - // Set up the force server object id - const forceServerObjectId = - typeof this.s.options.forceServerObjectId === 'boolean' - ? this.s.options.forceServerObjectId - : this.s.collection.s.db.options.forceServerObjectId; - - // 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 this.s.options.addToOperationsList(this, UPDATE, op[key]); - } - - // Crud spec update format - if (op.updateOne || op.updateMany || op.replaceOne) { - const multi = op.updateOne || op.replaceOne ? false : true; - const operation = { - q: op[key].filter, - u: op[key].update || op[key].replacement, - multi: multi - }; - if (this.isOrdered) { - operation.upsert = op[key].upsert ? true : false; - if (op.collation) operation.collation = op.collation; - } else { - if (op[key].upsert) operation.upsert = true; - } - if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; - return this.s.options.addToOperationsList(this, 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 this.s.options.addToOperationsList(this, REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if (op.deleteOne || op.deleteMany) { - const limit = op.deleteOne ? 1 : 0; - const operation = { q: op[key].filter, limit: limit }; - if (this.isOrdered) { - if (op.collation) operation.collation = op.collation; - } - return this.s.options.addToOperationsList(this, REMOVE, operation); - } - - // Insert operations - if (op.insertOne && op.insertOne.document == null) { - if (forceServerObjectId !== true && op.insertOne._id == null) - op.insertOne._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne); - } else if (op.insertOne && op.insertOne.document) { - if (forceServerObjectId !== true && op.insertOne.document._id == null) - op.insertOne.document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); - } - - if (op.insertMany) { - for (let i = 0; i < op.insertMany.length; i++) { - if (forceServerObjectId !== true && op.insertMany[i]._id == null) - op.insertMany[i]._id = new ObjectID(); - this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError( - 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' - ); - } - - /** - * Execute next write command in a chain - * - * @method - * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation - * @param {object} writeConcern - * @param {object} options - * @param {function} callback - */ - bulkExecute(_writeConcern, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (this.s.executed) { - const executedError = toError('batch cannot be re-executed'); - return typeof callback === 'function' - ? callback(executedError, null) - : this.s.promiseLibrary.reject(executedError); - } - - if (typeof _writeConcern === 'function') { - callback = _writeConcern; - } else if (_writeConcern && typeof _writeConcern === 'object') { - this.s.writeConcern = _writeConcern; - } - - // If we have current batch - if (this.isOrdered) { - if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); - } else { - 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) { - const emptyBatchError = toError('Invalid Operation, no operations specified'); - return typeof callback === 'function' - ? callback(emptyBatchError, null) - : this.s.promiseLibrary.reject(emptyBatchError); - } - return { options, callback }; - } - - /** - * Handles final options before executing command - * - * @param {object} config - * @param {object} config.options - * @param {number} config.batch - * @param {function} config.resultHandler - * @param {function} callback - */ - finalOptionsHandler(config, callback) { - const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); - if (this.s.writeConcern != null) { - finalOptions.writeConcern = this.s.writeConcern; - } - - if (finalOptions.bypassDocumentValidation !== true) { - delete finalOptions.bypassDocumentValidation; - } - - // Set an operationIf if provided - if (this.operationId) { - config.resultHandler.operationId = this.operationId; - } - - // Serialize functions - if (this.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true; - } - - // Ignore undefined - if (this.s.options.ignoreUndefined) { - finalOptions.ignoreUndefined = true; - } - - // Is the bypassDocumentValidation options specific - if (this.s.bypassDocumentValidation === true) { - finalOptions.bypassDocumentValidation = true; - } - - // Is the checkKeys option disabled - if (this.s.checkKeys === false) { - finalOptions.checkKeys = false; - } - - if (finalOptions.retryWrites) { - if (config.batch.batchType === UPDATE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); - } - - if (config.batch.batchType === REMOVE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); - } - } - - try { - if (config.batch.batchType === INSERT) { - this.s.topology.insert( - this.s.collection.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === UPDATE) { - this.s.topology.update( - this.s.collection.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === REMOVE) { - this.s.topology.remove( - this.s.collection.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } - } catch (err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - handleCallback( - callback, - null, - mergeBatchResults(false, config.batch, this.s.bulkResult, err, null) - ); - } - } - - /** - * Handles the write error before executing commands - * - * @param {function} callback - * @param {BulkWriteResult} writeResult - * @param {class} self either OrderedBulkOperation or UnorderdBulkOperation - */ - handleWriteError(callback, writeResult) { - if (this.s.bulkResult.writeErrors.length > 0) { - if (this.s.bulkResult.writeErrors.length === 1) { - handleCallback( - callback, - new BulkWriteError(toError(this.s.bulkResult.writeErrors[0]), writeResult), - null - ); - return true; - } - - handleCallback( - callback, - new BulkWriteError( - toError({ - message: 'write operation failed', - code: this.s.bulkResult.writeErrors[0].code, - writeErrors: this.s.bulkResult.writeErrors - }), - writeResult - ), - null - ); - return true; - } else if (writeResult.getWriteConcernError()) { - handleCallback( - callback, - new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), - null - ); - return true; - } - } -} - -Object.defineProperty(BulkOperationBase.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -// Exports symbols -module.exports = { - Batch, - BulkOperationBase, - BulkWriteError, - BulkWriteResult, - bson, - FindOperators, - handleMongoWriteConcernError, - LegacyOp, - mergeBatchResults, - INVALID_BSON_ERROR: INVALID_BSON_ERROR, - MULTIPLE_ERROR: MULTIPLE_ERROR, - UNKNOWN_ERROR: UNKNOWN_ERROR, - WRITE_CONCERN_ERROR: WRITE_CONCERN_ERROR, - INSERT: INSERT, - UPDATE: UPDATE, - REMOVE: REMOVE, - WriteError, - WriteConcernError -}; diff --git a/node_modules/mongodb/lib/bulk/ordered.js b/node_modules/mongodb/lib/bulk/ordered.js deleted file mode 100644 index 9f8e4b5c7f7f8a79b3ae2c4679c3440db62ab7b0..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/bulk/ordered.js +++ /dev/null @@ -1,182 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const utils = require('../utils'); -const toError = utils.toError; -const handleCallback = utils.handleCallback; -const BulkWriteResult = common.BulkWriteResult; -const Batch = common.Batch; -const mergeBatchResults = common.mergeBatchResults; -const executeOperation = utils.executeOperation; -const MongoWriteConcernError = require('mongodb-core').MongoWriteConcernError; -const handleMongoWriteConcernError = require('./common').handleMongoWriteConcernError; -const bson = common.bson; -const isPromiseLike = require('../utils').isPromiseLike; - -/** - * Add to internal list of Operations - * - * @param {OrderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {OrderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false - }); - - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Check if we need to create a new batch - if ( - bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || - bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes || - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Reset the current size trackers - bulkOperation.s.currentBatchSize = 0; - bulkOperation.s.currentBatchSizeBytes = 0; - } - - if (docType === common.INSERT) { - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.currentIndex, - _id: document._id - }); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatchSize += 1; - bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize; - bulkOperation.s.currentIndex += 1; - - // Return bulkOperation - return bulkOperation; -} - -/** - * 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. - */ - -class OrderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, true); - } - - /** - * 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] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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 {Promise} returns Promise if no callback passed - */ - execute(_writeConcern, options, callback) { - const ret = this.bulkExecute(_writeConcern, options, callback); - if (isPromiseLike(ret)) { - return ret; - } - - options = ret.options; - callback = ret.callback; - - return executeOperation(this.s.topology, executeCommands, [this, options, callback]); - } -} - -/** - * Execute next write command in a chain - * - * @param {OrderedBulkOperation} bulkOperation - * @param {object} options - * @param {function} callback - */ -function executeCommands(bulkOperation, options, callback) { - if (bulkOperation.s.batches.length === 0) { - return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); - } - - // Ordered execution of the command - const batch = bulkOperation.s.batches.shift(); - - function resultHandler(err, result) { - // Error is a driver related error not a bulk op error, terminate - if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { - return handleCallback(callback, err); - } - - // If we have and error - if (err) err.ok = 0; - if (err instanceof MongoWriteConcernError) { - return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, true, err, callback); - } - - // Merge the results together - const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); - const mergeResult = mergeBatchResults(true, batch, bulkOperation.s.bulkResult, err, result); - if (mergeResult != null) { - return handleCallback(callback, null, writeResult); - } - - if (bulkOperation.handleWriteError(callback, writeResult)) return; - - // Execute the next command in line - executeCommands(bulkOperation, options, callback); - } - - bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeOrderedBulkOp(topology, collection, options) { - return new OrderedBulkOperation(topology, collection, options); -} - -initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; -module.exports = initializeOrderedBulkOp; -module.exports.Bulk = OrderedBulkOperation; diff --git a/node_modules/mongodb/lib/bulk/unordered.js b/node_modules/mongodb/lib/bulk/unordered.js deleted file mode 100644 index 563777bfdf392ce1e89233fedd4dbd076f635e8b..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/bulk/unordered.js +++ /dev/null @@ -1,219 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const utils = require('../utils'); -const toError = utils.toError; -const handleCallback = utils.handleCallback; -const BulkWriteResult = common.BulkWriteResult; -const Batch = common.Batch; -const mergeBatchResults = common.mergeBatchResults; -const executeOperation = utils.executeOperation; -const MongoWriteConcernError = require('mongodb-core').MongoWriteConcernError; -const handleMongoWriteConcernError = require('./common').handleMongoWriteConcernError; -const bson = common.bson; -const isPromiseLike = require('../utils').isPromiseLike; - -/** - * Add to internal list of Operations - * - * @param {UnorderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {UnorderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false - }); - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); - // Holds the current batch - bulkOperation.s.currentBatch = null; - // Get the right type of batch - if (docType === common.INSERT) { - bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; - } else if (docType === common.UPDATE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; - } - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Check if we need to create a new batch - if ( - bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || - bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes || - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; - - // Save back the current Batch to the right type - if (docType === common.INSERT) { - bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.bulkResult.insertedIds.length, - _id: document._id - }); - } else if (docType === common.UPDATE) { - bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; - } - - // Update current batch size - bulkOperation.s.currentBatch.size += 1; - bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {number} length Get the number of operations in the bulk. - * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. - */ -class UnorderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, false); - } - - /** - * 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] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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 {Promise} returns Promise if no callback passed - */ - execute(_writeConcern, options, callback) { - const ret = this.bulkExecute(_writeConcern, options, callback); - if (isPromiseLike(ret)) { - return ret; - } - - options = ret.options; - callback = ret.callback; - - return executeOperation(this.s.topology, executeBatches, [this, options, callback]); - } -} - -/** - * Execute the command - * - * @param {UnorderedBulkOperation} bulkOperation - * @param {object} batch - * @param {object} options - * @param {function} callback - */ -function executeBatch(bulkOperation, batch, options, callback) { - function resultHandler(err, result) { - // Error is a driver related error not a bulk op error, terminate - if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { - return handleCallback(callback, err); - } - - // If we have and error - if (err) err.ok = 0; - if (err instanceof MongoWriteConcernError) { - return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, false, err, callback); - } - handleCallback( - callback, - null, - mergeBatchResults(false, batch, bulkOperation.s.bulkResult, err, result) - ); - } - - bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); -} - -/** - * Execute all the commands - * - * @param {UnorderedBulkOperation} bulkOperation - * @param {object} options - * @param {function} callback - */ -function executeBatches(bulkOperation, options, callback) { - let numberOfCommandsToExecute = bulkOperation.s.batches.length; - let hasErrored = false; - // Execute over all the batches - for (let i = 0; i < bulkOperation.s.batches.length; i++) { - executeBatch(bulkOperation, bulkOperation.s.batches[i], options, function(err) { - if (hasErrored) { - return; - } - - if (err) { - hasErrored = true; - return handleCallback(callback, err); - } - // Count down the number of commands left to execute - numberOfCommandsToExecute = numberOfCommandsToExecute - 1; - - // Execute - if (numberOfCommandsToExecute === 0) { - // Driver level error - if (err) return handleCallback(callback, err); - - const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); - if (bulkOperation.handleWriteError(callback, writeResult)) return; - - return handleCallback(callback, null, writeResult); - } - }); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeUnorderedBulkOp(topology, collection, options) { - return new UnorderedBulkOperation(topology, collection, options); -} - -initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; -module.exports = initializeUnorderedBulkOp; -module.exports.Bulk = UnorderedBulkOperation; diff --git a/node_modules/mongodb/lib/change_stream.js b/node_modules/mongodb/lib/change_stream.js deleted file mode 100644 index 21f24285425af6ffb15fe6a7eeac067c27a6ce78..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/change_stream.js +++ /dev/null @@ -1,469 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'); -const isResumableError = require('./error').isResumableError; -const MongoError = require('mongodb-core').MongoError; - -var cursorOptionNames = ['maxAwaitTimeMS', 'collation', 'readPreference']; - -const CHANGE_DOMAIN_TYPES = { - COLLECTION: Symbol('Collection'), - DATABASE: Symbol('Database'), - CLUSTER: Symbol('Cluster') -}; - -/** - * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. - * @class ChangeStream - * @since 3.0.0 - * @param {(MongoClient|Db|Collection)} changeDomain The domain against which to create the change stream - * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @fires ChangeStream#close - * @fires ChangeStream#change - * @fires ChangeStream#end - * @fires ChangeStream#error - * @return {ChangeStream} a ChangeStream instance. - */ - -class ChangeStream extends EventEmitter { - constructor(changeDomain, pipeline, options) { - super(); - const Collection = require('./collection'); - const Db = require('./db'); - const MongoClient = require('./mongo_client'); - - this.pipeline = pipeline || []; - this.options = options || {}; - this.cursorNamespace = undefined; - this.namespace = {}; - - if (changeDomain instanceof Collection) { - this.type = CHANGE_DOMAIN_TYPES.COLLECTION; - this.topology = changeDomain.s.db.serverConfig; - - this.namespace = { - collection: changeDomain.collectionName, - database: changeDomain.s.db.databaseName - }; - - this.cursorNamespace = `${this.namespace.database}.${this.namespace.collection}`; - } else if (changeDomain instanceof Db) { - this.type = CHANGE_DOMAIN_TYPES.DATABASE; - this.namespace = { collection: '', database: changeDomain.databaseName }; - this.cursorNamespace = this.namespace.database; - this.topology = changeDomain.serverConfig; - } else if (changeDomain instanceof MongoClient) { - this.type = CHANGE_DOMAIN_TYPES.CLUSTER; - this.namespace = { collection: '', database: 'admin' }; - this.cursorNamespace = this.namespace.database; - this.topology = changeDomain.topology; - } else { - throw new TypeError( - 'changeDomain provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' - ); - } - - this.promiseLibrary = changeDomain.s.promiseLibrary; - if (!this.options.readPreference && changeDomain.s.readPreference) { - this.options.readPreference = changeDomain.s.readPreference; - } - - // We need to get the operationTime as early as possible - const isMaster = this.topology.lastIsMaster(); - if (!isMaster) { - throw new MongoError('Topology does not have an ismaster yet.'); - } - - this.operationTime = isMaster.operationTime; - - // Create contained Change Stream cursor - this.cursor = createChangeStreamCursor(this); - - // Listen for any `change` listeners being added to ChangeStream - this.on('newListener', eventName => { - if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { - this.cursor.on('data', change => - processNewChange({ changeStream: this, change, eventEmitter: true }) - ); - } - }); - - // Listen for all `change` listeners being removed from ChangeStream - this.on('removeListener', eventName => { - if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { - this.cursor.removeAllListeners('data'); - } - }); - } - - /** - * Check if there is any document still available in the Change Stream - * @function ChangeStream.prototype.hasNext - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - hasNext(callback) { - return this.cursor.hasNext(callback); - } - - /** - * Get the next available document from the Change Stream, returns null if no more documents are available. - * @function ChangeStream.prototype.next - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - next(callback) { - var self = this; - if (this.isClosed()) { - if (callback) return callback(new Error('Change Stream is not open.'), null); - return self.promiseLibrary.reject(new Error('Change Stream is not open.')); - } - - return this.cursor - .next() - .then(change => processNewChange({ changeStream: self, change, callback })) - .catch(error => processNewChange({ changeStream: self, error, callback })); - } - - /** - * Is the cursor closed - * @method ChangeStream.prototype.isClosed - * @return {boolean} - */ - isClosed() { - if (this.cursor) { - return this.cursor.isClosed(); - } - return true; - } - - /** - * Close the Change Stream - * @method ChangeStream.prototype.close - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(callback) { - if (!this.cursor) { - if (callback) return callback(); - return this.promiseLibrary.resolve(); - } - - // Tidy up the existing cursor - var cursor = this.cursor; - delete this.cursor; - return cursor.close(callback); - } - - /** - * 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. - * @method - * @param {Writable} destination The destination for writing data - * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} - * @return {null} - */ - pipe(destination, options) { - if (!this.pipeDestinations) { - this.pipeDestinations = []; - } - this.pipeDestinations.push(destination); - return this.cursor.pipe(destination, options); - } - - /** - * This method will remove the hooks set up for a previous pipe() call. - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - unpipe(destination) { - if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { - this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); - } - return this.cursor.unpipe(destination); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - */ - stream(options) { - this.streamOptions = options; - return this.cursor.stream(options); - } - - /** - * 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. - * @return {null} - */ - pause() { - return this.cursor.pause(); - } - - /** - * This method will cause the readable stream to resume emitting data events. - * @return {null} - */ - resume() { - return this.cursor.resume(); - } -} - -// Create a new change stream cursor based on self's configuration -var createChangeStreamCursor = function(self) { - if (self.resumeToken) { - self.options.resumeAfter = self.resumeToken; - } - - var changeStreamCursor = buildChangeStreamAggregationCommand(self); - - /** - * Fired for each new matching change in the specified namespace. Attaching a `change` - * event listener to a Change Stream will switch the stream into flowing mode. Data will - * then be passed as soon as it is available. - * - * @event ChangeStream#change - * @type {object} - */ - if (self.listenerCount('change') > 0) { - changeStreamCursor.on('data', function(change) { - processNewChange({ changeStream: self, change, eventEmitter: true }); - }); - } - - /** - * Change stream close event - * - * @event ChangeStream#close - * @type {null} - */ - changeStreamCursor.on('close', function() { - self.emit('close'); - }); - - /** - * Change stream end event - * - * @event ChangeStream#end - * @type {null} - */ - changeStreamCursor.on('end', function() { - self.emit('end'); - }); - - /** - * Fired when the stream encounters an error. - * - * @event ChangeStream#error - * @type {Error} - */ - changeStreamCursor.on('error', function(error) { - processNewChange({ changeStream: self, error, eventEmitter: true }); - }); - - if (self.pipeDestinations) { - const cursorStream = changeStreamCursor.stream(self.streamOptions); - for (let pipeDestination in self.pipeDestinations) { - cursorStream.pipe(pipeDestination); - } - } - - return changeStreamCursor; -}; - -function getResumeToken(self) { - return self.resumeToken || self.options.resumeAfter; -} - -function getStartAtOperationTime(self) { - const isMaster = self.topology.lastIsMaster() || {}; - return ( - isMaster.maxWireVersion && isMaster.maxWireVersion >= 7 && self.options.startAtOperationTime - ); -} - -var buildChangeStreamAggregationCommand = function(self) { - const topology = self.topology; - const namespace = self.namespace; - const pipeline = self.pipeline; - const options = self.options; - const cursorNamespace = self.cursorNamespace; - - var changeStreamStageOptions = { - fullDocument: options.fullDocument || 'default' - }; - - const resumeToken = getResumeToken(self); - const startAtOperationTime = getStartAtOperationTime(self); - if (resumeToken) { - changeStreamStageOptions.resumeAfter = resumeToken; - } - - if (startAtOperationTime) { - changeStreamStageOptions.startAtOperationTime = startAtOperationTime; - } - - // Map cursor options - var cursorOptions = {}; - cursorOptionNames.forEach(function(optionName) { - if (options[optionName]) { - cursorOptions[optionName] = options[optionName]; - } - }); - - if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { - changeStreamStageOptions.allChangesForCluster = true; - } - - var changeStreamPipeline = [{ $changeStream: changeStreamStageOptions }]; - - changeStreamPipeline = changeStreamPipeline.concat(pipeline); - - var command = { - aggregate: self.type === CHANGE_DOMAIN_TYPES.COLLECTION ? namespace.collection : 1, - pipeline: changeStreamPipeline, - readConcern: { level: 'majority' }, - cursor: { - batchSize: options.batchSize || 1 - } - }; - - // Create and return the cursor - return topology.cursor(cursorNamespace, command, cursorOptions); -}; - -// This method performs a basic server selection loop, satisfying the requirements of -// ChangeStream resumability until the new SDAM layer can be used. -const SELECTION_TIMEOUT = 30000; -function waitForTopologyConnected(topology, options, callback) { - setTimeout(() => { - if (options && options.start == null) options.start = process.hrtime(); - const start = options.start || process.hrtime(); - const timeout = options.timeout || SELECTION_TIMEOUT; - const readPreference = options.readPreference; - - if (topology.isConnected({ readPreference })) return callback(null, null); - const hrElapsed = process.hrtime(start); - const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6; - if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection')); - waitForTopologyConnected(topology, options, callback); - }, 3000); // this is an arbitrary wait time to allow SDAM to transition -} - -// Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream. -function processNewChange(args) { - const changeStream = args.changeStream; - const error = args.error; - const change = args.change; - const callback = args.callback; - const eventEmitter = args.eventEmitter || false; - - // If the changeStream is closed, then it should not process a change. - if (changeStream.isClosed()) { - // We do not error in the eventEmitter case. - if (eventEmitter) { - return; - } - - const error = new MongoError('ChangeStream is closed'); - return typeof callback === 'function' - ? callback(error, null) - : changeStream.promiseLibrary.reject(error); - } - - const topology = changeStream.topology; - const options = changeStream.cursor.options; - - if (error) { - if (isResumableError(error) && !changeStream.attemptingResume) { - changeStream.attemptingResume = true; - - if (!(getResumeToken(changeStream) || getStartAtOperationTime(changeStream))) { - const startAtOperationTime = changeStream.cursor.cursorState.operationTime; - changeStream.options = Object.assign({ startAtOperationTime }, changeStream.options); - } - - // stop listening to all events from old cursor - ['data', 'close', 'end', 'error'].forEach(event => - changeStream.cursor.removeAllListeners(event) - ); - - // close internal cursor, ignore errors - changeStream.cursor.close(); - - // attempt recreating the cursor - if (eventEmitter) { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) return changeStream.emit('error', err); - changeStream.cursor = createChangeStreamCursor(changeStream); - }); - - return; - } - - if (callback) { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) return callback(err, null); - - changeStream.cursor = createChangeStreamCursor(changeStream); - changeStream.next(callback); - }); - - return; - } - - return new Promise((resolve, reject) => { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) return reject(err); - resolve(); - }); - }) - .then(() => (changeStream.cursor = createChangeStreamCursor(changeStream))) - .then(() => changeStream.next()); - } - - if (eventEmitter) return changeStream.emit('error', error); - if (typeof callback === 'function') return callback(error, null); - return changeStream.promiseLibrary.reject(error); - } - - changeStream.attemptingResume = false; - - // Cache the resume token if it is present. If it is not present return an error. - if (!change || !change._id) { - var noResumeTokenError = new Error( - 'A change stream document has been received that lacks a resume token (_id).' - ); - - if (eventEmitter) return changeStream.emit('error', noResumeTokenError); - if (typeof callback === 'function') return callback(noResumeTokenError, null); - return changeStream.promiseLibrary.reject(noResumeTokenError); - } - - changeStream.resumeToken = change._id; - - // Return the change - if (eventEmitter) return changeStream.emit('change', change); - if (typeof callback === 'function') return callback(error, change); - return changeStream.promiseLibrary.resolve(change); -} - -/** - * The callback format for results - * @callback ChangeStream~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. - */ - -module.exports = ChangeStream; diff --git a/node_modules/mongodb/lib/collection.js b/node_modules/mongodb/lib/collection.js deleted file mode 100644 index b5b178276d087a81a029de0509ff7bc3eb1bc568..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/collection.js +++ /dev/null @@ -1,2099 +0,0 @@ -'use strict'; - -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const checkCollectionName = require('./utils').checkCollectionName; -const ObjectID = require('mongodb-core').BSON.ObjectID; -const AggregationCursor = require('./aggregation_cursor'); -const MongoError = require('mongodb-core').MongoError; -const toError = require('./utils').toError; -const normalizeHintField = require('./utils').normalizeHintField; -const handleCallback = require('./utils').handleCallback; -const decorateCommand = require('./utils').decorateCommand; -const decorateWithCollation = require('./utils').decorateWithCollation; -const decorateWithReadConcern = require('./utils').decorateWithReadConcern; -const formattedOrderClause = require('./utils').formattedOrderClause; -const ReadPreference = require('mongodb-core').ReadPreference; -const CommandCursor = require('./command_cursor'); -const unordered = require('./bulk/unordered'); -const ordered = require('./bulk/ordered'); -const ChangeStream = require('./change_stream'); -const executeOperation = require('./utils').executeOperation; -const applyWriteConcern = require('./utils').applyWriteConcern; -const resolveReadPreference = require('./utils').resolveReadPreference; - -// Operations -const bulkWrite = require('./operations/collection_ops').bulkWrite; -const checkForAtomicOperators = require('./operations/collection_ops').checkForAtomicOperators; -const count = require('./operations/collection_ops').count; -const countDocuments = require('./operations/collection_ops').countDocuments; -const createIndex = require('./operations/collection_ops').createIndex; -const createIndexes = require('./operations/collection_ops').createIndexes; -const deleteMany = require('./operations/collection_ops').deleteMany; -const deleteOne = require('./operations/collection_ops').deleteOne; -const distinct = require('./operations/collection_ops').distinct; -const dropIndex = require('./operations/collection_ops').dropIndex; -const dropIndexes = require('./operations/collection_ops').dropIndexes; -const ensureIndex = require('./operations/collection_ops').ensureIndex; -const findAndModify = require('./operations/collection_ops').findAndModify; -const findAndRemove = require('./operations/collection_ops').findAndRemove; -const findOne = require('./operations/collection_ops').findOne; -const findOneAndDelete = require('./operations/collection_ops').findOneAndDelete; -const findOneAndReplace = require('./operations/collection_ops').findOneAndReplace; -const findOneAndUpdate = require('./operations/collection_ops').findOneAndUpdate; -const geoHaystackSearch = require('./operations/collection_ops').geoHaystackSearch; -const group = require('./operations/collection_ops').group; -const indexes = require('./operations/collection_ops').indexes; -const indexExists = require('./operations/collection_ops').indexExists; -const indexInformation = require('./operations/collection_ops').indexInformation; -const insertOne = require('./operations/collection_ops').insertOne; -const isCapped = require('./operations/collection_ops').isCapped; -const mapReduce = require('./operations/collection_ops').mapReduce; -const optionsOp = require('./operations/collection_ops').optionsOp; -const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; -const prepareDocs = require('./operations/collection_ops').prepareDocs; -const reIndex = require('./operations/collection_ops').reIndex; -const removeDocuments = require('./operations/collection_ops').removeDocuments; -const rename = require('./operations/collection_ops').rename; -const replaceOne = require('./operations/collection_ops').replaceOne; -const save = require('./operations/collection_ops').save; -const stats = require('./operations/collection_ops').stats; -const updateDocuments = require('./operations/collection_ops').updateDocuments; -const updateMany = require('./operations/collection_ops').updateMany; -const updateOne = require('./operations/collection_ops').updateOne; - -/** - * @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 - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - */ - -const mergeKeys = ['ignoreUndefined']; - -/** - * 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} readConcern The current read concern values. - * @property {object} hint Get current index hint for collection. - * @return {Collection} a Collection instance. - */ -function Collection(db, topology, dbName, name, pkFactory, options) { - checkCollectionName(name); - - // Unpack variables - const internalHint = null; - const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - const serializeFunctions = - options == null || options.serializeFunctions == null - ? db.s.options.serializeFunctions - : options.serializeFunctions; - const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; - const promoteLongs = - options == null || options.promoteLongs == null - ? db.s.options.promoteLongs - : options.promoteLongs; - const promoteValues = - options == null || options.promoteValues == null - ? db.s.options.promoteValues - : options.promoteValues; - const promoteBuffers = - options == null || options.promoteBuffers == null - ? db.s.options.promoteBuffers - : options.promoteBuffers; - let readPreference = null; - const collectionHint = null; - const namespace = `${dbName}.${name}`; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // 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, - // SlaveOK - slaveOk: slaveOk, - // Serialize functions - serializeFunctions: serializeFunctions, - // Raw - raw: raw, - // promoteLongs - promoteLongs: promoteLongs, - // promoteValues - promoteValues: promoteValues, - // promoteBuffers - promoteBuffers: promoteBuffers, - // internalHint - internalHint: internalHint, - // collectionHint - collectionHint: collectionHint, - // Name - name: name, - // Promise library - promiseLibrary: promiseLibrary, - // Read Concern - readConcern: options.readConcern, - // Write Concern - writeConcern: options.writeConcern - }; -} - -Object.defineProperty(Collection.prototype, 'dbName', { - enumerable: true, - get: function() { - return this.s.dbName; - } -}); - -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, 'readConcern', { - enumerable: true, - get: function() { - return this.s.readConcern || { level: 'local' }; - } -}); - -Object.defineProperty(Collection.prototype, 'writeConcern', { - enumerable: true, - get: function() { - let ops = {}; - if (this.s.writeConcern) { - return this.s.writeConcern; - } - - 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); - } -}); - -const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot']; - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * @method - * @param {object} [query={}] The cursor query object. - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] 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] DEPRECATED: 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] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @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 {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference] 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] Number of miliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @throws {MongoError} - * @return {Cursor} - */ -Collection.prototype.find = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - console.warn('Third parameter to `find()` must be a callback or undefined'); - } - - let selector = query; - // figuring out arguments - if (typeof callback !== 'function') { - if (typeof options === 'function') { - callback = options; - options = undefined; - } else if (options == null) { - callback = typeof selector === 'function' ? selector : undefined; - selector = typeof selector === 'object' ? selector : undefined; - } - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - const object = selector; - if (Buffer.isBuffer(object)) { - const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); - if (object_size !== object.length) { - const error = new Error( - 'query selector 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 != null && selector._bsontype === 'ObjectID') { - selector = { _id: selector }; - } - - if (!options) options = {}; - - let projection = options.projection || options.fields; - - if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { - projection = projection.length - ? projection.reduce((result, field) => { - result[field] = 1; - return result; - }, {}) - : { _id: 1 }; - } - - // Make a shallow copy of options - let newOptions = Object.assign({}, options); - - // Make a shallow copy of the collection options - for (let key in this.s.options) { - if (mergeKeys.indexOf(key) !== -1) { - newOptions[key] = this.s.options[key]; - } - } - - // Unpack options - newOptions.skip = options.skip ? options.skip : 0; - newOptions.limit = options.limit ? options.limit : 0; - newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; - newOptions.hint = - options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; - newOptions.timeout = 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.readPreference = resolveReadPreference(newOptions, { - db: this.s.db, - collection: 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 MongoError.create({ message: 'query selector must be an object', driver: true }); - } - - // Build the find command - const 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; - - decorateCommand(findCommand, newOptions, ['session', 'collation']); - - if (projection) findCommand.fields = projection; - - // Add db object to the new options - newOptions.db = this.s.db; - - // Add the promise library - newOptions.promiseLibrary = this.s.promiseLibrary; - - // Set raw if available at collection level - if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; - // Set promoteLongs if available at collection level - if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') - newOptions.promoteLongs = this.s.promoteLongs; - if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') - newOptions.promoteValues = this.s.promoteValues; - if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') - newOptions.promoteBuffers = this.s.promoteBuffers; - - // Sort options - if (findCommand.sort) { - findCommand.sort = formattedOrderClause(findCommand.sort); - } - - // Set the readConcern - decorateWithReadConcern(findCommand, this, options); - - // Decorate find command with collation options - try { - decorateWithCollation(findCommand, this, options); - } catch (err) { - if (typeof callback === 'function') return callback(err, null); - throw err; - } - - const cursor = this.s.topology.cursor(this.s.namespace, findCommand, newOptions); - - return typeof callback === 'function' ? handleCallback(callback, null, cursor) : cursor; - } -); - -/** - * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object} doc Document to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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 {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertOne = function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndfined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation(this.s.topology, insertOne, [this, doc, options, callback]); -}; - -function mapInsertManyResults(docs, r) { - const finalResult = { - result: { ok: 1, n: r.insertedCount }, - ops: docs, - insertedCount: r.insertedCount, - insertedIds: r.insertedIds - }; - - if (r.getLastOp()) { - finalResult.result.opTime = r.getLastOp(); - } - - return finalResult; -} - -/** - * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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 {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertMany = function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : { ordered: true }; - - if (!Array.isArray(docs) && typeof callback === 'function') { - return callback( - MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) - ); - } else if (!Array.isArray(docs)) { - return new this.s.promiseLibrary((resolve, reject) => { - reject( - MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) - ); - }); - } - - // If keep going set unordered - options['serializeFunctions'] = options['serializeFunctions'] || this.s.serializeFunctions; - - docs = prepareDocs(this, docs, options); - - // Generate the bulk write operations - const operations = [ - { - insertMany: docs - } - ]; - - return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback], { - resultMutator: result => mapInsertManyResults(docs, result) - }); -}; - -/** - * @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 {BulkWriteError} 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}} - * - * If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} operations Bulk operations to perform. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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.ordered=true] Execute write operation in ordered or unordered fashion. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~bulkWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.bulkWrite = function(operations, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: true }; - - if (!Array.isArray(operations)) { - throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); - } - - return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback]); -}; - -/** - * @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. - */ - -/** - * @typedef {Object} Collection~insertWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {Object.<Number, ObjectId>} insertedIds Map of the index of the inserted document to the id of the inserted document. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * @typedef {Object} Collection~insertOneWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * The callback format for inserts - * @callback Collection~insertWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * The callback format for inserts - * @callback Collection~insertOneWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {(object|object[])} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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 {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated Use insertOne, insertMany or bulkWrite - */ -Collection.prototype.insert = deprecate(function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: false }; - docs = !Array.isArray(docs) ? [docs] : docs; - - if (options.keepGoing === true) { - options.ordered = false; - } - - return this.insertMany(docs, options, callback); -}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~updateWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents scanned. - * @property {Number} result.nModified The total count of documents modified. - * @property {Object} connection The connection object used for the operation. - * @property {Number} matchedCount The number of documents that matched the filter. - * @property {Number} modifiedCount The number of documents that were modified. - * @property {Number} upsertedCount The number of documents upserted. - * @property {Object} upsertedId The upserted id. - * @property {ObjectId} upsertedId._id The upserted _id returned from the server. - * @property {Object} message - * @property {Array} ops - */ - -/** - * The callback format for inserts - * @callback Collection~updateWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Update a single document in a collection - * @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] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateOne = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - options = Object.assign({}, options); - - // Add ignoreUndfined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation(this.s.topology, updateOne, [this, filter, update, options, callback]); -}; - -/** - * Replace a document in a collection with another document - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} doc The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise<Collection~updatewriteOpResultObject>} returns Promise if no callback passed - */ -Collection.prototype.replaceOne = function(filter, doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndfined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation(this.s.topology, replaceOne, [this, filter, doc, options, callback]); -}; - -/** - * Update multiple documents in a collection - * @method - * @param {object} filter The Filter used to select the documents to update - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise<Collection~updateWriteOpResultObject>} returns Promise if no callback passed - */ -Collection.prototype.updateMany = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - options = Object.assign({}, options); - - // Add ignoreUndfined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation(this.s.topology, updateMany, [this, filter, update, options, callback]); -}; - -/** - * Updates documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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 {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - * @deprecated use updateOne, updateMany or bulkWrite - */ -Collection.prototype.update = deprecate(function(selector, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndfined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation(this.s.topology, updateDocuments, [ - this, - selector, - update, - options, - callback - ]); -}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~deleteWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents deleted. - * @property {Object} connection The connection object used for the operation. - * @property {Number} deletedCount The number of documents deleted. - */ - -/** - * The callback format for inserts - * @callback Collection~deleteWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Delete a document from a collection - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteOne = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndfined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation(this.s.topology, deleteOne, [this, filter, options, callback]); -}; - -Collection.prototype.removeOne = Collection.prototype.deleteOne; - -/** - * Delete multiple documents from a collection - * @method - * @param {object} filter The Filter used to select the documents to remove - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteMany = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndfined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation(this.s.topology, deleteMany, [this, filter, options, callback]); -}; - -Collection.prototype.removeMany = Collection.prototype.deleteMany; - -/** - * Remove documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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 {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use deleteOne, deleteMany or bulkWrite - */ -Collection.prototype.remove = deprecate(function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndfined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation(this.s.topology, removeDocuments, [this, selector, options, callback]); -}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); - -/** - * 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] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -Collection.prototype.save = deprecate(function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndfined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeOperation(this.s.topology, save, [this, doc, options, callback]); -}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); - -/** - * 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. - */ - -/** - * The callback format for an aggregation call - * @callback Collection~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -/** - * Fetches the first document that matches the query - * @method - * @param {object} query Query for find Operation - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] 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] DEPRECATED: 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] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @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 {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference] 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] Number of miliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOne = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - console.warn('Third parameter to `findOne()` must be a callback or undefined'); - } - - if (typeof query === 'function') (callback = query), (query = {}), (options = {}); - if (typeof options === 'function') (callback = options), (options = {}); - query = query || {}; - options = options || {}; - - return executeOperation(this.s.topology, findOne, [this, query, options, callback]); - } -); - -/** - * 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] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.rename = function(newName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - return executeOperation(this.s.topology, rename, [this, newName, options, callback]); -}; - -/** - * Drop the collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.drop = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, this.s.db.dropCollection.bind(this.s.db), [ - this.s.name, - options, - callback - ]); -}; - -/** - * Returns the options of the collection. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.options = function(opts, callback) { - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - return executeOperation(this.s.topology, optionsOp, [this, opts, callback]); -}; - -/** - * Returns if the collection is a capped collection - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.isCapped = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, isCapped, [this, options, callback]); -}; - -/** - * Creates an index on the db and collection collection. - * @method - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, createIndex, [this, 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 {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.createIndexes = function(indexSpecs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - - options = options ? Object.assign({}, options) : {}; - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - return executeOperation(this.s.topology, createIndexes, [this, indexSpecs, options, callback]); -}; - -/** - * Drops an index from this collection. - * @method - * @param {string} indexName Name of the index to drop. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndex = function(indexName, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() || {} : {}; - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - return executeOperation(this.s.topology, dropIndex, [this, indexName, options, callback]); -}; - -/** - * Drops all indexes from this collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - return executeOperation(this.s.topology, dropIndexes, [this, options, callback]); -}; - -/** - * Drops all indexes from this collection. - * @method - * @deprecated use dropIndexes - * @param {Collection~resultCallback} callback The command result callback - * @return {Promise} returns Promise if no [callback] passed - */ -Collection.prototype.dropAllIndexes = deprecate( - Collection.prototype.dropIndexes, - 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' -); - -/** - * 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 {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.reIndex = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, reIndex, [this, options, callback]); -}; - -/** - * Get the list of all indexes information for the collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.batchSize] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Collection.prototype.listIndexes = function(options) { - options = options || {}; - // Clone the options - options = Object.assign({}, options); - // Determine the read preference in the options. - options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this }); - // Set the CommandCursor constructor - options.cursorFactory = CommandCursor; - // Set the promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - if (!this.s.topology.capabilities()) { - throw new MongoError('cannot connect to server'); - } - - // Cursor options - let cursor = options.batchSize ? { batchSize: options.batchSize } : {}; - - // We have a list collections command - if (this.s.topology.capabilities().hasListIndexesCommand) { - // Build the command - const command = { listIndexes: this.s.name, cursor: cursor }; - // Execute the cursor - cursor = this.s.topology.cursor(`${this.s.dbName}.$cmd`, command, options); - // Do we have a readPreference, apply it - if (options.readPreference) cursor.setReadPreference(options.readPreference); - // Return the cursor - return cursor; - } - - // Get the namespace - const ns = `${this.s.dbName}.system.indexes`; - // Get the query - cursor = this.s.topology.cursor(ns, { find: ns, query: { ns: this.s.namespace } }, options); - // Do we have a readPreference, apply it - if (options.readPreference) cursor.setReadPreference(options.readPreference); - // Set the passed in batch size if one was provided - if (options.batchSize) cursor = cursor.batchSize(options.batchSize); - // Return the cursor - return cursor; -}; - -/** - * 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] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, ensureIndex, [this, fieldOrSpec, options, callback]); -}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); - -/** - * 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 {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexExists = function(indexes, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, indexExists, [this, indexes, options, callback]); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexInformation = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - return executeOperation(this.s.topology, indexInformation, [this, 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] Optional settings. - * @param {boolean} [options.limit] The limit of documents to count. - * @param {boolean} [options.skip] The number of documents to skip for the count. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~countCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead - */ -Collection.prototype.count = deprecate(function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - return executeOperation(this.s.topology, count, [this, query, options, callback]); -}, 'collection.count is deprecated, and will be removed in a future version.' + - ' Use collection.countDocuments or collection.estimatedDocumentCount instead'); - -/** - * Gets an estimate of the count of documents in a collection using collection metadata. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - */ -Collection.prototype.estimatedDocumentCount = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, count, [this, null, options, callback]); -}; - -/** - * Gets the number of documents matching the filter. - * - * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} - * the following query operators must be replaced: - * - * | Operator | Replacement | - * | -------- | ----------- | - * | `$where` | [`$expr`][1] | - * | `$near` | [`$geoWithin`][2] with [`$center`][3] | - * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | - * - * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ - * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - * - * @param {object} [query] the query for the count - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specifies a collation. - * @param {string|object} [options.hint] The index to use. - * @param {number} [options.limit] The maximum number of document to count. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {number} [options.skip] The number of documents to skip before counting. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ - * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - */ - -Collection.prototype.countDocuments = function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - return executeOperation(this.s.topology, countDocuments, [this, query, options, callback]); -}; - -/** - * 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.distinct = function(key, query, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - const queryOption = args.length ? args.shift() || {} : {}; - const optionsOption = args.length ? args.shift() || {} : {}; - - return executeOperation(this.s.topology, distinct, [ - this, - key, - queryOption, - optionsOption, - callback - ]); -}; - -/** - * Retrieve all the indexes on the collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, indexes, [this, options, callback]); -}; - -/** - * Get all the collection statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.stats = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - return executeOperation(this.s.topology, stats, [this, options, callback]); -}; - -/** - * @typedef {Object} Collection~findAndModifyWriteOpResult - * @property {object} value Document returned from findAndModify command. - * @property {object} lastErrorObject The raw lastErrorObject returned from the command. - * @property {Number} ok Is 1 if the command executed correctly. - */ - -/** - * The callback format for inserts - * @callback Collection~findAndModifyCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise<Collection~findAndModifyWriteOpResultObject>} returns Promise if no callback passed - */ -Collection.prototype.findOneAndDelete = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - - return executeOperation(this.s.topology, findOneAndDelete, [this, filter, options, 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 The Filter used to select the document to replace - * @param {object} replacement The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] 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 {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise<Collection~findAndModifyWriteOpResultObject>} returns Promise if no callback passed - */ -Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - if (replacement == null || typeof replacement !== 'object') - throw toError('replacement parameter must be an object'); - - return executeOperation(this.s.topology, findOneAndReplace, [ - this, - filter, - replacement, - options, - 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 The Filter used to select the document to update - * @param {object} update Update operations to be performed on the document - * @param {object} [options] Optional settings. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] 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 {ClientSession} [options.session] optional session to use for this operation - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise<Collection~findAndModifyWriteOpResultObject>} returns Promise if no callback passed - */ -Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - if (update == null || typeof update !== 'object') - throw toError('update parameter must be an object'); - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - return executeOperation(this.s.topology, findOneAndUpdate, [ - this, - filter, - update, - options, - 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] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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.projection] Object containing the field projection for the result returned from the operation. - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -Collection.prototype.findAndModify = deprecate(function(query, sort, doc, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Clone options - options = Object.assign({}, options); - // Force read preference primary - options.readPreference = ReadPreference.PRIMARY; - - return executeOperation(this.s.topology, findAndModify, [ - this, - query, - sort, - doc, - options, - callback - ]); -}, 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.'); - -/** - * 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] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndDelete instead - */ -Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - - return executeOperation(this.s.topology, findAndRemove, [this, query, sort, options, callback]); -}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); - -/** - * 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.cursor] 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] 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] 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 {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @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 {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~aggregationCallback} 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 - const args = Array.prototype.slice.call(arguments, 0); - // Get the callback - callback = args.pop(); - // Get the possible options object - const 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.hint || - opts.allowDiskUse) - ? args.pop() - : {}; - // Left over arguments is the pipeline - pipeline = args; - } - - // Ignore readConcern option - let ignoreReadConcern = false; - - // Build the command - const command = { aggregate: this.s.name, pipeline: pipeline }; - - // If out was specified - if (typeof options.out === 'string') { - pipeline.push({ $out: options.out }); - // Ignore read concern - ignoreReadConcern = true; - } else if (pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { - ignoreReadConcern = true; - } - - // Decorate command with writeConcern if out has been specified - if ( - pipeline.length > 0 && - pipeline[pipeline.length - 1]['$out'] && - this.s.topology.capabilities().commandsTakeWriteConcern - ) { - applyWriteConcern(command, { db: this.s.db, collection: this }, options); - } - - // Have we specified collation - try { - decorateWithCollation(command, this, options); - } catch (err) { - if (typeof callback === 'function') return callback(err, null); - throw err; - } - - // If we have bypassDocumentValidation set - if (options.bypassDocumentValidation === true) { - command.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Do we have a readConcern specified - if (!ignoreReadConcern) { - decorateWithReadConcern(command, this, options); - } - - // If we have allowDiskUse defined - if (options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; - if (typeof options.maxTimeMS === 'number') command.maxTimeMS = options.maxTimeMS; - - // If we are giving a hint - if (options.hint) command.hint = options.hint; - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this }); - - // If explain has been specified add it - if (options.explain) { - if (command.readConcern || command.writeConcern) { - throw toError('"explain" cannot be used on an aggregate call with readConcern/writeConcern'); - } - command.explain = options.explain; - } - - if (typeof options.comment === 'string') command.comment = options.comment; - - // Validate that cursor options is valid - if (options.cursor != null && typeof options.cursor !== 'object') { - throw toError('cursor options must be an object'); - } - - options.cursor = options.cursor || {}; - if (options.batchSize) options.cursor.batchSize = options.batchSize; - command.cursor = options.cursor; - - // promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // Set the AggregationCursor constructor - options.cursorFactory = AggregationCursor; - if (typeof callback !== 'function') { - if (!this.s.topology.capabilities()) { - throw new MongoError('cannot connect to server'); - } - - // 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); - } - - return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, command, options)); -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. - * @method - * @since 3.0.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Collection.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize] 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 {Promise} returns Promise if no callback passed - */ -Collection.prototype.parallelCollectionScan = function(options, callback) { - 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; - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this }); - - // Add a promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - if (options.session) { - options.session = undefined; - } - - return executeOperation(this.s.topology, parallelCollectionScan, [this, options, callback], { - skipSessions: true - }); -}; - -/** - * 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxDistance] Include results up to maxDistance from the point. - * @param {object} [options.search] Filter the results by a query. - * @param {number} [options.limit=false] Max number of results to return. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - return executeOperation(this.s.topology, geoHaystackSearch, [this, x, y, options, callback]); -}; - -/** - * 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. - */ -Collection.prototype.group = deprecate(function( - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback -) { - const args = Array.prototype.slice.call(arguments, 3); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - 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._bsontype === '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; - - return executeOperation(this.s.topology, group, [ - this, - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback - ]); -}, -'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); - -/** - * 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * @param {object} [options.query] Query filter object. - * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * @param {number} [options.limit] Number of objects to return from collection. - * @param {boolean} [options.keeptemp=false] Keep temporary data. - * @param {(function|string)} [options.finalize] Finalize function. - * @param {object} [options.scope] 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 {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.mapReduce = function(map, reduce, options, callback) { - 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(); - } - - return executeOperation(this.s.topology, mapReduce, [this, map, reduce, options, callback]); -}; - -/** - * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {UnorderedBulkOperation} - */ -Collection.prototype.initializeUnorderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - options.promiseLibrary = this.s.promiseLibrary; - 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] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {OrderedBulkOperation} callback The command result callback - * @return {null} - */ -Collection.prototype.initializeOrderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session's options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - options.promiseLibrary = this.s.promiseLibrary; - return ordered(this.s.topology, this, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Collection.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -module.exports = Collection; diff --git a/node_modules/mongodb/lib/command_cursor.js b/node_modules/mongodb/lib/command_cursor.js deleted file mode 100644 index 50afb6f85b8f97904fd7a146244c486ca841e4d7..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/command_cursor.js +++ /dev/null @@ -1,334 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const ReadPreference = require('mongodb-core').ReadPreference; -const MongoError = require('mongodb-core').MongoError; -const Readable = require('stream').Readable; -const CoreCursor = require('./cursor'); - -/** - * @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 - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).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); - * client.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 state = CommandCursor.INIT; - var streamOptions = {}; - - // MaxTimeMS - var maxTimeMS = null; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary || Promise; - - // Set up - Readable.call(this, { objectMode: true }); - - // Internal state - this.s = { - // MaxTimeMS - maxTimeMS: maxTimeMS, - // 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, - // Promise library - promiseLibrary: promiseLibrary, - // Optional ClientSession - session: options.session - }; -}; - -/** - * 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', - 'hasNext', - 'each', - 'forEach', - 'toArray', - 'rewind', - 'bufferedCount', - 'readBufferedDocuments', - 'close', - 'isClosed', - 'kill', - 'setCursorBatchSize', - '_find', - '_getmore', - '_killcursor', - 'isDead', - 'explain', - 'isNotified', - 'isKilled', - '_endSession', - '_initImplicitSession' -]; - -// Only inherit the types we need -for (var i = 0; i < methodsToInherit.length; i++) { - CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; -} - -/** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ -CommandCursor.prototype.setReadPreference = function(readPreference) { - if (this.s.state === CommandCursor.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (this.s.state !== CommandCursor.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.s.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.s.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; -}; - -/** - * 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 MongoError.create({ message: 'Cursor is closed', driver: true }); - if (typeof value !== 'number') - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - 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; -}; - -/** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ -CommandCursor.prototype.getLogger = function() { - return this.logger; -}; - -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 {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function CommandCursor.prototype.hasNext - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * 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 {Promise} returns Promise if no callback passed - */ - -/** - * 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 {Promise} returns Promise if no callback passed - */ - -/** - * 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; diff --git a/node_modules/mongodb/lib/constants.js b/node_modules/mongodb/lib/constants.js deleted file mode 100644 index d6cc68add8e3229f46b35078fe6959f4fcab2333..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/constants.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = { - SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', - SYSTEM_INDEX_COLLECTION: 'system.indexes', - SYSTEM_PROFILE_COLLECTION: 'system.profile', - SYSTEM_USER_COLLECTION: 'system.users', - SYSTEM_COMMAND_COLLECTION: '$cmd', - SYSTEM_JS_COLLECTION: 'system.js' -}; diff --git a/node_modules/mongodb/lib/cursor.js b/node_modules/mongodb/lib/cursor.js deleted file mode 100644 index 4a0b815f675c642b3d981b94e5b8de4e0ead3b2f..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/cursor.js +++ /dev/null @@ -1,1152 +0,0 @@ -'use strict'; - -const Transform = require('stream').Transform; -const PassThrough = require('stream').PassThrough; -const inherits = require('util').inherits; -const deprecate = require('util').deprecate; -const handleCallback = require('./utils').handleCallback; -const ReadPreference = require('mongodb-core').ReadPreference; -const MongoError = require('mongodb-core').MongoError; -const Readable = require('stream').Readable; -const CoreCursor = require('mongodb-core').Cursor; -const Map = require('mongodb-core').BSON.Map; -const executeOperation = require('./utils').executeOperation; - -const count = require('./operations/cursor_ops').count; -const each = require('./operations/cursor_ops').each; -const hasNext = require('./operations/cursor_ops').hasNext; -const next = require('./operations/cursor_ops').next; -const toArray = require('./operations/cursor_ops').toArray; - -/** - * @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 4.X - * or higher stream - * - * **CURSORS Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).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); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the mongodb-core and node.js - * @external CoreCursor - * @external Readable - */ - -// Flags allowed for cursor -const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; -const 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 - * Cursor cursor options. - * - * collection.find({}).project({a:1}) // Create a projection of field a - * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 - * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 - * collection.find({}).filter({a:1}) // Set query on the cursor - * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries - * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable - * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay - * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout - * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData - * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial - * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} - * collection.find({}).max(10) // Set the cursor max - * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS - * collection.find({}).min(100) // Set the cursor min - * collection.find({}).returnKey(true) // Set the cursor returnKey - * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference - * collection.find({}).showRecordId(true) // Set the cursor showRecordId - * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query - * collection.find({}).hint('a_1') // Set the cursor hint - * - * All options are chainable, so one can do the following. - * - * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) - */ -function Cursor(bson, ns, cmd, options, topology, topologyOptions) { - CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); - const state = Cursor.INIT; - const streamOptions = {}; - - // Tailable cursor options - const numberOfRetries = options.numberOfRetries || 5; - const tailableRetryInterval = options.tailableRetryInterval || 500; - const currentNumberOfRetries = numberOfRetries; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // 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, - // Promise library - promiseLibrary: promiseLibrary, - // Current doc - currentDoc: null, - // explicitlyIgnoreSession - explicitlyIgnoreSession: options.explicitlyIgnoreSession - }; - - // Optional ClientSession - if (!options.explicitlyIgnoreSession && options.session) { - this.s.session = options.session; - } - - // Translate correctly - if (this.s.options.noCursorTimeout === true) { - this.addCursorFlag('noCursorTimeout', true); - } - - // Set the sort value - this.sortValue = this.s.cmd.sort; - - // Get the batchSize - const batchSize = - cmd.cursor && cmd.cursor.batchSize - ? cmd.cursor && cmd.cursor.batchSize - : options.cursor && options.cursor.batchSize - ? options.cursor.batchSize - : 1000; - - // Set the batchSize - this.setCursorBatchSize(batchSize); -} - -/** - * 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 -Cursor.prototype._next = function() { - if (this._initImplicitSession) { - this._initImplicitSession(); - } - return CoreCursor.prototype.next.apply(this, arguments); -}; - -for (let name in CoreCursor.prototype) { - Cursor.prototype[name] = CoreCursor.prototype[name]; -} - -Cursor.prototype._initImplicitSession = function() { - if (!this.s.explicitlyIgnoreSession && !this.s.session && this.s.topology.hasSessionSupport()) { - this.s.session = this.s.topology.startSession({ owner: this }); - this.cursorState.session = this.s.session; - } -}; - -Cursor.prototype._endSession = function() { - const didCloseCursor = CoreCursor.prototype._endSession.apply(this, arguments); - if (didCloseCursor) { - this.s.session = undefined; - } -}; - -/** - * Check if there is any document still available in the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.hasNext = function(callback) { - return executeOperation(this.s.topology, hasNext, [this, callback], { - skipSessions: true - }); -}; - -/** - * 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} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.next = function(callback) { - return executeOperation(this.s.topology, next, [this, callback], { - skipSessions: true - }); -}; - -/** - * 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 MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.s.cmd.query = filter; - return this; -}; - -/** - * Set the cursor maxScan - * @method - * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ -Cursor.prototype.maxScan = deprecate(function(maxScan) { - if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.s.cmd.maxScan = maxScan; - return this; -}, 'Cursor.maxScan is deprecated, and will be removed in a later version'); - -/** - * Set the cursor hint - * @method - * @param {object} hint If specified, then the query system will only consider plans using the hinted index. - * @return {Cursor} - */ -Cursor.prototype.hint = function(hint) { - if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.s.cmd.hint = hint; - return this; -}; - -/** - * Set the cursor min - * @method - * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. - * @return {Cursor} - */ -Cursor.prototype.min = function(min) { - if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - this.s.cmd.min = min; - return this; -}; - -/** - * Set the cursor max - * @method - * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. - * @return {Cursor} - */ -Cursor.prototype.max = function(max) { - if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.s.cmd.max = max; - return this; -}; - -/** - * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. - * @method - * @param {bool} returnKey the returnKey value. - * @return {Cursor} - */ -Cursor.prototype.returnKey = function(value) { - if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.s.cmd.returnKey = value; - return this; -}; - -/** - * Set the cursor showRecordId - * @method - * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. - * @return {Cursor} - */ -Cursor.prototype.showRecordId = function(value) { - if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.s.cmd.showDiskLoc = value; - return this; -}; - -/** - * Set the cursor snapshot - * @method - * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ -Cursor.prototype.snapshot = deprecate(function(value) { - if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.s.cmd.snapshot = value; - return this; -}, 'Cursor Snapshot is deprecated, and will be removed in a later version'); - -/** - * 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 MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (fields.indexOf(field) === -1) { - throw MongoError.create({ - message: `option ${field} is not a supported option ${fields}`, - driver: true - }); - } - - 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', '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 MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (flags.indexOf(flag) === -1) { - throw MongoError.create({ - message: `flag ${flag} is not a supported flag ${flags}`, - driver: true - }); - } - - if (typeof value !== 'boolean') { - throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); - } - - 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 {string|boolean|number} value The modifier 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 MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (name[0] !== '$') { - throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); - } - - // Strip of the $ - const 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 MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.s.cmd.comment = value; - return this; -}; - -/** - * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) - * @method - * @param {number} value Number of milliseconds to wait before aborting the tailed query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.maxAwaitTimeMS = function(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); - } - - if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.s.cmd.maxAwaitTimeMS = 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 MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); - } - - if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - 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 MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - 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 MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); - } - - if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - let order = keyOrList; - - // We have an array of arrays, we need to preserve the order of the sort - // so we will us a Map - if (Array.isArray(order) && Array.isArray(order[0])) { - order = new Map( - order.map(x => { - const value = [x[0], null]; - if (x[1] === 'asc') { - value[1] = 1; - } else if (x[1] === 'desc') { - value[1] = -1; - } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { - value[1] = x[1]; - } else { - throw new MongoError( - "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return value; - }) - ); - } - - 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 MongoError.create({ message: "Tailable cursor doesn't support batchSize", driver: true }); - } - - if (this.s.state === Cursor.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.s.cmd.batchSize = value; - this.setCursorBatchSize(value); - return this; -}; - -/** - * Set the collation options for the cursor. - * @method - * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.collation = function(value) { - this.s.cmd.collation = 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 MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); - } - - if (this.s.state === Cursor.OPEN || this.s.state === Cursor.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'limit requires an integer', driver: true }); - } - - 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 MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); - } - - if (this.s.state === Cursor.OPEN || this.s.state === Cursor.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'skip requires an integer', driver: true }); - } - - 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|boolean)} result The result object if the command was executed successfully. - */ - -/** - * Clone the cursor - * @function external:CoreCursor#clone - * @return {Cursor} - */ - -/** - * Resets the cursor - * @function external:CoreCursor#rewind - * @return {null} - */ - -/** - * 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 = deprecate(function(callback) { - // Rewind cursor state - this.rewind(); - // Set current cursor to INIT - this.s.state = Cursor.INIT; - // Run the query - each(this, callback); -}, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); - -/** - * 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 {Promise} if no callback supplied - */ -Cursor.prototype.forEach = function(iterator, callback) { - // Rewind cursor state - this.rewind(); - - // Set current cursor to INIT - this.s.state = Cursor.INIT; - - if (typeof callback === 'function') { - each(this, (err, doc) => { - if (err) { - callback(err); - return false; - } - if (doc != null) { - iterator(doc); - return true; - } - if (doc == null && callback) { - const internalCallback = callback; - callback = null; - internalCallback(null); - return false; - } - }); - } else { - return new this.s.promiseLibrary((fulfill, reject) => { - each(this, (err, doc) => { - if (err) { - reject(err); - return false; - } else if (doc == null) { - fulfill(null); - return false; - } else { - iterator(doc); - return true; - } - }); - }); - } -}; - -/** - * 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(readPreference) { - if (this.s.state !== Cursor.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.s.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.s.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - 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 contains 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 {Promise} returns Promise if no callback passed - */ -Cursor.prototype.toArray = function(callback) { - if (this.s.options.tailable) { - throw MongoError.create({ - message: 'Tailable cursor cannot be converted to array', - driver: true - }); - } - - return executeOperation(this.s.topology, toArray, [this, callback], { - skipSessions: true - }); -}; - -/** - * 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=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. - * @param {object} [options] Optional settings. - * @param {number} [options.skip] The number of documents to skip. - * @param {number} [options.limit] The maximum amounts to count before aborting. - * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Cursor~countResultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.count = function(applySkipLimit, opts, callback) { - if (this.s.cmd.query == null) - throw MongoError.create({ message: 'count can only be used with find command', driver: true }); - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - if (typeof applySkipLimit === 'function') { - callback = applySkipLimit; - applySkipLimit = true; - } - - if (this.s.session) { - opts = Object.assign({}, opts, { session: this.s.session }); - } - - return executeOperation(this.s.topology, count, [this, applySkipLimit, opts, callback], { - skipSessions: !!this.s.session - }); -}; - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.close = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { skipKillCursors: false }, options); - - this.s.state = Cursor.CLOSED; - if (!options.skipKillCursors) { - // Kill the cursor - this.kill(); - } - - const completeClose = () => { - // Emit the close event for the cursor - this.emit('close'); - - // Callback if provided - if (typeof callback === 'function') { - return handleCallback(callback, null, this); - } - - // Return a Promise - return new this.s.promiseLibrary(resolve => { - resolve(); - }); - }; - - if (this.s.session) { - if (typeof callback === 'function') { - return this._endSession(() => completeClose()); - } - - return new this.s.promiseLibrary(resolve => { - this._endSession(() => completeClose().then(resolve)); - }); - } - - return completeClose(); -}; - -/** - * Map all documents using the provided function - * @method - * @param {function} [transform] The mapping transformation method. - * @return {Cursor} - */ -Cursor.prototype.map = function(transform) { - if (this.cursorState.transforms && this.cursorState.transforms.doc) { - const oldTransform = this.cursorState.transforms.doc; - this.cursorState.transforms.doc = doc => { - return transform(oldTransform(doc)); - }; - } else { - 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) { - if (err) this.emit('error', err); - this.pause(); - this.close(); -}; - -/** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - * TODO: replace this method with transformStream in next major release - */ -Cursor.prototype.stream = function(options) { - this.s.streamOptions = options || {}; - return this; -}; - -/** - * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, - * returns a stream of unmodified docs. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {stream} - */ -Cursor.prototype.transformStream = function(options) { - const streamOptions = options || {}; - if (typeof streamOptions.transform === 'function') { - const stream = new Transform({ - objectMode: true, - transform: function(chunk, encoding, callback) { - this.push(streamOptions.transform(chunk)); - callback(); - } - }); - - return this.pipe(stream); - } - return this.pipe(new PassThrough({ objectMode: true })); -}; - -/** - * Execute the explain for the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.explain = function(callback) { - this.s.cmd.explain = true; - - // Do we have a readConcern - if (this.s.cmd.readConcern) { - delete this.s.cmd['readConcern']; - } - - return executeOperation(this.s.topology, this._next.bind(this), [callback], { - skipSessions: true - }); -}; - -Cursor.prototype._read = function() { - if (this.s.state === Cursor.CLOSED || this.isDead()) { - return this.push(null); - } - - // Get the next item - this.next((err, result) => { - if (err) { - if (this.listeners('error') && this.listeners('error').length > 0) { - this.emit('error', err); - } - if (!this.isDead()) this.close(); - - // Emit end event - this.emit('end'); - return this.emit('finish'); - } - - // If we provided a transformation method - if (typeof this.s.streamOptions.transform === 'function' && result != null) { - return this.push(this.s.streamOptions.transform(result)); - } - - // If we provided a map function - if ( - this.cursorState.transforms && - typeof this.cursorState.transforms.doc === 'function' && - result != null - ) { - return this.push(this.cursorState.transforms.doc(result)); - } - - // Return the result - this.push(result); - - if (result === null && this.isDead()) { - this.once('end', () => { - this.close(); - this.emit('finish'); - }); - } - }); -}; - -/** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ -Cursor.prototype.getLogger = function() { - return this.logger; -}; - -Object.defineProperty(Cursor.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (!this || !this.s) { - return null; - } - - return this.s.options.readPreference; - } -}); - -Object.defineProperty(Cursor.prototype, 'namespace', { - enumerable: true, - get: function() { - if (!this || !this.s) { - return null; - } - - // TODO: refactor this logic into core - const ns = this.s.ns || ''; - const 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/mongodb/lib/db.js b/node_modules/mongodb/lib/db.js deleted file mode 100644 index b3257f3a3b3d23a5bb0e5901303c77ce4a9bd4ed..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/db.js +++ /dev/null @@ -1,985 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const inherits = require('util').inherits; -const getSingleProperty = require('./utils').getSingleProperty; -const CommandCursor = require('./command_cursor'); -const handleCallback = require('./utils').handleCallback; -const filterOptions = require('./utils').filterOptions; -const toError = require('./utils').toError; -const ReadPreference = require('mongodb-core').ReadPreference; -const MongoError = require('mongodb-core').MongoError; -const ObjectID = require('mongodb-core').ObjectID; -const Logger = require('mongodb-core').Logger; -const Collection = require('./collection'); -const mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern; -const executeOperation = require('./utils').executeOperation; -const applyWriteConcern = require('./utils').applyWriteConcern; -const resolveReadPreference = require('./utils').resolveReadPreference; -const ChangeStream = require('./change_stream'); -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const CONSTANTS = require('./constants'); - -// Operations -const addUser = require('./operations/db_ops').addUser; -const collections = require('./operations/db_ops').collections; -const createCollection = require('./operations/db_ops').createCollection; -const createIndex = require('./operations/db_ops').createIndex; -const createListener = require('./operations/db_ops').createListener; -const dropCollection = require('./operations/db_ops').dropCollection; -const dropDatabase = require('./operations/db_ops').dropDatabase; -const ensureIndex = require('./operations/db_ops').ensureIndex; -const evaluate = require('./operations/db_ops').evaluate; -const executeCommand = require('./operations/db_ops').executeCommand; -const executeDbAdminCommand = require('./operations/db_ops').executeDbAdminCommand; -const indexInformation = require('./operations/db_ops').indexInformation; -const listCollectionsTransforms = require('./operations/db_ops').listCollectionsTransforms; -const profilingInfo = require('./operations/db_ops').profilingInfo; -const profilingLevel = require('./operations/db_ops').profilingLevel; -const removeUser = require('./operations/db_ops').removeUser; -const setProfilingLevel = require('./operations/db_ops').setProfilingLevel; -const validateDatabaseName = require('./operations/db_ops').validateDatabaseName; - -/** - * @fileOverview The **Db** class is a class that represents a MongoDB Database. - * - * @example - * const MongoClient = require('mongodb').MongoClient; - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Select the database by name - * const testDb = client.db(dbName); - * client.close(); - * }); - */ - -// Allowed parameters -const legalOptionNames = [ - 'w', - 'wtimeout', - 'fsync', - 'j', - 'readPreference', - 'readPreferenceTags', - 'native_parser', - 'forceServerObjectId', - 'pkFactory', - 'serializeFunctions', - 'raw', - 'bufferMaxEntries', - 'authSource', - 'ignoreUndefined', - 'promoteLongs', - 'promiseLibrary', - 'readConcern', - 'retryMiliSeconds', - 'numberOfRetries', - 'parentDb', - 'noListener', - 'loggerLevel', - 'logger', - 'promoteBuffers', - 'promoteLongs', - 'promoteValues', - 'compression', - 'retryWrites' -]; - -/** - * 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] Optional settings. - * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @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.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @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 {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @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 {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @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. - * @property {object} topology Access the topology object (single server, replicaset or mongos). - * @fires Db#close - * @fires Db#reconnect - * @fires Db#error - * @fires Db#timeout - * @fires Db#parseError - * @fires Db#fullsetup - * @return {Db} a Db instance. - */ -function Db(databaseName, topology, options) { - options = options || {}; - if (!(this instanceof Db)) return new Db(databaseName, topology, options); - EventEmitter.call(this); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure we put the promiseLib in the options - options.promiseLibrary = promiseLibrary; - - // Internal state of the db object - this.s = { - // Database name - databaseName: databaseName, - // DbCache - dbCache: {}, - // 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, - // 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, - // Promise library - promiseLibrary: promiseLibrary, - // No listener - noListener: typeof options.noListener === 'boolean' ? options.noListener : false, - // ReadConcern - readConcern: options.readConcern - }; - - // Ensure we have a valid db name - validateDatabaseName(this.s.databaseName); - - // Add a read Only property - getSingleProperty(this, 'serverConfig', this.s.topology); - getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); - getSingleProperty(this, 'databaseName', this.s.databaseName); - - // This is a child db, do not register any listeners - if (options.parentDb) return; - if (this.s.noListener) return; - - // Add listeners - topology.on('error', createListener(this, 'error', this)); - topology.on('timeout', createListener(this, 'timeout', this)); - topology.on('close', createListener(this, 'close', this)); - topology.on('parseError', createListener(this, 'parseError', this)); - topology.once('open', createListener(this, 'open', this)); - topology.once('fullsetup', createListener(this, 'fullsetup', this)); - topology.once('all', createListener(this, 'all', this)); - topology.on('reconnect', createListener(this, 'reconnect', this)); -} - -inherits(Db, EventEmitter); - -// Topology -Object.defineProperty(Db.prototype, 'topology', { - enumerable: true, - get: function() { - return this.s.topology; - } -}); - -// Options -Object.defineProperty(Db.prototype, 'options', { - enumerable: true, - get: function() { - return this.s.options; - } -}); - -// slaveOk specified -Object.defineProperty(Db.prototype, 'slaveOk', { - enumerable: true, - get: function() { - if ( - this.s.options.readPreference != null && - (this.s.options.readPreference !== 'primary' || - this.s.options.readPreference.mode !== 'primary') - ) { - return true; - } - return false; - } -}); - -// get the write Concern -Object.defineProperty(Db.prototype, 'writeConcern', { - enumerable: true, - get: function() { - const 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; - } -}); - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.command = function(command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - return executeOperation(this.s.topology, executeCommand, [this, command, options, callback]); -}; - -/** - * Return the Admin db instance - * @method - * @return {Admin} return the new Admin db instance - */ -Db.prototype.admin = function() { - const Admin = require('./admin'); - - return new Admin(this, this.s.topology, this.s.promiseLibrary); -}; - -/** - * 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. - */ - -const collectionKeys = [ - 'pkFactory', - 'readPreference', - 'serializeFunctions', - 'strict', - 'readConcern', - 'ignoreUndefined', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs' -]; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you - * can use it without a callback in the following way: `const collection = db.collection('mycollection');` - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] 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 {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @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) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options = Object.assign({}, options); - - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // If we have not set a collection level readConcern set the db level one - options.readConcern = options.readConcern || this.s.readConcern; - - // Do we have ignoreUndefined set - if (this.s.options.ignoreUndefined) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Merge in all needed options and ensure correct writeConcern merging from db level - options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); - - // Execute - if (options == null || !options.strict) { - try { - const 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 (err instanceof MongoError && callback) return callback(err); - throw err; - } - } - - // Strict mode - if (typeof callback !== 'function') { - throw toError(`A callback is required in strict mode. While getting collection ${name}`); - } - - // Did the user destroy the topology - if (this.serverConfig && this.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); - - // Strict mode - this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length === 0) - return handleCallback( - callback, - toError(`Collection ${name} does not exist. Currently in strict mode.`), - null - ); - - try { - return handleCallback( - callback, - null, - new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err, null); - } - }); -}; - -/** - * Create a new collection on a server with the specified options. Use this to create capped collections. - * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] 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 {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 - * @param {number} [options.size] The size of the capped collection in bytes. - * @param {number} [options.max] The maximum number of documents in the capped collection. - * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. - * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. - * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. - * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. - * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. - * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. - * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. - * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. create creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createCollection = deprecateOptions( - { - name: 'Db.createCollection', - deprecatedOptions: ['autoIndexId'], - optionsIndex: 1 - }, - function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; - - return executeOperation(this.s.topology, createCollection, [this, name, options, callback]); - } -); - -/** - * Get all the db statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.stats = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Build command object - const commandObject = { dbStats: true }; - // Check if we have the scale value - if (options['scale'] != null) commandObject['scale'] = options['scale']; - - // If we have a readPreference set - if (options.readPreference == null && this.s.readPreference) { - options.readPreference = this.s.readPreference; - } - - // Execute the command - return this.command(commandObject, options, callback); -}; - -/** - * Get the list of all collection information for the specified db. - * - * @method - * @param {object} [filter={}] Query to filter collections by - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info - * @param {number} [options.batchSize] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Db.prototype.listCollections = function(filter, options) { - filter = filter || {}; - options = options || {}; - - // Shallow clone the object - options = Object.assign({}, options); - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // Ensure valid readPreference - options.readPreference = resolveReadPreference(options, { - db: this, - default: ReadPreference.primary - }); - - // Cursor options - let cursor = options.batchSize ? { batchSize: options.batchSize } : {}; - - // We have a list collections command - if (this.serverConfig.capabilities().hasListCollectionsCommand) { - const nameOnly = typeof options.nameOnly === 'boolean' ? options.nameOnly : false; - // Build the command - const command = { listCollections: true, filter, cursor, nameOnly }; - // Set the AggregationCursor constructor - options.cursorFactory = CommandCursor; - // Create the cursor - cursor = this.s.topology.cursor(`${this.s.databaseName}.$cmd`, command, options); - // Do we have a readPreference, apply it - if (options.readPreference) { - cursor.setReadPreference(options.readPreference); - } - // Return the cursor - return cursor; - } - - // 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 = Object.assign({}, filter); - filter.name = `${this.s.databaseName}.${filter.name}`; - } - } - - // No filter, filter by current database - if (filter == null) { - filter.name = `/${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 - const _options = { transforms: listCollectionsTransforms(this.s.databaseName) }; - // Get the cursor - cursor = this.collection(CONSTANTS.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options); - // Do we have a readPreference, apply it - if (options.readPreference) cursor.setReadPreference(options.readPreference); - // 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] Optional settings. - * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.eval = deprecate(function(code, parameters, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - return executeOperation(this.s.topology, evaluate, [this, code, parameters, options, callback]); -}, 'Db.eval is deprecated as of MongoDB version 3.2'); - -/** - * 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] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Add return new collection - options.new_collection = true; - - const collection = this.collection(fromCollection); - return executeOperation(this.s.topology, collection.rename.bind(collection), [ - 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 {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropCollection = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Command to execute - const cmd = { drop: name }; - - // Decorate with write concern - applyWriteConcern(cmd, { db: this }, options); - - // options - const opts = Object.assign({}, this.s.options, { readPreference: ReadPreference.PRIMARY }); - if (options.session) opts.session = options.session; - - return executeOperation(this.s.topology, dropCollection, [this, cmd, opts, callback]); -}; - -/** - * Drop a database, removing it permanently from the server. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropDatabase = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Drop database command - const cmd = { dropDatabase: 1 }; - - // Decorate with write concern - applyWriteConcern(cmd, { db: this }, options); - - // Ensure primary only - const finalOptions = Object.assign({}, this.s.options, { - readPreference: ReadPreference.PRIMARY - }); - - if (options.session) { - finalOptions.session = options.session; - } - - return executeOperation(this.s.topology, dropDatabase, [this, cmd, finalOptions, callback]); -}; - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionsResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.collections = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, collections, [this, options, callback]); -}; - -/** - * Runs a command on the database as admin. - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.executeDbAdminCommand = function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.readPreference = resolveReadPreference(options); - - return executeOperation(this.s.topology, executeDbAdminCommand, [ - this, - selector, - options, - callback - ]); -}; - -/** - * Creates an index on the db and collection. - * @method - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - return executeOperation(this.s.topology, createIndex, [ - this, - name, - fieldOrSpec, - options, - callback - ]); -}; - -/** - * 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] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, ensureIndex, [ - this, - name, - fieldOrSpec, - options, - callback - ]); -}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); - -Db.prototype.addChild = function(db) { - if (this.s.parentDb) return this.s.parentDb.addChild(db); - this.s.children.push(db); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.addUser = function(username, password, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, addUser, [this, username, password, options, callback]); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.removeUser = function(username, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, removeUser, [this, username, options, callback]); -}; - -/** - * Set the current profiling level of MongoDB - * - * @param {string} level The new profiling level (off, slow_only, all). - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.setProfilingLevel = function(level, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, setProfilingLevel, [this, level, options, callback]); -}; - -/** - * Retrive the current profiling information for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Query the system.profile collection directly. - */ -Db.prototype.profilingInfo = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, profilingInfo, [this, options, callback]); -}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.profilingLevel = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, profilingLevel, [this, options, callback]); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.indexInformation = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.s.topology, indexInformation, [this, name, options, callback]); -}; - -/** - * Unref all sockets - * @method - */ -Db.prototype.unref = function() { - this.s.topology.unref(); -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Db.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Db.prototype.getLogger = function() { - return this.s.logger; -}; - -/** - * Db close event - * - * Emitted after a socket closed against a single server or mongos proxy. - * - * @event Db#close - * @type {MongoError} - */ - -/** - * Db reconnect event - * - * * Server: Emitted when the driver has reconnected and re-authenticated. - * * ReplicaSet: N/A - * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. - * - * @event Db#reconnect - * @type {object} - */ - -/** - * Db error event - * - * Emitted after an error occurred against a single server or mongos proxy. - * - * @event Db#error - * @type {MongoError} - */ - -/** - * Db timeout event - * - * Emitted after a socket timeout occurred against a single server or mongos proxy. - * - * @event Db#timeout - * @type {MongoError} - */ - -/** - * Db parseError event - * - * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. - * - * @event Db#parseError - * @type {MongoError} - */ - -/** - * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. - * - * * Server: Emitted when the driver has connected to the single server and has authenticated. - * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. - * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. - * - * @event Db#fullsetup - * @type {Db} - */ - -// Constants -Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; -Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; -Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; -Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; -Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; -Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; - -module.exports = Db; diff --git a/node_modules/mongodb/lib/error.js b/node_modules/mongodb/lib/error.js deleted file mode 100644 index 03b555ad4c73c581aca499ee453293de9ddf7df4..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/error.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -const MongoNetworkError = require('mongodb-core').MongoNetworkError; -const mongoErrorContextSymbol = require('mongodb-core').mongoErrorContextSymbol; - -const GET_MORE_NON_RESUMABLE_CODES = new Set([ - 136, // CappedPositionLost - 237, // CursorKilled - 11601 // Interrupted -]); - -// From spec@https://github.com/mongodb/specifications/blob/35e466ddf25059cb30e4113de71cdebd3754657f/source/change-streams.rst#resumable-error: -// -// An error is considered resumable if it meets any of the following criteria: -// - any error encountered which is not a server error (e.g. a timeout error or network error) -// - any server error response from a getMore command excluding those containing the following error codes -// - Interrupted: 11601 -// - CappedPositionLost: 136 -// - CursorKilled: 237 -// - a server error response with an error message containing the substring "not master" or "node is recovering" -// -// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. - -function isGetMoreError(error) { - if (error[mongoErrorContextSymbol]) { - return error[mongoErrorContextSymbol].isGetMore; - } -} - -function isResumableError(error) { - if (!isGetMoreError(error)) { - return false; - } - - return !!( - error instanceof MongoNetworkError || - !GET_MORE_NON_RESUMABLE_CODES.has(error.code) || - error.message.match(/not master/) || - error.message.match(/node is recovering/) - ); -} - -module.exports = { GET_MORE_NON_RESUMABLE_CODES, isResumableError }; diff --git a/node_modules/mongodb/lib/gridfs-stream/download.js b/node_modules/mongodb/lib/gridfs-stream/download.js deleted file mode 100644 index 9012602670a77ecdea1da2d4f9f2c641d3228171..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/gridfs-stream/download.js +++ /dev/null @@ -1,415 +0,0 @@ -'use strict'; - -var stream = require('stream'), - util = require('util'); - -module.exports = GridFSBucketReadStream; - -/** - * A readable stream that enables you to read buffers from GridFS. - * - * Do not instantiate this class directly. Use `openDownloadStream()` instead. - * - * @class - * @param {Collection} chunks Handle for chunks collection - * @param {Collection} files Handle for files collection - * @param {Object} readPreference The read preference to use - * @param {Object} filter The query to use to find the file document - * @param {Object} [options] Optional settings. - * @param {Number} [options.sort] Optional sort for the file find query - * @param {Number} [options.skip] Optional skip for the file find query - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @fires GridFSBucketReadStream#error - * @fires GridFSBucketReadStream#file - * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. - */ - -function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { - this.s = { - bytesRead: 0, - chunks: chunks, - cursor: null, - expected: 0, - files: files, - filter: filter, - init: false, - expectedEnd: 0, - file: null, - options: options, - readPreference: readPreference - }; - - stream.Readable.call(this); -} - -util.inherits(GridFSBucketReadStream, stream.Readable); - -/** - * An error occurred - * - * @event GridFSBucketReadStream#error - * @type {Error} - */ - -/** - * Fires when the stream loaded the file document corresponding to the - * provided id. - * - * @event GridFSBucketReadStream#file - * @type {object} - */ - -/** - * Emitted when a chunk of data is available to be consumed. - * - * @event GridFSBucketReadStream#data - * @type {object} - */ - -/** - * Fired when the stream is exhausted (no more data events). - * - * @event GridFSBucketReadStream#end - * @type {object} - */ - -/** - * Fired when the stream is exhausted and the underlying cursor is killed - * - * @event GridFSBucketReadStream#close - * @type {object} - */ - -/** - * Reads from the cursor and pushes to the stream. - * @method - */ - -GridFSBucketReadStream.prototype._read = function() { - var _this = this; - if (this.destroyed) { - return; - } - - waitForFile(_this, function() { - doRead(_this); - }); -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} start Offset in bytes to start reading at - * @return {GridFSBucketReadStream} - */ - -GridFSBucketReadStream.prototype.start = function(start) { - throwIfInitialized(this); - this.s.options.start = start; - return this; -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} end Offset in bytes to stop reading at - * @return {GridFSBucketReadStream} - */ - -GridFSBucketReadStream.prototype.end = function(end) { - throwIfInitialized(this); - this.s.options.end = end; - return this; -}; - -/** - * Marks this stream as aborted (will never push another `data` event) - * and kills the underlying cursor. Will emit the 'end' event, and then - * the 'close' event once the cursor is successfully killed. - * - * @method - * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. - * @fires GridFSBucketWriteStream#close - * @fires GridFSBucketWriteStream#end - */ - -GridFSBucketReadStream.prototype.abort = function(callback) { - var _this = this; - this.push(null); - this.destroyed = true; - if (this.s.cursor) { - this.s.cursor.close(function(error) { - _this.emit('close'); - callback && callback(error); - }); - } else { - if (!this.s.init) { - // If not initialized, fire close event because we will never - // get a cursor - _this.emit('close'); - } - callback && callback(); - } -}; - -/** - * @ignore - */ - -function throwIfInitialized(self) { - if (self.s.init) { - throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); - } -} - -/** - * @ignore - */ - -function doRead(_this) { - if (_this.destroyed) { - return; - } - - _this.s.cursor.next(function(error, doc) { - if (_this.destroyed) { - return; - } - if (error) { - return __handleError(_this, error); - } - if (!doc) { - _this.push(null); - return _this.s.cursor.close(function(error) { - if (error) { - return __handleError(_this, error); - } - _this.emit('close'); - }); - } - - var bytesRemaining = _this.s.file.length - _this.s.bytesRead; - var expectedN = _this.s.expected++; - var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); - - if (doc.n > expectedN) { - var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - if (doc.n < expectedN) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; - - if (buf.length !== expectedLength) { - if (bytesRemaining <= 0) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; - return __handleError(_this, new Error(errmsg)); - } - - errmsg = - 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; - return __handleError(_this, new Error(errmsg)); - } - - _this.s.bytesRead += buf.length; - - if (buf.length === 0) { - return _this.push(null); - } - - var sliceStart = null; - var sliceEnd = null; - - if (_this.s.bytesToSkip != null) { - sliceStart = _this.s.bytesToSkip; - _this.s.bytesToSkip = 0; - } - - if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) { - sliceEnd = _this.s.bytesToTrim; - } - - // If the remaining amount of data left is < chunkSize read the right amount of data - if (_this.s.options.end && _this.s.options.end - _this.s.bytesToSkip < buf.length) { - sliceEnd = _this.s.options.end - _this.s.bytesToSkip; - } - - if (sliceStart != null || sliceEnd != null) { - buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); - } - - _this.push(buf); - }); -} - -/** - * @ignore - */ - -function init(self) { - var findOneOptions = {}; - if (self.s.readPreference) { - findOneOptions.readPreference = self.s.readPreference; - } - if (self.s.options && self.s.options.sort) { - findOneOptions.sort = self.s.options.sort; - } - if (self.s.options && self.s.options.skip) { - findOneOptions.skip = self.s.options.skip; - } - - self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { - if (error) { - return __handleError(self, error); - } - if (!doc) { - var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; - var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; - var err = new Error(errmsg); - err.code = 'ENOENT'; - return __handleError(self, err); - } - - // If document is empty, kill the stream immediately and don't - // execute any reads - if (doc.length <= 0) { - self.push(null); - return; - } - - if (self.destroyed) { - // If user destroys the stream before we have a cursor, wait - // until the query is done to say we're 'closed' because we can't - // cancel a query. - self.emit('close'); - return; - } - - self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); - - var filter = { files_id: doc._id }; - - // Currently (MongoDB 3.4.4) skip function does not support the index, - // it needs to retrieve all the documents first and then skip them. (CS-25811) - // As work around we use $gte on the "n" field. - if (self.s.options && self.s.options.start != null) { - var skip = Math.floor(self.s.options.start / doc.chunkSize); - if (skip > 0) { - filter['n'] = { $gte: skip }; - } - } - self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); - - if (self.s.readPreference) { - self.s.cursor.setReadPreference(self.s.readPreference); - } - - self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); - self.s.file = doc; - self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); - self.emit('file', doc); - }); -} - -/** - * @ignore - */ - -function waitForFile(_this, callback) { - if (_this.s.file) { - return callback(); - } - - if (!_this.s.init) { - init(_this); - _this.s.init = true; - } - - _this.once('file', function() { - callback(); - }); -} - -/** - * @ignore - */ - -function handleStartOption(stream, doc, options) { - if (options && options.start != null) { - if (options.start > doc.length) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); - } - if (options.end != null && options.end < options.start) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'greater than stream end (' + - options.end + - ')' - ); - } - - stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; - stream.s.expected = Math.floor(options.start / doc.chunkSize); - - return options.start - stream.s.bytesRead; - } -} - -/** - * @ignore - */ - -function handleEndOption(stream, doc, cursor, options) { - if (options && options.end != null) { - if (options.end > doc.length) { - throw new Error( - 'Stream end (' + - options.end + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); - } - - var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; - - cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); - - stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); - - return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; - } -} - -/** - * @ignore - */ - -function __handleError(_this, error) { - _this.emit('error', error); -} diff --git a/node_modules/mongodb/lib/gridfs-stream/index.js b/node_modules/mongodb/lib/gridfs-stream/index.js deleted file mode 100644 index 9d64a847a091c11b50a74422c6851c4eb0b9310f..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/gridfs-stream/index.js +++ /dev/null @@ -1,358 +0,0 @@ -'use strict'; - -var Emitter = require('events').EventEmitter; -var GridFSBucketReadStream = require('./download'); -var GridFSBucketWriteStream = require('./upload'); -var shallowClone = require('../utils').shallowClone; -var toError = require('../utils').toError; -var util = require('util'); -var executeOperation = require('../utils').executeOperation; - -var DEFAULT_GRIDFS_BUCKET_OPTIONS = { - bucketName: 'fs', - chunkSizeBytes: 255 * 1024 -}; - -module.exports = GridFSBucket; - -/** - * Constructor for a streaming GridFS interface - * @class - * @param {Db} db A db handle - * @param {object} [options] Optional settings. - * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. - * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB - * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` - * @param {object} [options.readPreference] Optional read preference to be passed to read operations - * @fires GridFSBucketWriteStream#index - * @return {GridFSBucket} - */ - -function GridFSBucket(db, options) { - Emitter.apply(this); - this.setMaxListeners(0); - - if (options && typeof options === 'object') { - options = shallowClone(options); - var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); - for (var i = 0; i < keys.length; ++i) { - if (!options[keys[i]]) { - options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; - } - } - } else { - options = DEFAULT_GRIDFS_BUCKET_OPTIONS; - } - - this.s = { - db: db, - options: options, - _chunksCollection: db.collection(options.bucketName + '.chunks'), - _filesCollection: db.collection(options.bucketName + '.files'), - checkedIndexes: false, - calledOpenUploadStream: false, - promiseLibrary: db.s.promiseLibrary || Promise - }; -} - -util.inherits(GridFSBucket, Emitter); - -/** - * When the first call to openUploadStream is made, the upload stream will - * check to see if it needs to create the proper indexes on the chunks and - * files collections. This event is fired either when 1) it determines that - * no index creation is necessary, 2) when it successfully creates the - * necessary indexes. - * - * @event GridFSBucket#index - * @type {Error} - */ - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStream = function(filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string|number|object} id A custom id used to identify the file - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - - options.id = id; - - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming file - * data from GridFS. - * @method - * @param {ObjectId} id The id of the file doc - * @param {Object} [options] Optional settings. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStream = function(id, options) { - var filter = { _id: id }; - options = { - start: options && options.start, - end: options && options.end - }; - - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Deletes a file with the given id - * @method - * @param {ObjectId} id The id of the file doc - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.delete = function(id, callback) { - return executeOperation(this.s.db.s.topology, _delete, [this, id, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _delete(_this, id, callback) { - _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { - if (error) { - return callback(error); - } - - _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { - if (error) { - return callback(error); - } - - // Delete orphaned chunks before returning FileNotFound - if (!res.result.n) { - var errmsg = 'FileNotFound: no file with id ' + id + ' found'; - return callback(new Error(errmsg)); - } - - callback(); - }); - }); -} - -/** - * Convenience wrapper around find on the files collection - * @method - * @param {Object} filter - * @param {Object} [options] Optional settings for cursor - * @param {number} [options.batchSize] Optional batch size for cursor - * @param {number} [options.limit] Optional limit for cursor - * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor - * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag - * @param {number} [options.skip] Optional skip for cursor - * @param {object} [options.sort] Optional sort for cursor - * @return {Cursor} - */ - -GridFSBucket.prototype.find = function(filter, options) { - filter = filter || {}; - options = options || {}; - - var cursor = this.s._filesCollection.find(filter); - - if (options.batchSize != null) { - cursor.batchSize(options.batchSize); - } - if (options.limit != null) { - cursor.limit(options.limit); - } - if (options.maxTimeMS != null) { - cursor.maxTimeMS(options.maxTimeMS); - } - if (options.noCursorTimeout != null) { - cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); - } - if (options.skip != null) { - cursor.skip(options.skip); - } - if (options.sort != null) { - cursor.sort(options.sort); - } - - return cursor; -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming the - * file with the given name from GridFS. If there are multiple files with - * the same name, this will stream the most recent file with the given name - * (as determined by the `uploadDate` field). You can set the `revision` - * option to change this behavior. - * @method - * @param {String} filename The name of the file to stream - * @param {Object} [options] Optional settings - * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { - var sort = { uploadDate: -1 }; - var skip = null; - if (options && options.revision != null) { - if (options.revision >= 0) { - sort = { uploadDate: 1 }; - skip = options.revision; - } else { - skip = -options.revision - 1; - } - } - - var filter = { filename: filename }; - options = { - sort: sort, - skip: skip, - start: options && options.start, - end: options && options.end - }; - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Renames the file with the given _id to the given string - * @method - * @param {ObjectId} id the id of the file to rename - * @param {String} filename new name for the file - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.rename = function(id, filename, callback) { - return executeOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _rename(_this, id, filename, callback) { - var filter = { _id: id }; - var update = { $set: { filename: filename } }; - _this.s._filesCollection.updateOne(filter, update, function(error, res) { - if (error) { - return callback(error); - } - if (!res.result.n) { - return callback(toError('File with id ' + id + ' not found')); - } - callback(); - }); -} - -/** - * Removes this bucket's files collection, followed by its chunks collection. - * @method - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.drop = function(callback) { - return executeOperation(this.s.db.s.topology, _drop, [this, callback], { - skipSessions: true - }); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -GridFSBucket.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -/** - * @ignore - */ - -function _drop(_this, callback) { - _this.s._filesCollection.drop(function(error) { - if (error) { - return callback(error); - } - _this.s._chunksCollection.drop(function(error) { - if (error) { - return callback(error); - } - - return callback(); - }); - }); -} - -/** - * Callback format for all GridFSBucket methods that can accept a callback. - * @callback GridFSBucket~errorCallback - * @param {MongoError} error An error instance representing any errors that occurred - */ diff --git a/node_modules/mongodb/lib/gridfs-stream/upload.js b/node_modules/mongodb/lib/gridfs-stream/upload.js deleted file mode 100644 index adbba4116b1986d814363de770f81a43eb489f08..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/gridfs-stream/upload.js +++ /dev/null @@ -1,538 +0,0 @@ -'use strict'; - -var core = require('mongodb-core'); -var crypto = require('crypto'); -var stream = require('stream'); -var util = require('util'); -var Buffer = require('safe-buffer').Buffer; - -var ERROR_NAMESPACE_NOT_FOUND = 26; - -module.exports = GridFSBucketWriteStream; - -/** - * A writable stream that enables you to write buffers to GridFS. - * - * Do not instantiate this class directly. Use `openUploadStream()` instead. - * - * @class - * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {string|number|object} [options.id] Custom file id for the GridFS file. - * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes - * @param {number} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {number} [options.j] The journal write concern - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @fires GridFSBucketWriteStream#error - * @fires GridFSBucketWriteStream#finish - * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. - */ - -function GridFSBucketWriteStream(bucket, filename, options) { - options = options || {}; - this.bucket = bucket; - this.chunks = bucket.s._chunksCollection; - this.filename = filename; - this.files = bucket.s._filesCollection; - this.options = options; - // Signals the write is all done - this.done = false; - - this.id = options.id ? options.id : core.BSON.ObjectId(); - this.chunkSizeBytes = this.options.chunkSizeBytes; - this.bufToStore = Buffer.alloc(this.chunkSizeBytes); - this.length = 0; - this.md5 = !options.disableMD5 && crypto.createHash('md5'); - this.n = 0; - this.pos = 0; - this.state = { - streamEnd: false, - outstandingRequests: 0, - errored: false, - aborted: false, - promiseLibrary: this.bucket.s.promiseLibrary - }; - - if (!this.bucket.s.calledOpenUploadStream) { - this.bucket.s.calledOpenUploadStream = true; - - var _this = this; - checkIndexes(this, function() { - _this.bucket.s.checkedIndexes = true; - _this.bucket.emit('index'); - }); - } -} - -util.inherits(GridFSBucketWriteStream, stream.Writable); - -/** - * An error occurred - * - * @event GridFSBucketWriteStream#error - * @type {Error} - */ - -/** - * `end()` was called and the write stream successfully wrote the file - * metadata and all the chunks to MongoDB. - * - * @event GridFSBucketWriteStream#finish - * @type {object} - */ - -/** - * Write a buffer to the stream. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. - * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. - */ - -GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { - var _this = this; - return waitForIndexes(this, function() { - return doWrite(_this, chunk, encoding, callback); - }); -}; - -/** - * Places this write stream into an aborted state (all future writes fail) - * and deletes all chunks that have already been written. - * - * @method - * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred - * @return {Promise} if no callback specified - */ - -GridFSBucketWriteStream.prototype.abort = function(callback) { - if (this.state.streamEnd) { - var error = new Error('Cannot abort a stream that has already completed'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - if (this.state.aborted) { - error = new Error('Cannot call abort() on a stream twice'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - this.state.aborted = true; - this.chunks.deleteMany({ files_id: this.id }, function(error) { - if (typeof callback === 'function') callback(error); - }); -}; - -/** - * Tells the stream that no more data will be coming in. The stream will - * persist the remaining data to MongoDB, write the files document, and - * then emit a 'finish' event. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB - */ - -GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { - var _this = this; - if (typeof chunk === 'function') { - (callback = chunk), (chunk = null), (encoding = null); - } else if (typeof encoding === 'function') { - (callback = encoding), (encoding = null); - } - - if (checkAborted(this, callback)) { - return; - } - this.state.streamEnd = true; - - if (callback) { - this.once('finish', function(result) { - callback(null, result); - }); - } - - if (!chunk) { - waitForIndexes(this, function() { - writeRemnant(_this); - }); - return; - } - - this.write(chunk, encoding, function() { - writeRemnant(_this); - }); -}; - -/** - * @ignore - */ - -function __handleError(_this, error, callback) { - if (_this.state.errored) { - return; - } - _this.state.errored = true; - if (callback) { - return callback(error); - } - _this.emit('error', error); -} - -/** - * @ignore - */ - -function createChunkDoc(filesId, n, data) { - return { - _id: core.BSON.ObjectId(), - files_id: filesId, - n: n, - data: data - }; -} - -/** - * @ignore - */ - -function checkChunksIndex(_this, callback) { - _this.chunks.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { files_id: 1, n: 1 }; - _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - return; - } - return callback(error); - } - - var hasChunksIndex = false; - indexes.forEach(function(index) { - if (index.key) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { - hasChunksIndex = true; - } - } - }); - - if (hasChunksIndex) { - callback(); - } else { - index = { files_id: 1, n: 1 }; - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - indexOptions.unique = true; - - _this.chunks.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - } - }); -} - -/** - * @ignore - */ - -function checkDone(_this, callback) { - if (_this.done) return true; - if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { - // Set done so we dont' trigger duplicate createFilesDoc - _this.done = true; - // Create a new files doc - var filesDoc = createFilesDoc( - _this.id, - _this.length, - _this.chunkSizeBytes, - _this.md5 && _this.md5.digest('hex'), - _this.filename, - _this.options.contentType, - _this.options.aliases, - _this.options.metadata - ); - - if (checkAborted(_this, callback)) { - return false; - } - - _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error, callback); - } - _this.emit('finish', filesDoc); - }); - - return true; - } - - return false; -} - -/** - * @ignore - */ - -function checkIndexes(_this, callback) { - _this.files.findOne({}, { _id: 1 }, function(error, doc) { - if (error) { - return callback(error); - } - if (doc) { - return callback(); - } - - _this.files.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { filename: 1, uploadDate: 1 }; - _this.files.createIndex(index, { background: false }, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - return; - } - return callback(error); - } - - var hasFileIndex = false; - indexes.forEach(function(index) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { - hasFileIndex = true; - } - }); - - if (hasFileIndex) { - checkChunksIndex(_this, callback); - } else { - index = { filename: 1, uploadDate: 1 }; - - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - - _this.files.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - } - }); - }); -} - -/** - * @ignore - */ - -function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { - var ret = { - _id: _id, - length: length, - chunkSize: chunkSize, - uploadDate: new Date(), - filename: filename - }; - - if (md5) { - ret.md5 = md5; - } - - if (contentType) { - ret.contentType = contentType; - } - - if (aliases) { - ret.aliases = aliases; - } - - if (metadata) { - ret.metadata = metadata; - } - - return ret; -} - -/** - * @ignore - */ - -function doWrite(_this, chunk, encoding, callback) { - if (checkAborted(_this, callback)) { - return false; - } - - var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); - - _this.length += inputBuf.length; - - // Input is small enough to fit in our buffer - if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { - inputBuf.copy(_this.bufToStore, _this.pos); - _this.pos += inputBuf.length; - - callback && callback(); - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // True means client can keep writing. - return true; - } - - // Otherwise, buffer is too big for current chunk, so we need to flush - // to MongoDB. - var inputBufRemaining = inputBuf.length; - var spaceRemaining = _this.chunkSizeBytes - _this.pos; - var numToCopy = Math.min(spaceRemaining, inputBuf.length); - var outstandingRequests = 0; - while (inputBufRemaining > 0) { - var inputBufPos = inputBuf.length - inputBufRemaining; - inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); - _this.pos += numToCopy; - spaceRemaining -= numToCopy; - if (spaceRemaining === 0) { - if (_this.md5) { - _this.md5.update(_this.bufToStore); - } - var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); - ++_this.state.outstandingRequests; - ++outstandingRequests; - - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - --outstandingRequests; - - if (!outstandingRequests) { - _this.emit('drain', doc); - callback && callback(); - checkDone(_this); - } - }); - - spaceRemaining = _this.chunkSizeBytes; - _this.pos = 0; - ++_this.n; - } - inputBufRemaining -= numToCopy; - numToCopy = Math.min(spaceRemaining, inputBufRemaining); - } - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // False means the client should wait for the 'drain' event. - return false; -} - -/** - * @ignore - */ - -function getWriteOptions(_this) { - var obj = {}; - if (_this.options.writeConcern) { - obj.w = _this.options.writeConcern.w; - obj.wtimeout = _this.options.writeConcern.wtimeout; - obj.j = _this.options.writeConcern.j; - } - return obj; -} - -/** - * @ignore - */ - -function waitForIndexes(_this, callback) { - if (_this.bucket.s.checkedIndexes) { - return callback(false); - } - - _this.bucket.once('index', function() { - callback(true); - }); - - return true; -} - -/** - * @ignore - */ - -function writeRemnant(_this, callback) { - // Buffer is empty, so don't bother to insert - if (_this.pos === 0) { - return checkDone(_this, callback); - } - - ++_this.state.outstandingRequests; - - // Create a new buffer to make sure the buffer isn't bigger than it needs - // to be. - var remnant = Buffer.alloc(_this.pos); - _this.bufToStore.copy(remnant, 0, 0, _this.pos); - if (_this.md5) { - _this.md5.update(remnant); - } - var doc = createChunkDoc(_this.id, _this.n, remnant); - - // If the stream was aborted, do not write remnant - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - checkDone(_this); - }); -} - -/** - * @ignore - */ - -function checkAborted(_this, callback) { - if (_this.state.aborted) { - if (typeof callback === 'function') { - callback(new Error('this stream has been aborted')); - } - return true; - } - return false; -} diff --git a/node_modules/mongodb/lib/gridfs/chunk.js b/node_modules/mongodb/lib/gridfs/chunk.js deleted file mode 100644 index c29bba02a7e1d44de205acad4e278e97e9117369..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/gridfs/chunk.js +++ /dev/null @@ -1,236 +0,0 @@ -'use strict'; - -var Binary = require('mongodb-core').BSON.Binary, - ObjectID = require('mongodb-core').BSON.ObjectID; - -var Buffer = require('safe-buffer').Buffer; - -/** - * 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 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 (typeof mongoObjectFinal.data === 'string') { - var buffer = Buffer.alloc(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); - this.data = new Binary(buffer); - } else if (Array.isArray(mongoObjectFinal.data)) { - buffer = Buffer.alloc(mongoObjectFinal.data.length); - var data = mongoObjectFinal.data.join(''); - buffer.write(data, 0, data.length, 'binary'); - this.data = new Binary(buffer); - } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { - this.data = mongoObjectFinal.data; - } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { - 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, data.length, 'binary'); - 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 = Buffer.alloc(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 = { upsert: true }; - for (var name in options) writeOptions[name] = options[name]; - for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; - - 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.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { - 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: - * - * <pre><code> - * { - * '_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 - * } - * </code></pre> - * - * @see <a href="http://www.mongodb.org/display/DOCS/GridFS+Specification#GridFSSpecification-{{chunks}}">MongoDB GridFS Chunk Object Structure</a> - */ -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; diff --git a/node_modules/mongodb/lib/gridfs/grid_store.js b/node_modules/mongodb/lib/gridfs/grid_store.js deleted file mode 100644 index 4b5eb5e4b85458b478e466ccde73f6d7465f9790..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/gridfs/grid_store.js +++ /dev/null @@ -1,1907 +0,0 @@ -'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 <a href="http://www.mongodb.org/display/DOCS/GridFS">here</a>. - * - * @example - * const MongoClient = require('mongodb').MongoClient; - * const GridStore = require('mongodb').GridStore; - * const ObjectID = require('mongodb').ObjectID; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * const db = client.db(dbName); - * const 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); - * client.close(); - * test.done(); - * }); - * }); - * }); - * }); - * }); - */ -const Chunk = require('./chunk'); -const ObjectID = require('mongodb-core').BSON.ObjectID; -const ReadPreference = require('mongodb-core').ReadPreference; -const Buffer = require('safe-buffer').Buffer; -const fs = require('fs'); -const f = require('util').format; -const util = require('util'); -const MongoError = require('mongodb-core').MongoError; -const inherits = util.inherits; -const Duplex = require('stream').Duplex; -const shallowClone = require('../utils').shallowClone; -const executeOperation = require('../utils').executeOperation; -const deprecate = require('util').deprecate; - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -const deprecationFn = deprecate(() => {}, -'GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead'); - -/** - * 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] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] 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] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {string} [options.content_type] 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] Arbitrary data the user wants to store. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {(ReadPreference|string)} [options.readPreference] 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. - * @deprecated Use GridFSBucket API instead - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - deprecationFn(); - if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - 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 && id._bsontype === '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 || db.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']; - - // Get the promiseLibrary - var promiseLibrary = this.options.promiseLibrary || Promise; - - // Set the promiseLibrary - this.promiseLibrary = promiseLibrary; - - 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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~openCallback} [callback] this will be called after executing this method - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.open = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') { - throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true }); - } - - return executeOperation(this.db.s.topology, open, [this, options, callback], { - skipSessions: true - }); -}; - -var open = function(self, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(self.db, self.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() { - // Get chunk collection - var chunkCollection = self.chunkCollection(); - // Make an unique index for compatibility with mongo-cxx-driver:legacy - var chunkIndexOptions = shallowClone(writeConcern); - chunkIndexOptions.unique = true; - // Ensure index on chunk collection - chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function() { - // 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. - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.eof = function() { - return this.position === this.length ? true : false; -}; - -/** - * The callback result format. - * @callback GridStore~resultCallback - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @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 {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.getc = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.db.s.topology, getc, [this, options, callback], { - skipSessions: true - }); -}; - -var getc = function(self, options, callback) { - 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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @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 {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.puts = function(string, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - var finalString = string.match(/\n$/) == null ? string + '\n' : string; - return executeOperation( - this.db.s.topology, - this.write.bind(this), - [finalString, options, callback], - { skipSessions: true } - ); -}; - -/** - * Return a modified Readable stream including a possible transform method. - * - * @method - * @return {GridStoreStream} - * @deprecated Use GridFSBucket API instead - */ -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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @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 {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.write = function write(data, close, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.db.s.topology, - _writeNormal, - [this, data, close, options, callback], - { skipSessions: true } - ); -}; - -/** - * Handles the destroy part of a stream - * - * @method - * @result {null} - * @deprecated Use GridFSBucket API instead - */ -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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @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 {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.writeFile = function(file, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.db.s.topology, writeFile, [this, file, options, callback], { - skipSessions: true - }); -}; - -var writeFile = function(self, file, options, callback) { - 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; - - // Write a chunk - var writeChunk = function() { - // Allocate the buffer - var _buffer = Buffer.alloc(self.chunkSize); - // Read the file - fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { - 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.slice(0, bytesRead), function(err, chunk) { - if (err) return callback(err, self); - - chunk.save({}, function(err) { - if (err) return callback(err, self); - - self.position = self.position + bytesRead; - - // Point to current chunk - self.currentChunk = chunk; - - if (offset >= stats.size) { - fs.close(file, function(err) { - if (err) return callback(err); - - self.close(function(err) { - 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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @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 {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.close = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.db.s.topology, close, [this, options, callback], { - skipSessions: true - }); -}; - -var close = function(self, options, callback) { - if (self.mode[0] === 'w') { - // Set up options - options = Object.assign({}, self.writeConcern, options); - - if (self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save({}, function(err) { - 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) { - 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(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true })); - } -}; - -/** - * 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} - * @deprecated Use GridFSBucket API instead - */ -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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.unlink = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.db.s.topology, unlink, [this, options, callback], { - skipSessions: true - }); -}; - -var unlink = function(self, options, callback) { - deleteChunks(self, 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} - * @deprecated Use GridFSBucket API instead - */ -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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.readlines = function(separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - separator = args.length ? args.shift() : '\n'; - separator = separator || '\n'; - options = args.length ? args.shift() : {}; - - return executeOperation(this.db.s.topology, readlines, [this, separator, options, callback], { - skipSessions: true - }); -}; - -var readlines = function(self, separator, options, callback) { - self.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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @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 {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.rewind = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation(this.db.s.topology, rewind, [this, options, callback], { - skipSessions: true - }); -}; - -var rewind = function(self, options, callback) { - if (self.currentChunk.chunkNumber !== 0) { - if (self.mode[0] === 'w') { - deleteChunks(self, function(err) { - 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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.read = function(length, buffer, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - return executeOperation(this.db.s.topology, read, [this, length, buffer, options, callback], { - skipSessions: true - }); -}; - -var read = function(self, length, buffer, options, callback) { - // 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 ? Buffer.alloc(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(MongoError.create({ message: 'File does not exist', driver: true }), null); - // Else return data - return callback(null, finalBuffer); - } - - // Read the next chunk - 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( - MongoError.create({ - message: 'no chunks found for file, possibly corrupt', - driver: true - }), - 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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~tellCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.tell = function(callback) { - var self = this; - // We provided a callback leg - if (typeof callback === 'function') return callback(null, this.position); - // Return promise - return new self.promiseLibrary(function(resolve) { - resolve(self.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 {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~gridStoreCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.seek = function(position, seekLocation, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - seekLocation = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - return executeOperation( - this.db.s.topology, - seek, - [this, position, seekLocation, options, callback], - { skipSessions: true } - ); -}; - -var seek = function(self, position, seekLocation, options, callback) { - // Seek only supports read mode - if (self.mode !== 'r') { - return callback( - MongoError.create({ message: 'seek is only supported for mode r', driver: true }) - ); - } - - 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) { - if (err) return callback(err, null); - if (chunk == null) return callback(new Error('no chunk found')); - - // Set the current 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._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId; - return error( - MongoError.create({ - message: f( - 'file with id %s not opened for writing', - self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename - ), - driver: true - }), - 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' && doc) { - // Delete any existing chunks - deleteChunks(self, options, function(err) { - 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') { - 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; - - // No file exists set up write mode - if (self.mode === 'w') { - // Delete any existing chunks - deleteChunks(self, options, function(err) { - 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( - MongoError.create({ - message: f( - 'file with id %s not opened for writing', - self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename - ), - driver: true - }), - 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); - 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) { - 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) { - 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) { - callback(err, self); - }); - } - // Return normally - return callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - * <pre><code> - * { - * '_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} - * } - * </code></pre> - * - * @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) { - 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeOperation( - db.s.topology, - exists, - [db, fileIdObject, rootCollection, options, callback], - { skipSessions: true } - ); -}; - -var exists = function(db, fileIdObject, rootCollection, options, callback) { - // 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeOperation(db.s.topology, list, [db, rootCollection, options, callback], { - skipSessions: true - }); -}; - -var list = function(db, rootCollection, options, callback) { - // 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeOperation( - db.s.topology, - readStatic, - [db, name, length, offset, options, callback], - { skipSessions: true } - ); -}; - -var readStatic = function(db, name, length, offset, options, callback) { - 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] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeOperation( - db.s.topology, - readlinesStatic, - [db, name, separator, options, callback], - { skipSessions: true } - ); -}; - -var readlinesStatic = function(db, name, separator, options, callback) { - 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] Optional settings. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.unlink = function(db, names, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { - skipSessions: true - }); -}; - -var unlinkStatic = function(self, db, names, options, callback) { - // 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() { - 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) { - if (err) return callback(err); - gridStore.collection(function(err, collection) { - if (err) return callback(err); - collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { - callback(err, self); - }); - }); - }); - }); - } -}; - -/** - * @ignore - */ -var _writeNormal = function(self, data, close, options, 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, Buffer.from(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 MongoError.create({ - message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', - driver: 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. - * @deprecated Use GridFSBucket API instead - */ -var GridStoreStream = function(gs) { - // 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]); - } - - return destination; -}; - -// Called by stream -GridStoreStream.prototype._read = function() { - 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) { - 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) { - var self = this; - if (self.endCalled) - return self.emit( - 'error', - MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) - ); - // 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 = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - 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/mongodb/lib/mongo_client.js b/node_modules/mongodb/lib/mongo_client.js deleted file mode 100644 index e6e938133167dc350c24bc4c757038fcc47be5da..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/mongo_client.js +++ /dev/null @@ -1,472 +0,0 @@ -'use strict'; - -const ChangeStream = require('./change_stream'); -const Db = require('./db'); -const EventEmitter = require('events').EventEmitter; -const executeOperation = require('./utils').executeOperation; -const handleCallback = require('./utils').handleCallback; -const inherits = require('util').inherits; -const MongoError = require('mongodb-core').MongoError; - -// Operations -const connectOp = require('./operations/mongo_client_ops').connectOp; -const logout = require('./operations/mongo_client_ops').logout; -const validOptions = require('./operations/mongo_client_ops').validOptions; - -/** - * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. - * - * @example - * // Connect using a MongoClient instance - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * const mongoClient = new MongoClient(url); - * mongoClient.connect(function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - * - * @example - * // Connect using the MongoClient.connect static method - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - */ - -/** - * Creates a new MongoClient instance - * @class - * @param {string} url The connection URI string - * @param {object} [options] Optional settings - * @param {number} [options.poolSize=5] The maximum size of the individual server pool - * @param {boolean} [options.ssl=false] Enable SSL connection. - * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority - * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer - * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer - * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase - * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting - * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). - * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @param {number} [options.socketTimeoutMS=360000] 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 - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j=false] Specify a journal write concern - * @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.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers - * @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 {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers - * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 - * @param {object} [options.compression] Type of compression to use: snappy or zlib - * @param {boolean} [options.fsync=false] Specify a file sync write concern - * @param {array} [options.readPreferenceTags] Read preference tags - * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor - * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client - * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @param {boolean} [options.useNewUrlParser=false] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {MongoClient} a MongoClient instance - */ -function MongoClient(url, options) { - if (!(this instanceof MongoClient)) return new MongoClient(url, options); - // Set up event emitter - EventEmitter.call(this); - - // The internal state - this.s = { - url: url, - options: options || {}, - promiseLibrary: null, - dbCache: {}, - sessions: [] - }; - - // Get the promiseLibrary - const promiseLibrary = this.s.options.promiseLibrary || Promise; - - // Add the promise to the internal state - this.s.promiseLibrary = promiseLibrary; -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -/** - * The callback format for results - * @callback MongoClient~connectCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {MongoClient} client The connected client. - */ - -/** - * 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 {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise<MongoClient>} returns Promise if no callback passed - */ -MongoClient.prototype.connect = function(callback) { - // Validate options object - const err = validOptions(this.s.options); - - if (typeof callback === 'string') { - throw new TypeError('`connect` only accepts a callback'); - } - - return executeOperation(this, connectOp, [this, err, callback], { - skipSessions: true - }); -}; - -/** - * Logout user from server, fire off on all connections and remove all auth info - * @method - * @param {object} [options] Optional settings. - * @param {string} [options.dbName] Logout against different database than current. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.logout = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Establish the correct database name - const dbName = this.s.options.authSource ? this.s.options.authSource : this.s.options.dbName; - - return executeOperation(this, logout, [this, dbName, callback], { - skipSessions: true - }); -}; - -/** - * Close the db and its underlying connections - * @method - * @param {boolean} force Force close, emitting no events - * @param {Db~noResultCallback} [callback] The result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.close = function(force, callback) { - if (typeof force === 'function') (callback = force), (force = false); - - // Close the topology connection - if (this.topology) { - this.topology.close(force); - } - // Emit close event - this.emit('close', this); - - // Fire close event on any cached db instances - for (const name in this.s.dbCache) { - this.s.dbCache[name].emit('close'); - } - - // Remove listeners after emit - this.removeAllListeners('close'); - - // Callback after next event loop tick - if (typeof callback === 'function') - return process.nextTick(() => { - handleCallback(callback, null); - }); - - // Return dummy promise - return new this.s.promiseLibrary(resolve => { - resolve(); - }); -}; - -/** - * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are - * related in a parent-child relationship to the original instance so that events are correctly emitted on child - * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. - * You can control these behaviors with the options noListener and returnNonCachedInstance. - * - * @method - * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {Db} - */ -MongoClient.prototype.db = function(dbName, options) { - options = options || {}; - - // Default to db from connection string if not provided - if (!dbName) { - dbName = this.s.options.dbName; - } - - // Copy the options and add out internal override of the not shared flag - const finalOptions = Object.assign({}, this.s.options, options); - - // Do we have the db in the cache already - if (this.s.dbCache[dbName] && finalOptions.returnNonCachedInstance !== true) { - return this.s.dbCache[dbName]; - } - - // Add promiseLibrary - finalOptions.promiseLibrary = this.s.promiseLibrary; - - // If no topology throw an error message - if (!this.topology) { - throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); - } - - // Return the db object - const db = new Db(dbName, this.topology, finalOptions); - - // Add the db to the cache - this.s.dbCache[dbName] = db; - // Return the database - return db; -}; - -/** - * Check if MongoClient is connected - * - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {boolean} - */ -MongoClient.prototype.isConnected = function(options) { - options = options || {}; - - if (!this.topology) return false; - return this.topology.isConnected(options); -}; - -/** - * 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] Optional settings - * @param {number} [options.poolSize=5] The maximum size of the individual server pool - * @param {boolean} [options.ssl=false] Enable SSL connection. - * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority - * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer - * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer - * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase - * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {boolean} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting - * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). - * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @param {number} [options.socketTimeoutMS=360000] 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 - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j=false] Specify a journal write concern - * @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.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers - * @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 {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers - * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 - * @param {object} [options.compression] Type of compression to use: snappy or zlib - * @param {boolean} [options.fsync=false] Specify a file sync write concern - * @param {array} [options.readPreferenceTags] Read preference tags - * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor - * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances - * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise<MongoClient>} returns Promise if no callback passed - */ -MongoClient.connect = function(url, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : null; - options = options || {}; - - // Create client - const mongoClient = new MongoClient(url, options); - // Execute the connect method - return mongoClient.connect(callback); -}; - -/** - * Starts a new session on the server - * - * @param {SessionOptions} [options] optional settings for a driver session - * @return {ClientSession} the newly established session - */ -MongoClient.prototype.startSession = function(options) { - options = Object.assign({ explicit: true }, options); - if (!this.topology) { - throw new MongoError('Must connect to a server before calling this method'); - } - - if (!this.topology.hasSessionSupport()) { - throw new MongoError('Current topology does not support sessions'); - } - - return this.topology.startSession(options, this.s.options); -}; - -/** - * Runs a given operation with an implicitly created session. The lifetime of the session - * will be handled without the need for user interaction. - * - * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) - * - * @param {Object} [options] Optional settings to be appled to implicitly created session - * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` - * @return {Promise} - */ -MongoClient.prototype.withSession = function(options, operation) { - if (typeof options === 'function') (operation = options), (options = undefined); - const session = this.startSession(options); - - let cleanupHandler = (err, result, opts) => { - // prevent multiple calls to cleanupHandler - cleanupHandler = () => { - throw new ReferenceError('cleanupHandler was called too many times'); - }; - - opts = Object.assign({ throw: true }, opts); - session.endSession(); - - if (err) { - if (opts.throw) throw err; - return Promise.reject(err); - } - }; - - try { - const result = operation(session); - return Promise.resolve(result) - .then(result => cleanupHandler(null, result)) - .catch(err => cleanupHandler(err, null, { throw: true })); - } catch (err) { - return cleanupHandler(err, null, { throw: false }); - } -}; -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, - * and config databases. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -MongoClient.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the mongo client logger - * @method - * @return {Logger} return the mongo client logger - * @ignore - */ -MongoClient.prototype.getLogger = function() { - return this.s.options.logger; -}; - -module.exports = MongoClient; diff --git a/node_modules/mongodb/lib/operations/admin_ops.js b/node_modules/mongodb/lib/operations/admin_ops.js deleted file mode 100644 index b08071c3fc990dee10c3bba1227920e2eb39ff81..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/operations/admin_ops.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -const executeCommand = require('./db_ops').executeCommand; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; - -/** - * Get ReplicaSet status - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function replSetGetStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); -} - -/** - * Retrieve this db's server status. - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback - */ -function serverStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); -} - -/** - * Validate an existing collection - * - * @param {Admin} a collection instance. - * @param {string} collectionName The name of the collection to validate. - * @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function validateCollection(admin, collectionName, options, callback) { - const command = { validate: collectionName }; - const keys = Object.keys(options); - - // Decorate command with extra options - for (let i = 0; i < keys.length; i++) { - if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - executeCommand(admin.s.db, command, options, (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); - }); -} - -module.exports = { replSetGetStatus, serverStatus, validateCollection }; diff --git a/node_modules/mongodb/lib/operations/collection_ops.js b/node_modules/mongodb/lib/operations/collection_ops.js deleted file mode 100644 index 1314723522acafa60aa25e3e3dd921ac488490df..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/operations/collection_ops.js +++ /dev/null @@ -1,1494 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const checkCollectionName = require('../utils').checkCollectionName; -const Code = require('mongodb-core').BSON.Code; -const createIndexDb = require('./db_ops').createIndex; -const decorateCommand = require('../utils').decorateCommand; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const ensureIndexDb = require('./db_ops').ensureIndex; -const evaluate = require('./db_ops').evaluate; -const executeCommand = require('./db_ops').executeCommand; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const resolveReadPreference = require('../utils').resolveReadPreference; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; -const isObject = require('../utils').isObject; -const Long = require('mongodb-core').BSON.Long; -const MongoError = require('mongodb-core').MongoError; -const ReadPreference = require('mongodb-core').ReadPreference; -const toError = require('../utils').toError; - -let collection; -function loadCollection() { - if (!collection) { - collection = require('../collection'); - } - return collection; -} -let db; -function loadDb() { - if (!db) { - db = require('../db'); - } - return db; -} - -/** - * 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(); -const groupFunction = - 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; - -/** - * Perform a bulkWrite operation. See Collection.prototype.bulkWrite for more information. - * - * @method - * @param {Collection} a Collection instance. - * @param {object[]} operations Bulk operations to perform. - * @param {object} [options] Optional settings. See Collection.prototype.bulkWrite for a list of options. - * @param {Collection~bulkWriteOpCallback} [callback] The command result callback - */ -function bulkWrite(coll, operations, options, callback) { - // Add ignoreUndfined - if (coll.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = coll.s.options.ignoreUndefined; - } - - // Create the bulk operation - const bulk = - options.ordered === true || options.ordered == null - ? coll.initializeOrderedBulkOp(options) - : coll.initializeUnorderedBulkOp(options); - - // Do we have a collation - let collation = false; - - // for each op go through and add to the bulk - try { - for (let i = 0; i < operations.length; i++) { - // Get the operation type - const key = Object.keys(operations[i])[0]; - // Check if we have a collation - if (operations[i][key].collation) { - collation = true; - } - - // Pass to the raw bulk - bulk.raw(operations[i]); - } - } catch (err) { - return callback(err, null); - } - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; - const capabilities = coll.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - // Execute the bulk - bulk.execute(writeCon, finalOptions, (err, r) => { - // We have connection level error - if (!r && err) { - return callback(err, null); - } - - 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 = {}; - - // Update the n - r.n = r.insertedCount; - - // Inserted documents - const inserted = r.getInsertedIds(); - // Map inserted ids - for (let i = 0; i < inserted.length; i++) { - r.insertedIds[inserted[i].index] = inserted[i]._id; - } - - // Upserted documents - const upserted = r.getUpsertedIds(); - // Map upserted ids - for (let i = 0; i < upserted.length; i++) { - r.upsertedIds[upserted[i].index] = upserted[i]._id; - } - - // Return the results - callback(null, r); - }); -} - -// Check the update operation to ensure it has atomic operators. -function checkForAtomicOperators(update) { - const keys = Object.keys(update); - - // same errors as the server would give for update doc lacking atomic operators - if (keys.length === 0) { - return toError('The update operation document must contain at least one atomic operator.'); - } - - if (keys[0][0] !== '$') { - return toError('the update operation document must contain atomic operators.'); - } -} - -/** - * Count the number of documents in the collection that match the query. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} query The query for the count. - * @param {object} [options] Optional settings. See Collection.prototype.count for a list of options. - * @param {Collection~countCallback} [callback] The command result callback - */ -function count(coll, query, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - options.collectionName = coll.s.name; - - options.readPreference = resolveReadPreference(options, { - db: coll.s.db, - collection: coll - }); - - let cmd; - try { - cmd = buildCountCommand(coll, query, options); - } catch (err) { - return callback(err); - } - - executeCommand(coll.s.db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.n); - }); -} - -function countDocuments(coll, query, options, callback) { - const skip = options.skip; - const limit = options.limit; - options = Object.assign({}, options); - - const pipeline = [{ $match: query }]; - - // Add skip and limit if defined - if (typeof skip === 'number') { - pipeline.push({ $skip: skip }); - } - - if (typeof limit === 'number') { - pipeline.push({ $limit: limit }); - } - - pipeline.push({ $group: { _id: null, n: { $sum: 1 } } }); - - delete options.limit; - delete options.skip; - - coll.aggregate(pipeline, options).toArray((err, docs) => { - if (err) return handleCallback(callback, err); - handleCallback(callback, null, docs.length ? docs[0].n : 0); - }); -} - -/** - * Build the count command. - * - * @method - * @param {collectionOrCursor} an instance of a collection or cursor - * @param {object} query The query for the count. - * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. - */ -function buildCountCommand(collectionOrCursor, query, options) { - const skip = options.skip; - const limit = options.limit; - let hint = options.hint; - const maxTimeMS = options.maxTimeMS; - query = query || {}; - - // Final query - const cmd = { - count: options.collectionName, - query: query - }; - - // check if collectionOrCursor is a cursor by using cursor.s.numberOfRetries - if (collectionOrCursor.s.numberOfRetries) { - if (collectionOrCursor.s.options.hint) { - hint = collectionOrCursor.s.options.hint; - } else if (collectionOrCursor.s.cmd.hint) { - hint = collectionOrCursor.s.cmd.hint; - } - decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.s.cmd); - } else { - decorateWithCollation(cmd, collectionOrCursor, options); - } - - // Add limit, skip and maxTimeMS if defined - if (typeof skip === 'number') cmd.skip = skip; - if (typeof limit === 'number') cmd.limit = limit; - if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; - if (hint) cmd.hint = hint; - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, collectionOrCursor); - - return cmd; -} - -/** - * Create an index on the db and collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndex(coll, fieldOrSpec, options, callback) { - createIndexDb(coll.s.db, coll.s.name, fieldOrSpec, options, callback); -} - -/** - * Create 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 {Collection} a Collection instance. - * @param {array} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndexes(coll, indexSpecs, options, callback) { - const capabilities = coll.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexSpecs.length; i++) { - if (indexSpecs[i].name == null) { - const keys = []; - - // Did the user pass in a collation, check if our write server supports it - if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Execute the index - executeCommand( - coll.s.db, - { - createIndexes: coll.s.name, - indexes: indexSpecs - }, - options, - callback - ); -} - -function deleteCallback(err, r, callback) { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.deletedCount = r.result.n; - if (callback) callback(null, r); -} - -/** - * Delete multiple documents from the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} filter The Filter used to select the documents to remove - * @param {object} [options] Optional settings. See Collection.prototype.deleteMany for a list of options. - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - */ -function deleteMany(coll, filter, options, callback) { - options.single = false; - - removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); -} - -/** - * Delete a single document from the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. See Collection.prototype.deleteOne for a list of options. - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - */ -function deleteOne(coll, filter, options, callback) { - options.single = true; - removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); -} - -/** - * Return a list of distinct values for the given key across a collection. - * - * @method - * @param {Collection} a Collection instance. - * @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] Optional settings. See Collection.prototype.distinct for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function distinct(coll, key, query, options, callback) { - // maxTimeMS option - const maxTimeMS = options.maxTimeMS; - - // Distinct command - const cmd = { - distinct: coll.s.name, - key: key, - query: query - }; - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); - - // Add maxTimeMS if defined - if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, coll, options); - - // Have we specified collation - try { - decorateWithCollation(cmd, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.values); - }); -} - -/** - * Drop an index from this collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {string} indexName Name of the index to drop. - * @param {object} [options] Optional settings. See Collection.prototype.dropIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function dropIndex(coll, indexName, options, callback) { - // Delete index command - const cmd = { dropIndexes: coll.s.name, index: indexName }; - - // Decorate command with writeConcern if supported - applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); - - // Execute command - executeCommand(coll.s.db, cmd, options, (err, result) => { - if (typeof callback !== 'function') return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); -} - -/** - * Drop all indexes from this collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {Object} [options] Optional settings. See Collection.prototype.dropIndexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function dropIndexes(coll, options, callback) { - dropIndex(coll, '*', options, err => { - if (err) return handleCallback(callback, err, false); - handleCallback(callback, null, true); - }); -} - -/** - * Ensure that an index exists. If the index does not exist, this function creates it. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function ensureIndex(coll, fieldOrSpec, options, callback) { - ensureIndexDb(coll.s.db, coll.s.name, fieldOrSpec, options, callback); -} - -/** - * Find and update a document. - * - * @method - * @param {Collection} a Collection instance. - * @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] Optional settings. See Collection.prototype.findAndModify for a list of options. - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -function findAndModify(coll, query, sort, doc, options, callback) { - // Create findAndModify command object - const queryObject = { - findAndModify: coll.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; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - delete options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (finalOptions.writeConcern) { - queryObject.writeConcern = finalOptions.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (finalOptions.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; - } - - finalOptions.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, finalOptions); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); -} - -/** - * Find and remove a document. - * - * @method - * @param {Collection} a Collection instance. - * @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] Optional settings. See Collection.prototype.findAndRemove for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - * @deprecated use findOneAndDelete instead - */ -function findAndRemove(coll, query, sort, options, callback) { - // Add the remove option - options.remove = true; - // Execute the callback - findAndModify(coll, query, sort, null, options, callback); -} - -/** - * Fetch the first document that matches the query. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} query Query for find Operation - * @param {object} [options] Optional settings. See Collection.prototype.findOne for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function findOne(coll, query, options, callback) { - const cursor = coll - .find(query, options) - .limit(-1) - .batchSize(1); - - // Return the item - cursor.next((err, item) => { - if (err != null) return handleCallback(callback, toError(err), null); - handleCallback(callback, null, item); - }); -} - -/** - * Find a document and delete it in one atomic operation. This requires a write lock for the duration of the operation. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} filter Document selection filter. - * @param {object} [options] Optional settings. See Collection.prototype.findOneAndDelete for a list of options. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - */ -function findOneAndDelete(coll, filter, options, callback) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.remove = true; - // Execute find and Modify - findAndModify(coll, filter, options.sort, null, finalOptions, callback); -} - -/** - * Find a document and replace it in one atomic operation. This requires a write lock for the duration of the operation. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} filter Document selection filter. - * @param {object} replacement Document replacing the matching document. - * @param {object} [options] Optional settings. See Collection.prototype.findOneAndReplace for a list of options. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - */ -function findOneAndReplace(coll, filter, replacement, options, callback) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; - finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; - - // Execute findAndModify - findAndModify(coll, filter, options.sort, replacement, finalOptions, callback); -} - -/** - * Find a document and update it in one atomic operation. This requires a write lock for the duration of the operation. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} filter Document selection filter. - * @param {object} update Update operations to be performed on the document - * @param {object} [options] Optional settings. See Collection.prototype.findOneAndUpdate for a list of options. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - */ -function findOneAndUpdate(coll, filter, update, options, callback) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; - finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false; - - // Execute findAndModify - findAndModify(coll, filter, options.sort, update, finalOptions, callback); -} - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @method - * @param {Collection} a Collection instance. - * @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] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function geoHaystackSearch(coll, x, y, options, callback) { - // Build command object - let commandObject = { - geoSearch: coll.s.name, - near: [x, y] - }; - - // Remove read preference from hash if it exists - commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, res) => { - if (err) return handleCallback(callback, err); - if (res.err || res.errmsg) 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); - }); -} - -/** - * Run a group command across a collection. - * - * @method - * @param {Collection} a Collection instance. - * @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] Optional settings. See Collection.prototype.group for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. - */ -function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { - // Execute using the command - if (command) { - const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); - - const selector = { - group: { - ns: coll.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 && keys._bsontype === 'Code')) { - selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); - } else { - const hash = {}; - keys.forEach(key => { - hash[key] = 1; - }); - selector.group.key = hash; - } - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); - - // Do we have a readConcern specified - decorateWithReadConcern(selector, coll, options); - - // Have we specified collation - try { - decorateWithCollation(selector, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, selector, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.retval); - }); - } else { - // Create execution scope - const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; - - scope.ns = coll.s.name; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, results.result || results); - }); - } -} - -/** - * Retrieve all the indexes on the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexes(coll, options, callback) { - options = Object.assign({}, { full: true }, options); - indexInformationDb(coll.s.db, coll.s.name, options, callback); -} - -/** - * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexExists(coll, indexes, options, callback) { - indexInformation(coll, options, (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 (let 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); - }); -} - -/** - * Retrieve this collection's index info. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexInformation(coll, options, callback) { - indexInformationDb(coll.s.db, coll.s.name, options, callback); -} - -function insertDocuments(coll, 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]; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If keep going set unordered - if (finalOptions.keepGoing === true) finalOptions.ordered = false; - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // File inserts - coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (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); - }); -} - -/** - * Insert a single document into the collection. See Collection.prototype.insertOne for more information. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} doc Document to insert. - * @param {object} [options] Optional settings. See Collection.prototype.insertOne for a list of options. - * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback - */ -function insertOne(coll, doc, options, callback) { - if (Array.isArray(doc)) { - return callback( - MongoError.create({ message: 'doc parameter must be an object', driver: true }) - ); - } - - insertDocuments(coll, [doc], options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - // Workaround for pre 2.6 servers - if (r == null) return callback(null, { result: { ok: 1 } }); - // Add values to top level to ensure crud spec compatibility - r.insertedCount = r.result.n; - r.insertedId = doc._id; - if (callback) callback(null, r); - }); -} - -/** - * Determine whether the collection is a capped collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {Object} [options] Optional settings. See Collection.prototype.isCapped for a list of options. - * @param {Collection~resultCallback} [callback] The results callback - */ -function isCapped(coll, options, callback) { - optionsOp(coll, options, (err, document) => { - if (err) return handleCallback(callback, err); - handleCallback(callback, null, !!(document && document.capped)); - }); -} - -/** - * 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 {Collection} a Collection instance. - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function mapReduce(coll, map, reduce, options, callback) { - const mapCommandHash = { - mapreduce: coll.s.name, - map: map, - reduce: reduce - }; - - // Exclusion list - const exclusionList = ['readPreference', 'session', 'bypassDocumentValidation']; - - // Add any other options passed in - for (let n in options) { - if ('scope' === n) { - mapCommandHash[n] = processScope(options[n]); - } else { - // Only include if not in exclusion list - if (exclusionList.indexOf(n) === -1) { - mapCommandHash[n] = options[n]; - } - } - } - - options = Object.assign({}, options); - - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); - - // 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') - ) { - // Force readPreference to primary - options.readPreference = 'primary'; - // Decorate command with writeConcern if supported - applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); - } else { - decorateWithReadConcern(mapCommandHash, coll, options); - } - - // Is bypassDocumentValidation specified - if (options.bypassDocumentValidation === true) { - mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Have we specified collation - try { - decorateWithCollation(mapCommandHash, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, mapCommandHash, options, (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 - const 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, { results: result.results, stats: stats }); - } - - // The returned collection - let collection = null; - - // If we have an object it's a different db - if (result.result != null && typeof result.result === 'object') { - const doc = result.result; - // Return a collection from another db - let Db = loadDb(); - collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( - doc.collection - ); - } else { - // Create a collection object that wraps the result collection - collection = coll.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: collection, stats: stats }); - }); -} - -/** - * Return the options of the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {Object} [options] Optional settings. See Collection.prototype.options for a list of options. - * @param {Collection~resultCallback} [callback] The results callback - */ -function optionsOp(coll, opts, callback) { - coll.s.db.listCollections({ name: coll.s.name }, opts).toArray((err, collections) => { - if (err) return handleCallback(callback, err); - if (collections.length === 0) { - return handleCallback( - callback, - MongoError.create({ message: `collection ${coll.s.namespace} not found`, driver: true }) - ); - } - - handleCallback(callback, err, collections[0].options || null); - }); -} - -/** - * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are - * no ordering guarantees for returned results. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - */ -function parallelCollectionScan(coll, options, callback) { - // Create command object - const commandObject = { - parallelCollectionScan: coll.s.name, - numCursors: options.numCursors - }; - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Store the raw value - const raw = options.raw; - delete options['raw']; - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result == null) - return handleCallback( - callback, - new Error('no result returned for parallelCollectionScan'), - null - ); - - options = Object.assign({ explicitlyIgnoreSession: true }, options); - - const cursors = []; - // Add the raw back to the option - if (raw) options.raw = raw; - // Create command cursors for each item - for (let i = 0; i < result.cursors.length; i++) { - const rawId = result.cursors[i].cursor.id; - // Convert cursorId to Long if needed - const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; - // Add a command cursor - cursors.push(coll.s.topology.cursor(coll.s.namespace, cursorId, options)); - } - - handleCallback(callback, null, cursors); - }); -} - -// modifies documents before being inserted or updated -function prepareDocs(coll, docs, options) { - const forceServerObjectId = - typeof options.forceServerObjectId === 'boolean' - ? options.forceServerObjectId - : coll.s.db.options.forceServerObjectId; - - // no need to modify the docs if server sets the ObjectId - if (forceServerObjectId === true) { - return docs; - } - - return docs.map(doc => { - if (forceServerObjectId !== true && doc._id == null) { - doc._id = coll.s.pkFactory.createPk(); - } - - return doc; - }); -} - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope(scope) { - if (!isObject(scope) || scope._bsontype === 'ObjectID') { - return scope; - } - - const keys = Object.keys(scope); - let key; - const new_scope = {}; - - for (let i = keys.length - 1; i >= 0; 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; -} - -/** - * Reindex all indexes on the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {Object} [options] Optional settings. See Collection.prototype.reIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function reIndex(coll, options, callback) { - // Reindex - const cmd = { reIndex: coll.s.name }; - - // Execute the command - executeCommand(coll.s.db, cmd, options, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); -} - -function removeDocuments(coll, 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 || {}; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If selector is null set empty - if (selector == null) selector = {}; - - // Build the op - const op = { q: selector, limit: 0 }; - if (options.single) { - op.limit = 1; - } else if (finalOptions.retryWrites) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute the remove - coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (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); - }); -} - -/** - * Rename the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {string} newName New name of of the collection. - * @param {object} [options] Optional settings. See Collection.prototype.rename for a list of options. - * @param {Collection~collectionResultCallback} [callback] The results callback - */ -function rename(coll, newName, options, callback) { - let Collection = loadCollection(); - // Check the collection name - checkCollectionName(newName); - // Build the command - const renameCollection = `${coll.s.dbName}.${coll.s.name}`; - const toCollection = `${coll.s.dbName}.${newName}`; - const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; - const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; - - // Decorate command with writeConcern if supported - applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); - - // Execute against admin - executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (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( - coll.s.db, - coll.s.topology, - coll.s.dbName, - newName, - coll.s.pkFactory, - coll.s.options - ) - ); - } catch (err) { - return handleCallback(callback, toError(err), null); - } - }); -} - -/** - * Replace a document in the collection. - * - * @method - * @param {Collection} a Collection instance. - * @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] Optional settings. See Collection.prototype.replaceOne for a list of options. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - */ -function replaceOne(coll, filter, doc, options, callback) { - // Set single document update - options.multi = false; - - // Execute update - updateDocuments(coll, filter, doc, options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - 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] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - r.ops = [doc]; - if (callback) callback(null, r); - }); -} - -/** - * Save a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} doc Document to save - * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -function save(coll, doc, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern( - Object.assign({}, options), - { db: coll.s.db, collection: coll }, - options - ); - // Establish if we need to perform an insert or update - if (doc._id != null) { - finalOptions.upsert = true; - return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); - } - - // Insert the document - insertDocuments(coll, [doc], finalOptions, (err, result) => { - if (callback == null) return; - if (doc == null) return handleCallback(callback, null, null); - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); -} - -/** - * Get all the collection statistics. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - * @param {Collection~resultCallback} [callback] The collection result callback - */ -function stats(coll, options, callback) { - // Build command object - const commandObject = { - collStats: coll.s.name - }; - - // Check if we have the scale value - if (options['scale'] != null) commandObject['scale'] = options['scale']; - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); - - // Execute the command - executeCommand(coll.s.db, commandObject, options, callback); -} - -function updateCallback(err, r, callback) { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - 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] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); -} - -function updateDocuments(coll, 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')); - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, 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 || coll.s.serializeFunctions; - - // Execute the operation - const op = { q: selector, u: document }; - op.upsert = options.upsert !== void 0 ? !!options.upsert : false; - op.multi = options.multi !== void 0 ? !!options.multi : false; - - if (finalOptions.arrayFilters) { - op.arrayFilters = finalOptions.arrayFilters; - delete finalOptions.arrayFilters; - } - - if (finalOptions.retryWrites && op.multi) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - // Update options - coll.s.topology.update(coll.s.namespace, [op], finalOptions, (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); - }); -} - -/** - * Update multiple documents in the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} filter The Filter used to select the documents to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options] Optional settings. See Collection.prototype.updateMany for a list of options. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - */ -function updateMany(coll, filter, update, options, callback) { - // Set single document update - options.multi = true; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); -} - -/** - * Update a single document in the collection. - * - * @method - * @param {Collection} a Collection instance. - * @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] Optional settings. See Collection.prototype.updateOne for a list of options. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - */ -function updateOne(coll, filter, update, options, callback) { - // Set single document update - options.multi = false; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); -} - -module.exports = { - bulkWrite, - checkForAtomicOperators, - count, - countDocuments, - buildCountCommand, - createIndex, - createIndexes, - deleteMany, - deleteOne, - distinct, - dropIndex, - dropIndexes, - ensureIndex, - findAndModify, - findAndRemove, - findOne, - findOneAndDelete, - findOneAndReplace, - findOneAndUpdate, - geoHaystackSearch, - group, - indexes, - indexExists, - indexInformation, - insertOne, - isCapped, - mapReduce, - optionsOp, - parallelCollectionScan, - prepareDocs, - reIndex, - removeDocuments, - rename, - replaceOne, - save, - stats, - updateDocuments, - updateMany, - updateOne -}; diff --git a/node_modules/mongodb/lib/operations/cursor_ops.js b/node_modules/mongodb/lib/operations/cursor_ops.js deleted file mode 100644 index fa6db957b866ee79a1d0c7eb9afc1d05beb35376..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/operations/cursor_ops.js +++ /dev/null @@ -1,250 +0,0 @@ -'use strict'; - -const buildCountCommand = require('./collection_ops').buildCountCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('mongodb-core').MongoError; -const push = Array.prototype.push; - -let cursor; -function loadCursor() { - if (!cursor) { - cursor = require('../cursor'); - } - return cursor; -} - -/** - * Get the count of documents for this cursor. - * - * @method - * @param {Cursor} cursor The Cursor instance on which to count. - * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. - * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. - * @param {Cursor~countResultCallback} [callback] The result callback. - */ -function count(cursor, applySkipLimit, opts, callback) { - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (opts.readPreference) { - cursor.setReadPreference(opts.readPreference); - } - - if ( - typeof opts.maxTimeMS !== 'number' && - cursor.s.cmd && - typeof cursor.s.cmd.maxTimeMS === 'number' - ) { - opts.maxTimeMS = cursor.s.cmd.maxTimeMS; - } - - let options = {}; - options.skip = opts.skip; - options.limit = opts.limit; - options.hint = opts.hint; - options.maxTimeMS = opts.maxTimeMS; - - // Command - const delimiter = cursor.s.ns.indexOf('.'); - options.collectionName = cursor.s.ns.substr(delimiter + 1); - - let command; - try { - command = buildCountCommand(cursor, cursor.s.cmd.query, options); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.s.topology.command( - `${cursor.s.ns.substr(0, delimiter)}.$cmd`, - command, - cursor.s.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); -} - -/** - * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. - * - * @method - * @deprecated - * @param {Cursor} cursor The Cursor instance on which to run. - * @param {Cursor~resultCallback} callback The result callback. - */ -function each(cursor, callback) { - let Cursor = loadCursor(); - - if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); - if (cursor.isNotified()) return; - if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === Cursor.INIT) cursor.s.state = Cursor.OPEN; - - // Define function to avoid global scope escape - let fn = null; - // Trampoline all the entries - if (cursor.bufferedCount() > 0) { - while ((fn = loop(cursor, callback))) fn(cursor, callback); - each(cursor, callback); - } else { - cursor.next((err, item) => { - if (err) return handleCallback(callback, err); - if (item == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); - } - - if (handleCallback(callback, null, item) === false) return; - each(cursor, callback); - }); - } -} - -/** - * Check if there is any document still available in the cursor. - * - * @method - * @param {Cursor} cursor The Cursor instance on which to run. - * @param {Cursor~resultCallback} [callback] The result callback. - */ -function hasNext(cursor, callback) { - let Cursor = loadCursor(); - - if (cursor.s.currentDoc) { - return callback(null, true); - } - - if (cursor.isNotified()) { - return callback(null, false); - } - - nextObject(cursor, (err, doc) => { - if (err) return callback(err, null); - if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false); - if (!doc) return callback(null, false); - cursor.s.currentDoc = doc; - callback(null, true); - }); -} - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -function loop(cursor, callback) { - // No more items we are done - if (cursor.bufferedCount() === 0) return; - // Get the next document - cursor._next(callback); - // Loop - return loop; -} - -/** - * Get the next available document from the cursor. Returns null if no more documents are available. - * - * @method - * @param {Cursor} cursor The Cursor instance from which to get the next document. - * @param {Cursor~resultCallback} [callback] The result callback. - */ -function next(cursor, callback) { - // Return the currentDoc if someone called hasNext first - if (cursor.s.currentDoc) { - const doc = cursor.s.currentDoc; - cursor.s.currentDoc = null; - return callback(null, doc); - } - - // Return the next object - nextObject(cursor, callback); -} - -// Get the next available document from the cursor, returns null if no more documents are available. -function nextObject(cursor, callback) { - let Cursor = loadCursor(); - - if (cursor.s.state === Cursor.CLOSED || (cursor.isDead && cursor.isDead())) - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - if (cursor.s.state === Cursor.INIT && cursor.s.cmd.sort) { - try { - cursor.s.cmd.sort = formattedOrderClause(cursor.s.cmd.sort); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Get the next object - cursor._next((err, doc) => { - cursor.s.state = Cursor.OPEN; - if (err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -/** - * Returns an array of documents. See Cursor.prototype.toArray for more information. - * - * @method - * @param {Cursor} cursor The Cursor instance from which to get the next document. - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - */ -function toArray(cursor, callback) { - let Cursor = loadCursor(); - - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = Cursor.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return cursor._endSession - ? cursor._endSession(() => handleCallback(callback, err)) - : handleCallback(callback, err); - } - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - - // Transform the doc if transform method added - if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { - docs = docs.map(cursor.s.transforms.doc); - } - - push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); -} - -module.exports = { count, each, hasNext, next, toArray }; diff --git a/node_modules/mongodb/lib/operations/db_ops.js b/node_modules/mongodb/lib/operations/db_ops.js deleted file mode 100644 index 27179667d5daae1dd17f03e4f2e4ddbe6280a04c..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/operations/db_ops.js +++ /dev/null @@ -1,1006 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('mongodb-core').BSON.Code; -const resolveReadPreference = require('../utils').resolveReadPreference; -const crypto = require('crypto'); -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('mongodb-core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; -const ReadPreference = require('mongodb-core').ReadPreference; -const toError = require('../utils').toError; -const CONSTANTS = require('../constants'); - -const count = require('./collection_ops').count; -const findOne = require('./collection_ops').findOne; -const remove = require('./collection_ops').remove; -const updateOne = require('./collection_ops').updateOne; - -let collection; -function loadCollection() { - if (!collection) { - collection = require('../collection'); - } - return collection; -} -let db; -function loadDb() { - if (!db) { - db = require('../db'); - } - return db; -} - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -// Filter out any write concern options -const illegalCommandFields = [ - 'w', - 'wtimeout', - 'j', - 'fsync', - 'autoIndexId', - 'strict', - 'serializeFunctions', - 'pkFactory', - 'raw', - 'readPreference', - 'session' -]; - -/** - * Add a user to the database. - * @method - * @param {Db} db The Db instance on which to add a user. - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function addUser(db, username, password, options, callback) { - let Db = loadDb(); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Attempt to execute auth command - executeAuthCreateUserCommand(db, username, password, options, (err, r) => { - // We need to perform the backward compatible insert operation - if (err && err.code === -5000) { - const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); - - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - const userPassword = md5.digest('hex'); - - // If we have another db set - const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; - - // Fetch a user collection - const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); - - // Check if we are inserting the first user - count(collection, {}, finalOptions, (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 - const findOptions = Object.assign({ projection: { dbName: 1 } }, finalOptions); - collection.find({ user: username }, findOptions).toArray(err => { - // 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 - updateOne( - collection, - { user: username }, - { $set: { user: username, pwd: userPassword } }, - finalOptions, - err => { - 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); - }); -} - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Db} db The Db instance on which to fetch collections. - * @param {object} [options] Optional settings. See Db.prototype.collections for a list of options. - * @param {Db~collectionsResultCallback} [callback] The results callback - */ -function collections(db, options, callback) { - let Collection = loadCollection(); - - options = Object.assign({}, options, { nameOnly: true }); - // Let's get the collection names - db.listCollections({}, options).toArray((err, documents) => { - if (err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(doc => { - return doc.name.indexOf('$') === -1; - }); - - // Return the collection objects - handleCallback( - callback, - null, - documents.map(d => { - return new Collection( - db, - db.s.topology, - db.s.databaseName, - d.name, - db.s.pkFactory, - db.s.options - ); - }) - ); - }); -} - -/** - * Create a new collection on a server with the specified options. Use this to create capped collections. - * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ - * - * @method - * @param {Db} db The Db instance on which to create the collection. - * @param {string} name The collection name to create. - * @param {object} [options] Optional settings. See Db.prototype.createCollection for a list of options. - * @param {Db~collectionResultCallback} [callback] The results callback - */ -function createCollection(db, name, options, callback) { - let Collection = loadCollection(); - - // Get the write concern options - const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - const listCollectionOptions = Object.assign({}, finalOptions, { nameOnly: true }); - - // Check if we have the name - db - .listCollections({ name }, listCollectionOptions) - .setReadPreference(ReadPreference.PRIMARY) - .toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length > 0 && finalOptions.strict) { - return handleCallback( - callback, - MongoError.create({ - message: `Collection ${name} already exists. Currently in strict mode.`, - driver: true - }), - null - ); - } else if (collections.length > 0) { - try { - return handleCallback( - callback, - null, - new Collection(db, db.s.topology, db.s.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Create collection command - const cmd = { create: name }; - - // Decorate command with writeConcern if supported - applyWriteConcern(cmd, { db }, options); - - // Add all optional parameters - for (let n in options) { - if ( - options[n] != null && - typeof options[n] !== 'function' && - illegalCommandFields.indexOf(n) === -1 - ) { - cmd[n] = options[n]; - } - } - - // Force a primary read Preference - finalOptions.readPreference = ReadPreference.PRIMARY; - // Execute command - executeCommand(db, cmd, finalOptions, err => { - if (err) return handleCallback(callback, err); - - try { - return handleCallback( - callback, - null, - new Collection(db, db.s.topology, db.s.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err); - } - }); - }); -} - -/** - * Creates an index on the db and collection. - * @method - * @param {Db} db The Db instance on which to create an index. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function createIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); - finalOptions = applyWriteConcern(finalOptions, { db }, options); - - // Ensure we have a callback - if (finalOptions.writeConcern && typeof callback !== 'function') { - throw MongoError.create({ - message: 'Cannot use a writeConcern without a provided callback', - driver: true - }); - } - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { - if (err == null) return handleCallback(callback, err, result); - - /** - * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: - * 67 = 'CannotCreateIndex' (malformed index options) - * 85 = 'IndexOptionsConflict' (index already exists with different options) - * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) - * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) - * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) - * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) - */ - if ( - err.code === 67 || - err.code === 11000 || - err.code === 85 || - err.code === 86 || - err.code === 11600 || - err.code === 197 - ) { - return handleCallback(callback, err, result); - } - - // Create command - const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); - // Set no key checking - finalOptions.checkKeys = false; - // Insert document - db.s.topology.insert( - `${db.s.databaseName}.${CONSTANTS.SYSTEM_INDEX_COLLECTION}`, - doc, - finalOptions, - (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); - } - ); - }); -} - -// Add listeners to topology -function createListener(db, e, object) { - function listener(err) { - if (object.listeners(e).length > 0) { - object.emit(e, err, db); - - // Emit on all associated db's if available - for (let i = 0; i < db.s.children.length; i++) { - db.s.children[i].emit(e, err, db.s.children[i]); - } - } - } - return listener; -} - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {Db} db The Db instance on which to drop the collection. - * @param {string} name Name of collection to drop - * @param {Object} [options] Optional settings. See Db.prototype.dropCollection for a list of options. - * @param {Db~resultCallback} [callback] The results callback - */ -function dropCollection(db, name, options, callback) { - executeCommand(db, name, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - if (result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); -} - -/** - * Drop a database, removing it permanently from the server. - * - * @method - * @param {Db} db The Db instance to drop. - * @param {Object} cmd The command document. - * @param {Object} [options] Optional settings. See Db.prototype.dropDatabase for a list of options. - * @param {Db~resultCallback} [callback] The results callback - */ -function dropDatabase(db, cmd, options, callback) { - executeCommand(db, cmd, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); -} - -/** - * Ensures that an index exists. If it does not, creates it. - * - * @method - * @param {Db} db The Db instance on which to ensure the index. - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function ensureIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern({}, { db }, options); - // Create command - const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); - const index_name = selector.name; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Merge primary readPreference - finalOptions.readPreference = ReadPreference.PRIMARY; - - // Check if the index already exists - indexInformation(db, name, finalOptions, (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]) { - createIndex(db, name, fieldOrSpec, options, callback); - } else { - if (typeof callback === 'function') return handleCallback(callback, null, index_name); - } - }); -} - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Db} db The Db instance. - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - */ -function evaluate(db, code, parameters, options, callback) { - let finalCode = code; - let finalParameters = []; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // If not a code object translate to one - if (!(finalCode && finalCode._bsontype === '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 - let 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 ReadPreference(ReadPreference.PRIMARY); - - // Execute the command - executeCommand(db, cmd, options, (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, - MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), - null - ); - handleCallback(callback, err, result); - }); -} - -/** - * Execute a command - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeCommand(db, command, options, callback) { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.s.databaseName; - - // Convert the readPreference if its not a write - options.readPreference = resolveReadPreference(options, { db, default: ReadPreference.primary }); - - // Debug information - if (db.s.logger.isDebug()) - db.s.logger.debug( - `executing command ${JSON.stringify( - command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - - // Execute command - db.s.topology.command(`${dbName}.$cmd`, command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); -} - -/** - * Runs a command on the database as admin. - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeDbAdminCommand(db, command, options, callback) { - db.s.topology.command('admin.$cmd', command, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db - .collection(name) - .listIndexes(options) - .toArray((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)); - }); -} - -// Transformation methods for cursor results -function listCollectionsTransforms(databaseName) { - const matching = `${databaseName}.`; - - return { - doc: doc => { - const 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; - } - }; -} - -/** - * Retrive the current profiling information for MongoDB - * - * @method - * @param {Db} db The Db instance on which to retrieve the profiling info. - * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - * @deprecated Query the system.profile collection directly. - */ -function profilingInfo(db, options, callback) { - try { - db - .collection('system.profile') - .find({}, options) - .toArray(callback); - } catch (err) { - return callback(err, null); - } -} - -/** - * Retrieve the current profiling level for MongoDB - * - * @method - * @param {Db} db The Db instance on which to retrieve the profiling level. - * @param {Object} [options] Optional settings. See Db.prototype.profilingLevel for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function profilingLevel(db, options, callback) { - executeCommand(db, { profile: -1 }, options, (err, doc) => { - if (err == null && doc.ok === 1) { - const 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); - } - }); -} - -/** - * Remove a user from a database - * - * @method - * @param {Db} db The Db instance on which to remove the user. - * @param {string} username The username. - * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function removeUser(db, username, options, callback) { - let Db = loadDb(); - - // Attempt to execute command - executeAuthRemoveUserCommand(db, username, options, (err, result) => { - if (err && err.code === -5000) { - const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); - // If we have another db set - const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; - - // Fetch a user collection - const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); - - // Locate the user - findOne(collection, { user: username }, finalOptions, (err, user) => { - if (user == null) return handleCallback(callback, err, false); - remove(collection, { user: username }, finalOptions, err => { - handleCallback(callback, err, true); - }); - }); - - return; - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, err, result); - }); -} - -/** - * Set the current profiling level of MongoDB - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {string} level The new profiling level (off, slow_only, all). - * @param {Object} [options] Optional settings. See Db.prototype.setProfilingLevel for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - */ -function setProfilingLevel(db, level, options, callback) { - const command = {}; - let 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; - - executeCommand(db, command, options, (err, 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); - }); -} - -// Validate the database name -function validateDatabaseName(databaseName) { - if (typeof databaseName !== 'string') - throw MongoError.create({ message: 'database name must be a string', driver: true }); - if (databaseName.length === 0) - throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); - if (databaseName === '$external') return; - - const invalidChars = [' ', '.', '$', '/', '\\']; - for (let i = 0; i < invalidChars.length; i++) { - if (databaseName.indexOf(invalidChars[i]) !== -1) - throw MongoError.create({ - message: "database names cannot contain the character '" + invalidChars[i] + "'", - driver: true - }); - } -} - -/** - * Create the command object for Db.prototype.createIndex. - * - * @param {Db} db The Db instance on which to create the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @return {Object} The insert command object. - */ -function createCreateIndexCommand(db, name, fieldOrSpec, options) { - const indexParameters = parseIndexOptions(fieldOrSpec); - const fieldHash = indexParameters.fieldHash; - - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - const selector = { - ns: db.databaseName + '.' + name, - key: fieldHash, - name: indexName - }; - - // Ensure we have a correct finalUnique - const finalUnique = options == null || 'object' === typeof options ? false : options; - // Set up options - options = options == null || typeof options === 'boolean' ? {} : options; - - // Add all the options - const keysToOmit = Object.keys(selector); - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - selector[optionName] = options[optionName]; - } - } - - if (selector['unique'] == null) selector['unique'] = finalUnique; - - // Remove any write concern operations - const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; - for (let i = 0; i < removeKeys.length; i++) { - delete selector[removeKeys[i]]; - } - - // Return the command creation selector - return selector; -} - -/** - * Create index using the createIndexes command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - */ -function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { - // Build the index - const indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; - // merge all the options - const keysToOmit = Object.keys(indexes[0]).concat([ - 'writeConcern', - 'w', - 'wtimeout', - 'j', - 'fsync', - 'readPreference', - 'session' - ]); - - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - indexes[0][optionName] = options[optionName]; - } - } - - // Get capabilities - const capabilities = db.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - const error = new MongoError('server/primary/mongos does not support collation'); - error.code = 67; - // Return the error - return callback(error); - } - - // Create command, apply write concern to command - const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); - - // ReadPreference primary - options.readPreference = ReadPreference.PRIMARY; - - // Build the command - executeCommand(db, cmd, options, (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); - }); -} - -/** - * Run the createUser command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} username The username of the user to add. - * @param {string} password The password of the user to add. - * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeAuthCreateUserCommand(db, 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) { - return callback( - toError( - "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." - ) - ); - } - - // Get additional values - const customData = options.customData != null ? options.customData : {}; - let roles = Array.isArray(options.roles) ? options.roles : []; - const 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 - const 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 ( - (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && - !Array.isArray(options.roles) - ) { - roles = ['root']; - } else if (!Array.isArray(options.roles)) { - roles = ['dbOwner']; - } - - const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; - - // Build the command to execute - let command = { - createUser: username, - customData: customData, - roles: roles, - digestPassword - }; - - // Apply write concern to command - command = applyWriteConcern(command, { db }, options); - - let userPassword = password; - - if (!digestPassword) { - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - userPassword = md5.digest('hex'); - } - - // No password - if (typeof password === 'string') { - command.pwd = userPassword; - } - - // Force write using primary - commandOptions.readPreference = ReadPreference.primary; - - // Execute the command - executeCommand(db, command, commandOptions, (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 - ); - }); -} - -/** - * Run the dropUser command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} username The username of the user to remove. - * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeAuthRemoveUserCommand(db, username, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Get the error options - const commandOptions = { writeCommand: true }; - if (options['dbName']) commandOptions.dbName = options['dbName']; - - // Get additional values - const 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 - let command = { - dropUser: username - }; - - // Apply write concern to command - command = applyWriteConcern(command, { db }, options); - - // Force write using primary - commandOptions.readPreference = ReadPreference.primary; - - // Execute the command - executeCommand(db, command, commandOptions, (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); - }); -} - -module.exports = { - addUser, - collections, - createCollection, - createListener, - createIndex, - dropCollection, - dropDatabase, - ensureIndex, - evaluate, - executeCommand, - executeDbAdminCommand, - listCollectionsTransforms, - indexInformation, - profilingInfo, - profilingLevel, - removeUser, - setProfilingLevel, - validateDatabaseName -}; diff --git a/node_modules/mongodb/lib/operations/mongo_client_ops.js b/node_modules/mongodb/lib/operations/mongo_client_ops.js deleted file mode 100644 index d53ee7c235ec49e6b8f8a67ca9d20d1d9e5c2c51..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/operations/mongo_client_ops.js +++ /dev/null @@ -1,654 +0,0 @@ -'use strict'; - -const authenticate = require('../authenticate'); -const deprecate = require('util').deprecate; -const Logger = require('mongodb-core').Logger; -const MongoError = require('mongodb-core').MongoError; -const Mongos = require('../topologies/mongos'); -const parse = require('mongodb-core').parseConnectionString; -const ReadPreference = require('mongodb-core').ReadPreference; -const ReplSet = require('../topologies/replset'); -const Server = require('../topologies/server'); -const ServerSessionPool = require('mongodb-core').Sessions.ServerSessionPool; - -let client; -function loadClient() { - if (!client) { - client = require('../mongo_client'); - } - return client; -} - -const monitoringEvents = [ - 'timeout', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha', - 'all', - 'fullsetup', - 'open' -]; -const ignoreOptionNames = ['native_parser']; -const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; -const legacyParse = deprecate( - require('../url_parser'), - 'current URL string parser is deprecated, and will be removed in a future version. ' + - 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' -); -const validOptionNames = [ - 'poolSize', - 'ssl', - 'sslValidate', - 'sslCA', - 'sslCert', - 'sslKey', - 'sslPass', - 'sslCRL', - 'autoReconnect', - 'noDelay', - 'keepAlive', - 'keepAliveInitialDelay', - 'connectTimeoutMS', - 'family', - 'socketTimeoutMS', - 'reconnectTries', - 'reconnectInterval', - 'ha', - 'haInterval', - 'replicaSet', - 'secondaryAcceptableLatencyMS', - 'acceptableLatencyMS', - 'connectWithNoPrimary', - 'authSource', - 'w', - 'wtimeout', - 'j', - 'forceServerObjectId', - 'serializeFunctions', - 'ignoreUndefined', - 'raw', - 'bufferMaxEntries', - 'readPreference', - 'pkFactory', - 'promiseLibrary', - 'readConcern', - 'maxStalenessSeconds', - 'loggerLevel', - 'logger', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs', - 'domainsEnabled', - 'checkServerIdentity', - 'validateOptions', - 'appname', - 'auth', - 'user', - 'password', - 'authMechanism', - 'compression', - 'fsync', - 'readPreferenceTags', - 'numberOfRetries', - 'auto_reconnect', - 'minSize', - 'monitorCommands', - 'retryWrites', - 'useNewUrlParser' -]; - -function addListeners(mongoClient, topology) { - topology.on('authenticated', createListener(mongoClient, 'authenticated')); - topology.on('error', createListener(mongoClient, 'error')); - topology.on('timeout', createListener(mongoClient, 'timeout')); - topology.on('close', createListener(mongoClient, 'close')); - topology.on('parseError', createListener(mongoClient, 'parseError')); - topology.once('open', createListener(mongoClient, 'open')); - topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); - topology.once('all', createListener(mongoClient, 'all')); - topology.on('reconnect', createListener(mongoClient, 'reconnect')); -} - -function assignTopology(client, topology) { - client.topology = topology; - topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology); -} - -// Clear out all events -function clearAllEvents(topology) { - monitoringEvents.forEach(event => topology.removeAllListeners(event)); -} - -// Collect all events in order from SDAM -function collectEvents(mongoClient, topology) { - let MongoClient = loadClient(); - const collectedEvents = []; - - if (mongoClient instanceof MongoClient) { - monitoringEvents.forEach(event => { - topology.on(event, (object1, object2) => { - if (event === 'open') { - collectedEvents.push({ event: event, object1: mongoClient }); - } else { - collectedEvents.push({ event: event, object1: object1, object2: object2 }); - } - }); - }); - } - - return collectedEvents; -} - -/** - * 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 {MongoClient} mongoClient The MongoClient instance with which to connect. - * @param {string} url The connection URI string - * @param {object} [options] Optional settings. See MongoClient.prototype.connect for a list of options. - * @param {MongoClient~connectCallback} [callback] The command result callback - */ -function connect(mongoClient, url, options, callback) { - options = Object.assign({}, options); - - // If callback is null throw an exception - if (callback == null) { - throw new Error('no callback function provided'); - } - - // Get a logger for MongoClient - const logger = Logger('MongoClient', options); - - // Did we pass in a Server/ReplSet/Mongos - if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { - return connectWithUrl(mongoClient, url, options, connectCallback); - } - - const parseFn = options.useNewUrlParser ? parse : legacyParse; - const transform = options.useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; - - parseFn(url, options, (err, _object) => { - // Do not attempt to connect if parsing error - if (err) return callback(err); - - // Flatten - const object = transform(_object); - - // Parse the string - const _finalOptions = createUnifiedOptions(object, options); - - // Check if we have connection and socket timeout set - if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; - if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000; - - if (_finalOptions.db_options && _finalOptions.db_options.auth) { - delete _finalOptions.db_options.auth; - } - - // Store the merged options object - mongoClient.s.options = _finalOptions; - - // Failure modes - if (object.servers.length === 0) { - return callback(new Error('connection string must contain at least one seed host')); - } - - // Do we have a replicaset then skip discovery and go straight to connectivity - if (_finalOptions.replicaSet || _finalOptions.rs_name) { - return createTopology( - mongoClient, - 'replicaset', - _finalOptions, - connectHandler(mongoClient, _finalOptions, connectCallback) - ); - } else if (object.servers.length > 1) { - return createTopology( - mongoClient, - 'mongos', - _finalOptions, - connectHandler(mongoClient, _finalOptions, connectCallback) - ); - } else { - return createServer( - mongoClient, - _finalOptions, - connectHandler(mongoClient, _finalOptions, connectCallback) - ); - } - }); - function connectCallback(err, topology) { - const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; - if (err && err.message === 'no mongos proxies found in seed list') { - if (logger.isWarn()) { - logger.warn(warningMessage); - } - - // Return a more specific error message for MongoClient.connect - return callback(new MongoError(warningMessage)); - } - - // Return the error and db instance - callback(err, topology); - } -} - -function connectHandler(client, options, callback) { - return (err, topology) => { - if (err) { - return handleConnectCallback(err, topology, callback); - } - - // No authentication just reconnect - if (!options.auth) { - return handleConnectCallback(err, topology, callback); - } - - // Authenticate - authenticate(client, options.user, options.password, options, (err, success) => { - if (success) { - handleConnectCallback(null, topology, callback); - } else { - if (topology) topology.close(); - const authError = err ? err : new Error('Could not authenticate user ' + options.auth[0]); - handleConnectCallback(authError, topology, callback); - } - }); - }; -} - -/** - * 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 {MongoClient} mongoClient The MongoClient instance with which to connect. - * @param {MongoClient~connectCallback} [callback] The command result callback - */ -function connectOp(mongoClient, err, callback) { - // Did we have a validation error - if (err) return callback(err); - // Fallback to callback based connect - connect(mongoClient, mongoClient.s.url, mongoClient.s.options, err => { - if (err) return callback(err); - callback(null, mongoClient); - }); -} - -function connectWithUrl(mongoClient, url, options, connectCallback) { - // Set the topology - assignTopology(mongoClient, url); - - // Add listeners - addListeners(mongoClient, url); - - // Propagate the events to the client - relayEvents(mongoClient, url); - - let finalOptions = Object.assign({}, options); - - // If we have a readPreference passed in by the db options, convert it from a string - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - finalOptions.readPreference = new ReadPreference( - options.readPreference || options.read_preference - ); - } - - // Connect - return url.connect( - finalOptions, - connectHandler(mongoClient, finalOptions, (err, topology) => { - if (err) return connectCallback(err, topology); - if (finalOptions.user || finalOptions.password || finalOptions.authMechanism) { - return authenticate( - mongoClient, - finalOptions.user, - finalOptions.password, - finalOptions, - err => { - if (err) return connectCallback(err, topology); - connectCallback(err, topology); - } - ); - } - - connectCallback(err, topology); - }) - ); -} - -function createListener(mongoClient, event) { - const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); - return (v1, v2) => { - if (eventSet.has(event)) { - return mongoClient.emit(event, mongoClient); - } - - mongoClient.emit(event, v1, v2); - }; -} - -function createServer(mongoClient, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - // Set default options - const servers = translateOptions(options); - - const server = servers[0]; - - // Propagate the events to the client - const collectedEvents = collectEvents(mongoClient, server); - - // Connect to topology - server.connect(options, (err, topology) => { - if (err) { - server.close(true); - return callback(err); - } - // Clear out all the collected event listeners - clearAllEvents(server); - - // Relay all the events - relayEvents(mongoClient, server); - // Add listeners - addListeners(mongoClient, server); - // Check if we are really speaking to a mongos - const ismaster = topology.lastIsMaster(); - - // Set the topology - assignTopology(mongoClient, topology); - - // Do we actually have a mongos - if (ismaster && ismaster.msg === 'isdbgrid') { - // Destroy the current connection - topology.close(); - // Create mongos connection instead - return createTopology(mongoClient, 'mongos', options, callback); - } - - // Fire all the events - replayEvents(mongoClient, collectedEvents); - // Otherwise callback - callback(err, topology); - }); -} - -function createTopology(mongoClient, topologyType, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - const translationOptions = {}; - if (topologyType === 'unified') translationOptions.createServers = false; - - // Set default options - const servers = translateOptions(options, translationOptions); - - // Create the topology - let topology; - if (topologyType === 'mongos') { - topology = new Mongos(servers, options); - } else if (topologyType === 'replicaset') { - topology = new ReplSet(servers, options); - } - - // Add listeners - addListeners(mongoClient, topology); - - // Propagate the events to the client - relayEvents(mongoClient, topology); - - // Open the connection - topology.connect(options, (err, newTopology) => { - if (err) { - topology.close(true); - return callback(err); - } - - assignTopology(mongoClient, newTopology); - callback(null, newTopology); - }); -} - -function createUnifiedOptions(finalOptions, options) { - const childOptions = [ - 'mongos', - 'server', - 'db', - 'replset', - 'db_options', - 'server_options', - 'rs_options', - 'mongos_options' - ]; - const noMerge = ['readconcern', 'compression']; - - for (const name in options) { - if (noMerge.indexOf(name.toLowerCase()) !== -1) { - finalOptions[name] = options[name]; - } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { - finalOptions = mergeOptions(finalOptions, options[name], false); - } else { - if ( - options[name] && - typeof options[name] === 'object' && - !Buffer.isBuffer(options[name]) && - !Array.isArray(options[name]) - ) { - finalOptions = mergeOptions(finalOptions, options[name], true); - } else { - finalOptions[name] = options[name]; - } - } - } - - return finalOptions; -} - -function handleConnectCallback(err, topology, callback) { - return process.nextTick(() => { - try { - callback(err, topology); - } catch (err) { - if (topology) topology.close(); - throw err; - } - }); -} - -function legacyTransformUrlOptions(object) { - return mergeOptions(createUnifiedOptions({}, object), object, false); -} - -/** - * Logout user from server, fire off on all connections and remove all auth info. - * - * @method - * @param {MongoClient} mongoClient The MongoClient instance on which to logout. - * @param {object} [options] Optional settings. See MongoClient.prototype.logout for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function logout(mongoClient, dbName, callback) { - mongoClient.topology.logout(dbName, err => { - if (err) return callback(err); - callback(null, true); - }); -} - -function mergeOptions(target, source, flatten) { - for (const name in source) { - if (source[name] && typeof source[name] === 'object' && flatten) { - target = mergeOptions(target, source[name], flatten); - } else { - target[name] = source[name]; - } - } - - return target; -} - -function relayEvents(mongoClient, topology) { - const serverOrCommandEvents = [ - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha' - ]; - - serverOrCommandEvents.forEach(event => { - topology.on(event, (object1, object2) => { - mongoClient.emit(event, object1, object2); - }); - }); -} - -// -// Replay any events due to single server connection switching to Mongos -// -function replayEvents(mongoClient, events) { - for (let i = 0; i < events.length; i++) { - mongoClient.emit(events[i].event, events[i].object1, events[i].object2); - } -} - -const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { - obj[name.toLowerCase()] = name; - return obj; -}, {}); - -function transformUrlOptions(_object) { - let object = Object.assign({ servers: _object.hosts }, _object.options); - for (let name in object) { - const camelCaseName = LEGACY_OPTIONS_MAP[name]; - if (camelCaseName) { - object[camelCaseName] = object[name]; - } - } - if (_object.auth) { - const auth = _object.auth; - for (let i in auth) { - if (auth[i]) { - object[i] = auth[i]; - } - } - - if (auth.username) { - object.auth = auth; - object.user = auth.username; - } - - if (auth.db) { - object.authSource = object.authSource || auth.db; - } - } - - if (_object.defaultDatabase) { - object.dbName = _object.defaultDatabase; - } - - if (object.maxpoolsize) { - object.poolSize = object.maxpoolsize; - } - - if (object.readconcernlevel) { - object.readConcern = { level: object.readconcernlevel }; - } - - if (object.wtimeoutms) { - object.wtimeout = object.wtimeoutms; - } - - return object; -} - -function translateOptions(options, translationOptions) { - translationOptions = Object.assign({}, { createServers: true }, translationOptions); - - // If we have a readPreference passed in by the db options - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - options.readPreference = new ReadPreference(options.readPreference || options.read_preference); - } - - // Do we have readPreference tags, add them - if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { - options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; - } - - // Do we have maxStalenessSeconds - if (options.maxStalenessSeconds) { - options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; - } - - // Set the socket and connection timeouts - if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; - if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000; - - if (!translationOptions.createServers) { - return; - } - - // Create server instances - return options.servers.map(serverObj => { - return serverObj.domain_socket - ? new Server(serverObj.domain_socket, 27017, options) - : new Server(serverObj.host, serverObj.port, options); - }); -} - -// Validate options object -function validOptions(options) { - const _validOptions = validOptionNames.concat(legacyOptionNames); - - for (const name in options) { - if (ignoreOptionNames.indexOf(name) !== -1) { - continue; - } - - if (_validOptions.indexOf(name) === -1 && options.validateOptions) { - return new MongoError(`option ${name} is not supported`); - } else if (_validOptions.indexOf(name) === -1) { - console.warn(`the options [${name}] is not supported`); - } - - if (legacyOptionNames.indexOf(name) !== -1) { - console.warn( - `the server/replset/mongos/db options are deprecated, ` + - `all their options are supported at the top level of the options object [${validOptionNames}]` - ); - } - } -} - -module.exports = { connectOp, logout, validOptions }; diff --git a/node_modules/mongodb/lib/topologies/mongos.js b/node_modules/mongodb/lib/topologies/mongos.js deleted file mode 100644 index dc142773701339f3a380a6ca273af2b1c4a8f924..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/topologies/mongos.js +++ /dev/null @@ -1,452 +0,0 @@ -'use strict'; - -const TopologyBase = require('./topology_base').TopologyBase; -const MongoError = require('mongodb-core').MongoError; -const CMongos = require('mongodb-core').Mongos; -const Cursor = require('../cursor'); -const Server = require('./server'); -const Store = require('./topology_base').Store; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @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** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Mongos instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] 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 {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [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] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslCert] 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] 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] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @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 - * @fires Mongos#commandStarted - * @fires Mongos#commandSucceeded - * @fires Mongos#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Mongos} a Mongos instance. - */ -class Mongos extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the mongodb-core ones - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if (options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Internal state - this.s = { - // Create the Mongos - coreTopology: new CMongos(seedlist, clonedOptions), - // Server capabilities - sCapabilities: null, - // Debug turned on - debug: clonedOptions.debug, - // Store option defaults - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Actual store of callbacks - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: [], - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Force close the topology - self.close(true); - - // 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() { - self.emit('reconnect'); - self.s.store.execute(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - var events = ['timeout', 'error', 'close', 'fullsetup']; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.on('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - - // Set up serverConfig listeners - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self); - }); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - // Join and leave events - self.s.coreTopology.on('joined', relay('joined')); - self.s.coreTopology.on('left', relay('left')); - - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Mongos.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * 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} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/node_modules/mongodb/lib/topologies/replset.js b/node_modules/mongodb/lib/topologies/replset.js deleted file mode 100644 index 0a73134437922bb1c7de6771564483adf7ab21a1..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/topologies/replset.js +++ /dev/null @@ -1,497 +0,0 @@ -'use strict'; - -const Server = require('./server'); -const Cursor = require('../cursor'); -const MongoError = require('mongodb-core').MongoError; -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const CReplSet = require('mongodb-core').ReplSet; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @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** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'replicaSet', - 'rs_name', - 'secondaryAcceptableLatencyMS', - 'connectWithNoPrimary', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslCRL', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'strategy', - 'debug', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'maxStalenessSeconds', - 'promiseLibrary', - 'minSize', - 'monitorCommands' -]; - -/** - * Creates a new ReplSet instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {boolean} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=10000] 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 {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [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] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] 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] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @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 - * @fires ReplSet#commandStarted - * @fires ReplSet#commandSucceeded - * @fires ReplSet#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {ReplSet} a ReplSet instance. - */ -class ReplSet extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the mongodb-core ones - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if (options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Create the ReplSet - var coreTopology = new CReplSet(seedlist, clonedOptions); - - // Listen to reconnect event - coreTopology.on('reconnect', function() { - self.emit('reconnect'); - store.execute(); - }); - - // Internal state - this.s = { - // Replicaset - coreTopology: coreTopology, - // Server capabilities - sCapabilities: null, - // Debug tag - tag: options.tag, - // Store options - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Store - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: [], - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - - // Debug - if (clonedOptions.debug) { - // Last ismaster - Object.defineProperty(this, 'replset', { - enumerable: true, - get: function() { - return coreTopology; - } - }); - } - } - - // Connect method - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // 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.coreTopology.on('joined', replsetRelay('joined')); - self.s.coreTopology.on('left', relay('left')); - self.s.coreTopology.on('ping', relay('ping')); - self.s.coreTopology.on('ha', relayHa); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self, self); - }); - - self.s.coreTopology.on('all', function() { - self.emit('all', null, self); - }); - - // Connect handler - var connectHandler = function() { - // Set up listeners - self.s.coreTopology.once('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.once('close', errorHandler('close')); - - // 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() { - return function(err) { - ['timeout', 'error', 'close'].forEach(function(e) { - self.s.coreTopology.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Destroy the replset - self.s.coreTopology.destroy(); - - // Try to callback - try { - callback(err); - } catch (err) { - if (!self.s.coreTopology.isConnected()) - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } - - close(forceClosed) { - super.close(forceClosed); - - ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); - } -} - -Object.defineProperty(ReplSet.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * 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} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/node_modules/mongodb/lib/topologies/server.js b/node_modules/mongodb/lib/topologies/server.js deleted file mode 100644 index 77d8b6e5dc1adc6dd422ae40bf9cc33540926d33..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/topologies/server.js +++ /dev/null @@ -1,455 +0,0 @@ -'use strict'; - -const CServer = require('mongodb-core').Server; -const Cursor = require('../cursor'); -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const MongoError = require('mongodb-core').MongoError; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @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** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'reconnectInterval', - 'monitoring', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'compression', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * 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] 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 {boolean} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] 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] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @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 - * @param {number} [options.monitoring=true] Triggers the server instance to call ismaster - * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#commandStarted - * @fires Server#commandSucceeded - * @fires Server#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Server} a Server instance. - */ -class Server extends TopologyBase { - constructor(host, port, options) { - super(); - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Promise library - const promiseLibrary = options.promiseLibrary; - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // 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 MongoError.create({ message: 'port must be specified', driver: true }); - } - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - host: host, - port: port, - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the mongodb-core ones - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if (options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Define the internal properties - this.s = { - // Create an instance of a server instance from mongodb-core - coreTopology: new CServer(clonedOptions), - // Server capabilities - sCapabilities: null, - // Cloned options - clonedOptions: clonedOptions, - // Reconnect - reconnect: clonedOptions.reconnect, - // Emit error - emitError: clonedOptions.emitError, - // Pool size - poolSize: clonedOptions.size, - // Store Options - storeOptions: storeOptions, - // Store - store: store, - // Host - host: host, - // Port - port: port, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: [], - // Promise library - promiseLibrary: promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = this.s.clonedOptions; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.s.coreTopology.removeListener(e, connectHandlers[e]); - }); - - self.s.coreTopology.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() { - self.emit('reconnect', self); - self.s.store.execute(); - }; - - // Reconnect failed - var reconnectFailedHandler = function(err) { - self.emit('reconnectFailed', err); - self.s.store.flush(err); - }; - - // Destroy called on topology, perform cleanup - var destroyHandler = function() { - self.s.store.flush(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - // Only called on destroy - self.s.coreTopology.on('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') - }; - - // Clear out all the current handlers left over - [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Add the event handlers - self.s.coreTopology.once('timeout', connectHandlers.timeout); - self.s.coreTopology.once('error', connectHandlers.error); - self.s.coreTopology.once('close', connectHandlers.close); - self.s.coreTopology.once('connect', connectHandler); - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); - self.s.coreTopology.on('monitoring', relay('monitoring')); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Server.prototype, 'poolSize', { - enumerable: true, - get: function() { - return this.s.coreTopology.connections().length; - } -}); - -Object.defineProperty(Server.prototype, 'autoReconnect', { - enumerable: true, - get: function() { - return this.s.reconnect; - } -}); - -Object.defineProperty(Server.prototype, 'host', { - enumerable: true, - get: function() { - return this.s.host; - } -}); - -Object.defineProperty(Server.prototype, 'port', { - enumerable: true, - get: function() { - return this.s.port; - } -}); - -/** - * 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} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Server#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Server#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Server#commandFailed - * @type {object} - */ - -module.exports = Server; diff --git a/node_modules/mongodb/lib/topologies/topology_base.js b/node_modules/mongodb/lib/topologies/topology_base.js deleted file mode 100644 index 54f848c9740b9d34ef5b06e0ad049430d82fc669..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/topologies/topology_base.js +++ /dev/null @@ -1,446 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'), - MongoError = require('mongodb-core').MongoError, - f = require('util').format, - os = require('os'), - translateReadPreference = require('../utils').translateReadPreference, - ClientSession = require('mongodb-core').Sessions.ClientSession; - -// 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(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - 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( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - 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(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - 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( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); -}; - -Store.prototype.flush = function(err) { - while (this.s.storedOps.length > 0) { - this.s.storedOps - .shift() - .c( - err || - MongoError.create({ message: f('no connection available for operation'), driver: true }) - ); - } -}; - -var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; -var secondaryOptions = ['secondary', 'secondaryPreferred']; - -Store.prototype.execute = function(options) { - options = options || {}; - // Get current ops - var ops = this.s.storedOps; - // Reset the ops - this.s.storedOps = []; - - // Unpack options - var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; - var executeSecondary = - typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; - - // Execute all the stored ops - while (ops.length > 0) { - var op = ops.shift(); - - if (op.t === 'cursor') { - if (executePrimary && executeSecondary) { - op.o[op.m].apply(op.o, op.p); - } else if ( - executePrimary && - op.o.options && - op.o.options.readPreference && - primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } else if ( - !executePrimary && - executeSecondary && - op.o.options && - op.o.options.readPreference && - secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } - } else if (op.t === 'auth') { - this.s.topology[op.t].apply(this.s.topology, op.o); - } else { - if (executePrimary && executeSecondary) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - executePrimary && - op.op && - op.op.readPreference && - primaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - !executePrimary && - executeSecondary && - op.op && - op.op.readPreference && - secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - 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; - var commandsTakeWriteConcern = false; - var commandsTakeCollation = false; - - 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 (ismaster.maxWireVersion >= 5) { - commandsTakeWriteConcern = true; - commandsTakeCollation = 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); - setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); - setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); -}; - -// Get package.json variable -const driverVersion = require('../../package.json').version, - nodejsversion = f('Node.js %s, %s', process.version, os.endianness()), - type = os.type(), - name = process.platform, - architecture = process.arch, - release = os.release(); - -class TopologyBase extends EventEmitter { - constructor() { - super(); - - // Build default client information - this.clientInfo = { - driver: { - name: 'nodejs', - version: driverVersion - }, - os: { - type: type, - name: name, - architecture: architecture, - version: release - }, - platform: nodejsversion - }; - - this.setMaxListeners(Infinity); - } - - // Sessions related methods - hasSessionSupport() { - return this.logicalSessionTimeoutMinutes != null; - } - - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - session.once('ended', () => { - this.s.sessions = this.s.sessions.filter(s => !s.equals(session)); - }); - - this.s.sessions.push(session); - return session; - } - - endSessions(sessions, callback) { - return this.s.coreTopology.endSessions(sessions, callback); - } - - // Server capabilities - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.s.coreTopology.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - this.s.coreTopology.command(ns, cmd, translateReadPreference(options), callback); - } - - // Insert - insert(ns, ops, options, callback) { - this.s.coreTopology.insert(ns, ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - this.s.coreTopology.update(ns, ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - this.s.coreTopology.remove(ns, ops, options, callback); - } - - // IsConnected - isConnected(options) { - options = options || {}; - options = translateReadPreference(options); - - return this.s.coreTopology.isConnected(options); - } - - // IsDestroyed - isDestroyed() { - return this.s.coreTopology.isDestroyed(); - } - - // Cursor - cursor(ns, cmd, options) { - options = options || {}; - options = translateReadPreference(options); - options.disconnectHandler = this.s.store; - options.topology = this; - - return this.s.coreTopology.cursor(ns, cmd, options); - } - - lastIsMaster() { - return this.s.coreTopology.lastIsMaster(); - } - - selectServer(selector, options, callback) { - return this.s.coreTopology.selectServer(selector, options, callback); - } - - /** - * Unref all sockets - * @method - */ - unref() { - return this.s.coreTopology.unref(); - } - - auth() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.coreTopology.auth.apply(this.s.coreTopology, args); - } - - logout() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.coreTopology.logout.apply(this.s.coreTopology, args); - } - - /** - * All raw connections - * @method - * @return {array} - */ - connections() { - return this.s.coreTopology.connections(); - } - - close(forceClosed) { - // If we have sessions, we want to individually move them to the session pool, - // and then send a single endSessions call. - if (this.s.sessions.length) { - this.s.sessions.forEach(session => session.endSession()); - } - - if (this.s.sessionPool) { - this.s.sessionPool.endAllPooledSessions(); - } - - this.s.coreTopology.destroy({ - force: typeof forceClosed === 'boolean' ? forceClosed : false - }); - - // We need to wash out all stored processes - if (forceClosed === true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } - } -} - -// Properties -Object.defineProperty(TopologyBase.prototype, 'bson', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.bson; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'parserType', { - enumerable: true, - get: function() { - return this.s.coreTopology.parserType; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.coreTopology.logicalSessionTimeoutMinutes; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'type', { - enumerable: true, - get: function() { - return this.s.coreTopology.type; - } -}); - -exports.Store = Store; -exports.ServerCapabilities = ServerCapabilities; -exports.TopologyBase = TopologyBase; diff --git a/node_modules/mongodb/lib/url_parser.js b/node_modules/mongodb/lib/url_parser.js deleted file mode 100644 index 7cc0b2f2935192198b0618e6027e2d544430f903..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/url_parser.js +++ /dev/null @@ -1,622 +0,0 @@ -'use strict'; - -const ReadPreference = require('mongodb-core').ReadPreference, - parser = require('url'), - f = require('util').format, - Logger = require('mongodb-core').Logger, - dns = require('dns'); - -module.exports = function(url, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - let result; - try { - result = parser.parse(url, true); - } catch (e) { - return callback(new Error('URL malformed, cannot be parsed')); - } - - if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { - return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); - } - - if (result.protocol === 'mongodb:') { - return parseHandler(url, options, callback); - } - - // Otherwise parse this as an SRV record - if (result.hostname.split('.').length < 3) { - return callback(new Error('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - - if (result.pathname && result.pathname.match(',')) { - return callback(new Error('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); - } - - let srvAddress = `_mongodb._tcp.${result.host}`; - dns.resolveSrv(srvAddress, function(err, addresses) { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new Error('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback(new Error('Server record does not share hostname with parent URI')); - } - } - - let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; - let connectionStrings = addresses.map(function(address, i) { - if (i === 0) return `${base}${address.name}:${address.port}`; - else return `${address.name}:${address.port}`; - }); - - let connectionString = connectionStrings.join(',') + '/'; - let connectionStringOptions = []; - - // Add the default database if needed - if (result.path) { - let defaultDb = result.path.slice(1); - if (defaultDb.indexOf('?') !== -1) { - defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); - } - - connectionString += defaultDb; - } - - // Default to SSL true - if (!options.ssl && !result.search) { - connectionStringOptions.push('ssl=true'); - } else if (!options.ssl && result.search && !result.search.match('ssl')) { - connectionStringOptions.push('ssl=true'); - } - - // Keep original uri options - if (result.search) { - connectionStringOptions.push(result.search.replace('?', '')); - } - - dns.resolveTxt(result.host, function(err, record) { - if (err && err.code !== 'ENODATA') return callback(err); - if (err && err.code === 'ENODATA') record = null; - - if (record) { - if (record.length > 1) { - return callback(new Error('Multiple text records not allowed')); - } - - record = record[0]; - if (record.length > 1) record = record.join(''); - else record = record[0]; - - if (!record.includes('authSource') && !record.includes('replicaSet')) { - return callback(new Error('Text record must only set `authSource` or `replicaSet`')); - } - - connectionStringOptions.push(record); - } - - // Add any options to the connection string - if (connectionStringOptions.length) { - connectionString += `?${connectionStringOptions.join('&')}`; - } - - parseHandler(connectionString, options, callback); - }); - }); -}; - -function matchesParentDomain(srvAddress, parentDomain) { - let regex = /^.*?\./; - let srv = `.${srvAddress.replace(regex, '')}`; - let parent = `.${parentDomain.replace(regex, '')}`; - if (srv.endsWith(parent)) return true; - else return false; -} - -function parseHandler(address, options, callback) { - let result, err; - try { - result = parseConnectionString(address, options); - } catch (e) { - err = e; - } - - return err ? callback(err, null) : callback(null, result); -} - -function parseConnectionString(url, options) { - // Variables - let connection_part = ''; - let auth_part = ''; - let query_string_part = ''; - let dbName = 'admin'; - - // Url parser result - let result = parser.parse(url, true); - if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { - throw new Error('No hostname or hostnames provided in connection string'); - } - - if (result.port === '0') { - throw new Error('Invalid port (zero) with hostname'); - } - - if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { - throw new Error('Invalid port (larger than 65535) with hostname'); - } - - if ( - result.path && - result.path.length > 0 && - result.path[0] !== '/' && - url.indexOf('.sock') === -1 - ) { - throw new Error('Missing delimiting slash between hosts and options'); - } - - if (result.query) { - for (let name in result.query) { - if (name.indexOf('::') !== -1) { - throw new Error('Double colon in host identifier'); - } - - if (result.query[name] === '') { - throw new Error('Query parameter ' + name + ' is an incomplete value pair'); - } - } - } - - if (result.auth) { - let parts = result.auth.split(':'); - if (url.indexOf(result.auth) !== -1 && parts.length > 2) { - throw new Error('Username with password containing an unescaped colon'); - } - - if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { - throw new Error('Username containing an unescaped at-sign'); - } - } - - // Remove query - let clean = url.split('?').shift(); - - // Extract the list of hosts - let strings = clean.split(','); - let hosts = []; - - for (let i = 0; i < strings.length; i++) { - let hostString = strings[i]; - - if (hostString.indexOf('mongodb') !== -1) { - if (hostString.indexOf('@') !== -1) { - hosts.push(hostString.split('@').pop()); - } else { - hosts.push(hostString.substr('mongodb://'.length)); - } - } else if (hostString.indexOf('/') !== -1) { - hosts.push(hostString.split('/').shift()); - } else if (hostString.indexOf('/') === -1) { - hosts.push(hostString.trim()); - } - } - - for (let i = 0; i < hosts.length; i++) { - let r = parser.parse(f('mongodb://%s', hosts[i].trim())); - if (r.path && r.path.indexOf('.sock') !== -1) continue; - if (r.path && r.path.indexOf(':') !== -1) { - // Not connecting to a socket so check for an extra slash in the hostname. - // Using String#split as perf is better than match. - if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { - throw new Error('Slash in host identifier'); - } else { - throw new Error('Double colon in host identifier'); - } - } - } - - // 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 there is not more than one unescaped slash - if (connection_part.split('/').length > 2) { - throw new Error( - "Unsupported host '" + - connection_part.split('?')[0] + - "', hosts must be URL encoded and contain at most one unencoded slash" - ); - } - - // 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]; - // Check if multiple database names provided, or just an illegal trailing backslash - if (dbName.indexOf('/') !== -1) { - if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - connection_part = connection_part.split( - '/', - connection_part.indexOf('.sock') + '.sock'.length - ); - } - } else if (connection_part.indexOf('/') !== -1) { - // Check if multiple database names provided, or just an illegal trailing backslash - if (connection_part.split('/').length > 2) { - if (connection_part.split('/')[2].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - dbName = connection_part.split('/')[1]; - connection_part = connection_part.split('/')[0]; - } - - // URI decode the host information - connection_part = decodeURIComponent(connection_part); - - // Result object - let object = {}; - - // Pick apart the authentication part of the string - let authPart = auth_part || ''; - let auth = authPart.split(':', 2); - - // Decode the authentication URI components and verify integrity - let user = decodeURIComponent(auth[0]); - if (auth[0] !== encodeURIComponent(user)) { - throw new Error('Username contains an illegal unescaped character'); - } - auth[0] = user; - - if (auth[1]) { - let pass = decodeURIComponent(auth[1]); - if (auth[1] !== encodeURIComponent(pass)) { - throw new Error('Password contains an illegal unescaped character'); - } - auth[1] = pass; - } - - // Add auth to final object if we have 2 elements - if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; - // if user provided auth options, use that - if (options && options.auth != null) object.auth = options.auth; - - // Variables used for temporary storage - let hostPart; - let urlOptions; - let servers; - let compression; - let serverOptions = { socketOptions: {} }; - let dbOptions = { read_preference_tags: [] }; - let replSetServersOptions = { socketOptions: {} }; - let mongosOptions = { socketOptions: {} }; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = mongosOptions; - - // Let's check if we are using a domain socket - if (url.match(/\.sock/)) { - // Split out the socket part - let 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]; - domainSocket = decodeURIComponent(domainSocket); - servers = [{ domain_socket: domainSocket }]; - } else { - // Split up the db - hostPart = connection_part; - // Deduplicate servers - let deduplicatedServers = {}; - - // Parse all server results - servers = hostPart - .split(',') - .map(function(h) { - let _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 - let 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]; - } - - // No entry returned for duplicate servr - if (deduplicatedServers[_host + '_' + _port]) return null; - deduplicatedServers[_host + '_' + _port] = 1; - - // Return the mapped object - return { host: _host, port: _port }; - }) - .filter(function(x) { - return x != null; - }); - } - - // 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 'appname': - object.appname = decodeURIComponent(value); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = value === 'true'; - break; - case 'ssl': - if (value === 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - mongosOptions.ssl = value; - break; - } - serverOptions.ssl = value === 'true'; - replSetServersOptions.ssl = value === 'true'; - mongosOptions.ssl = value === 'true'; - break; - case 'sslValidate': - serverOptions.sslValidate = value === 'true'; - replSetServersOptions.sslValidate = value === 'true'; - mongosOptions.sslValidate = 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 'readConcernLevel': - dbOptions.readConcern = { level: value }; - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - mongosOptions.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) { - let 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 !== 'DEFAULT' && - value !== 'SCRAM-SHA-1' && - value !== 'SCRAM-SHA-256' && - value !== 'PLAIN' - ) - throw new Error( - 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' - ); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'authMechanismProperties': - { - // Split up into key, value pairs - let values = value.split(','); - let o = {}; - // For each value split into key, value - values.forEach(function(x) { - let 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; - if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; - if (typeof o.CANONICALIZE_HOST_NAME === 'string') - dbOptions.gssapiCanonicalizeHostName = - o.CANONICALIZE_HOST_NAME === 'true' ? true : false; - } - 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.readPreference = value; - break; - case 'maxStalenessSeconds': - dbOptions.maxStalenessSeconds = parseInt(value, 10); - break; - case 'readPreferenceTags': - { - // Decode the value - value = decodeURIComponent(value); - // Contains the tag object - let tagObject = {}; - if (value == null || value === '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - let tags = value.split(/,/); - for (let i = 0; i < tags.length; i++) { - let parts = tags[i].trim().split(/:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - } - break; - case 'compressors': - { - compression = serverOptions.compression || {}; - let compressors = value.split(','); - if ( - !compressors.every(function(compressor) { - return compressor === 'snappy' || compressor === 'zlib'; - }) - ) { - throw new Error('Compressors must be at least one of snappy or zlib'); - } - - compression.compressors = compressors; - serverOptions.compression = compression; - } - break; - case 'zlibCompressionLevel': - { - compression = serverOptions.compression || {}; - let zlibCompressionLevel = parseInt(value, 10); - if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { - throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); - } - - compression.zlibCompressionLevel = zlibCompressionLevel; - serverOptions.compression = compression; - } - break; - case 'retryWrites': - dbOptions.retryWrites = value === 'true'; - break; - case 'minSize': - dbOptions.minSize = parseInt(value, 10); - break; - default: - { - let logger = Logger('URL Parser'); - logger.warn(`${name} is not supported as a connection string option`); - } - 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.readPreference) { - dbOptions.readPreference = 'primary'; - } - - // make sure that user-provided options are applied with priority - dbOptions = Object.assign(dbOptions, options); - - // Add servers to result - object.servers = servers; - - // Returned parsed object - return object; -} diff --git a/node_modules/mongodb/lib/utils.js b/node_modules/mongodb/lib/utils.js deleted file mode 100644 index 90e6b7fda39accb0c8ce2f118871dadda1d25f9b..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/lib/utils.js +++ /dev/null @@ -1,723 +0,0 @@ -'use strict'; - -const MongoError = require('mongodb-core').MongoError; -const ReadPreference = require('mongodb-core').ReadPreference; - -var shallowClone = function(obj) { - var copy = {}; - for (var name in obj) copy[name] = obj[name]; - return copy; -}; - -// Figure out the read preference -var translateReadPreference = function(options) { - var r = null; - if (options.readPreference) { - r = options.readPreference; - } else { - return options; - } - - if (typeof r === 'string') { - options.readPreference = new ReadPreference(r); - } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { - const mode = r.mode || r.preference; - if (mode && typeof mode === 'string') { - options.readPreference = new ReadPreference(mode, r.tags, { - maxStalenessSeconds: r.maxStalenessSeconds - }); - } - } else if (!(r instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + r); - } - - return options; -}; - -// 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 new MongoError('collection name must be a String'); - } - - if (!collectionName || collectionName.indexOf('..') !== -1) { - throw new MongoError('collection names cannot be empty'); - } - - if ( - collectionName.indexOf('$') !== -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null - ) { - throw new MongoError("collection names must not contain '$'"); - } - - if (collectionName.match(/^\.|\.$/) != null) { - throw new MongoError("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the colletion name - if (collectionName.indexOf('\x00') !== -1) { - throw new MongoError('collection names cannot contain a null character'); - } -}; - -var handleCallback = function(callback, err, value1, value2) { - try { - if (callback == null) return; - - if (callback) { - return value2 ? callback(err, value1, value2) : 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 = MongoError.create({ message: msg, driver: true }); - - // Get all object keys - var keys = typeof error === 'object' ? Object.keys(error) : []; - - for (var i = 0; i < keys.length; i++) { - try { - e[keys[i]] = error[keys[i]]; - } catch (err) { - // continue - } - } - - 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]' === Object.prototype.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.indexOf(name) === -1) command[name] = options[name]; - } - - return command; -}; - -var mergeOptions = function(target, source) { - for (var name in source) { - target[name] = source[name]; - } - - return target; -}; - -// Merge options with translation -var translateOptions = function(target, source) { - var translations = { - // SSL translation options - sslCA: 'ca', - sslCRL: 'crl', - sslValidate: 'rejectUnauthorized', - sslKey: 'key', - sslCert: 'cert', - sslPass: 'passphrase', - // SocketTimeout translation options - socketTimeoutMS: 'socketTimeout', - connectTimeoutMS: 'connectionTimeout', - // Replicaset options - replicaSet: 'setName', - rs_name: 'setName', - secondaryAcceptableLatencyMS: 'acceptableLatency', - connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', - // Mongos options - acceptableLatencyMS: 'localThresholdMS' - }; - - for (var name in source) { - if (translations[name]) { - target[translations[name]] = source[name]; - } else { - target[name] = source[name]; - } - } - - return target; -}; - -var filterOptions = function(options, names) { - var filterOptions = {}; - - for (var name in options) { - if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; - } - - // Filtered options - return filterOptions; -}; - -// Write concern keys -var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; - -// Merge the write concern options -var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { - // Mix in any allowed options - for (var i = 0; i < keys.length; i++) { - if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { - targetOptions[keys[i]] = sourceOptions[keys[i]]; - } - } - - // No merging of write concern - if (!mergeWriteConcern) return targetOptions; - - // Found no write Concern options - var found = false; - for (i = 0; i < writeConcernKeys.length; i++) { - if (targetOptions[writeConcernKeys[i]]) { - found = true; - break; - } - } - - if (!found) { - for (i = 0; i < writeConcernKeys.length; i++) { - if (sourceOptions[writeConcernKeys[i]]) { - targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; - } - } - } - - return targetOptions; -}; - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {function} operation The operation to execute - * @param {array} args Arguments to apply the provided operation - * @param {object} [options] Options that modify the behavior of the method - * @param {function]} [options.resultMutator] Allows for the result of the operation to be changed for custom return types - */ -const executeOperation = (topology, operation, args, options) => { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!Array.isArray(args)) { - throw new TypeError('This method requires an array of arguments to apply'); - } - - options = options || {}; - const Promise = topology.s.promiseLibrary; - let resultMutator = options.resultMutator; - let callback = args[args.length - 1]; - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, opOptions, owner; - if (!options.skipSessions && topology.hasSessionSupport()) { - opOptions = args[args.length - 2]; - if (opOptions == null || opOptions.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - const optionsIndex = args.length - 2; - args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); - } else if (opOptions.session && opOptions.session.hasEnded) { - throw new MongoError('Use of expired sessions is not permitted'); - } - } - - const makeExecuteCallback = (resolve, reject) => - function executeCallback(err, result) { - if (session && session.owner === owner && !options.returnsCursor) { - session.endSession(() => { - delete opOptions.session; - if (err) return reject(err); - if (resultMutator) return resolve(resultMutator(result)); - resolve(result); - }); - } else { - if (err) return reject(err); - if (resultMutator) return resolve(resultMutator(result)); - resolve(result); - } - }; - - // Execute using callback - if (typeof callback === 'function') { - callback = args.pop(); - const handler = makeExecuteCallback( - result => callback(null, result), - err => callback(err, null) - ); - args.push(handler); - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - throw e; - } - } - - // Return a Promise - if (args[args.length - 1] != null) { - throw new TypeError('final argument to `executeOperation` must be a callback'); - } - - return new Promise(function(resolve, reject) { - const handler = makeExecuteCallback(resolve, reject); - args[args.length - 1] = handler; - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - } - }); -}; - -/** - * Applies retryWrites: true to a command if retryWrites is set on the command's database. - * - * @param {object} target The target command to which we will apply retryWrites. - * @param {object} db The database from which we can inherit a retryWrites value. - */ -function applyRetryableWrites(target, db) { - if (db && db.s.options.retryWrites) { - target.retryWrites = true; - } - - return target; -} - -/** - * Applies a write concern to a command based on well defined inheritance rules, optionally - * detecting support for the write concern in the first place. - * - * @param {Object} target the target command we will be applying the write concern to - * @param {Object} sources sources where we can inherit default write concerns from - * @param {Object} [options] optional settings passed into a command for write concern overrides - * @returns {Object} the (now) decorated target - */ -function applyWriteConcern(target, sources, options) { - options = options || {}; - const db = sources.db; - const coll = sources.collection; - - if (options.session && options.session.inTransaction()) { - // writeConcern is not allowed within a multi-statement transaction - if (target.writeConcern) { - delete target.writeConcern; - } - - return target; - } - - if (options.w != null || options.j != null || options.fsync != null) { - const writeConcern = {}; - if (options.w != null) writeConcern.w = options.w; - if (options.wtimeout != null) writeConcern.wtimeout = options.wtimeout; - if (options.j != null) writeConcern.j = options.j; - if (options.fsync != null) writeConcern.fsync = options.fsync; - return Object.assign(target, { writeConcern }); - } - - if ( - coll && - (coll.writeConcern.w != null || coll.writeConcern.j != null || coll.writeConcern.fsync != null) - ) { - return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); - } - - if ( - db && - (db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) - ) { - return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); - } - - return target; -} - -/** - * Resolves a read preference based on well-defined inheritance rules. This method will not only - * determine the read preference (if there is one), but will also ensure the returned value is a - * properly constructed instance of `ReadPreference`. - * - * @param {Object} options The options passed into the method, potentially containing a read preference - * @param {Object} sources Sources from which we can inherit a read preference - * @returns {(ReadPreference|null)} The resolved read preference - */ -function resolveReadPreference(options, sources) { - options = options || {}; - sources = sources || {}; - - const db = sources.db; - const coll = sources.collection; - const defaultReadPreference = sources.default; - const session = options.session; - - let readPreference; - if (options.readPreference) { - readPreference = options.readPreference; - } else if (session && session.inTransaction() && session.transaction.options.readPreference) { - // The transaction’s read preference MUST override all other user configurable read preferences. - readPreference = session.transaction.options.readPreference; - } else { - if (coll && coll.s.readPreference) { - readPreference = coll.s.readPreference; - } else if (db && db.s.readPreference) { - readPreference = db.s.readPreference; - } else if (defaultReadPreference) { - readPreference = defaultReadPreference; - } - } - - // do we even have a read preference? - if (readPreference == null) { - return null; - } - - // now attempt to convert the read preference if necessary - if (typeof readPreference === 'string') { - readPreference = new ReadPreference(readPreference); - } else if ( - readPreference && - !(readPreference instanceof ReadPreference) && - typeof readPreference === 'object' - ) { - const mode = readPreference.mode || readPreference.preference; - if (mode && typeof mode === 'string') { - readPreference = new ReadPreference(mode, readPreference.tags, { - maxStalenessSeconds: readPreference.maxStalenessSeconds - }); - } - } else if (!(readPreference instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return readPreference; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies collation to a given command. - * - * @param {object} [command] the command on which to apply collation - * @param {(Cursor|Collection)} [target] target of command - * @param {object} [options] options containing collation settings - */ -function decorateWithCollation(command, target, options) { - const topology = target.s && target.s.topology; - - if (!topology) { - throw new TypeError('parameter "target" is missing a topology'); - } - - const capabilities = target.s.topology.capabilities(); - if (options.collation && typeof options.collation === 'object') { - if (capabilities && capabilities.commandsTakeCollation) { - command.collation = options.collation; - } else { - throw new MongoError(`server ${topology.s.coreTopology.name} does not support collation`); - } - } -} - -/** - * Applies a read concern to a given command. - * - * @param {object} command the command on which to apply the read concern - * @param {Collection} coll the parent collection of the operation calling this method - */ -function decorateWithReadConcern(command, coll, options) { - if (options && options.session && options.session.inTransaction()) { - return; - } - let readConcern = Object.assign({}, command.readConcern || {}); - if (coll.s.readConcern) { - Object.assign(readConcern, coll.s.readConcern); - } - - if (Object.keys(readConcern).length > 0) { - Object.assign(command, { readConcern: readConcern }); - } -} - -const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning'); -const emitConsoleWarning = msg => console.error(msg); -const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; - -/** - * Default message handler for generating deprecation warnings. - * - * @param {string} name function name - * @param {string} option option name - * @return {string} warning message - * @ignore - * @api private - */ -function defaultMsgHandler(name, option) { - return `${name} option [${option}] is deprecated and will be removed in a later version.`; -} - -/** - * Deprecates a given function's options. - * - * @param {object} config configuration for deprecation - * @param {string} config.name function name - * @param {Array} config.deprecatedOptions options to deprecate - * @param {number} config.optionsIndex index of options object in function arguments array - * @param {function} [config.msgHandler] optional custom message handler to generate warnings - * @param {function} fn the target function of deprecation - * @return {function} modified function that warns once per deprecated option, and executes original function - * @ignore - * @api private - */ -function deprecateOptions(config, fn) { - if (process.noDeprecation === true) { - return fn; - } - - const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; - - const optionsWarned = new Set(); - function deprecated() { - const options = arguments[config.optionsIndex]; - - // ensure options is a valid, non-empty object, otherwise short-circuit - if (!isObject(options) || Object.keys(options).length === 0) { - return fn.apply(this, arguments); - } - - config.deprecatedOptions.forEach(deprecatedOption => { - if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { - optionsWarned.add(deprecatedOption); - const msg = msgHandler(config.name, deprecatedOption); - emitDeprecationWarning(msg); - if (this && this.getLogger) { - const logger = this.getLogger(); - if (logger) { - logger.warn(msg); - } - } - } - }); - - return fn.apply(this, arguments); - } - - // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 - // The wrapper will keep the same prototype as fn to maintain prototype chain - Object.setPrototypeOf(deprecated, fn); - if (fn.prototype) { - // Setting this (rather than using Object.setPrototype, as above) ensures - // that calling the unwrapped constructor gives an instanceof the wrapped - // constructor. - deprecated.prototype = fn.prototype; - } - - return deprecated; -} - -module.exports = { - filterOptions, - mergeOptions, - translateOptions, - shallowClone, - getSingleProperty, - checkCollectionName, - toError, - formattedOrderClause, - parseIndexOptions, - normalizeHintField, - handleCallback, - decorateCommand, - isObject, - debugOptions, - MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, - mergeOptionsAndWriteConcern, - translateReadPreference, - executeOperation, - applyRetryableWrites, - applyWriteConcern, - resolveReadPreference, - isPromiseLike, - decorateWithCollation, - decorateWithReadConcern, - deprecateOptions -}; diff --git a/node_modules/mongodb/package.json b/node_modules/mongodb/package.json deleted file mode 100644 index df5096030c80daa1ab9123cc8c206bd12c2f6123..0000000000000000000000000000000000000000 --- a/node_modules/mongodb/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "_from": "mongodb@3.1.13", - "_id": "mongodb@3.1.13", - "_inBundle": false, - "_integrity": "sha512-sz2dhvBZQWf3LRNDhbd30KHVzdjZx9IKC0L+kSZ/gzYquCF5zPOgGqRz6sSCqYZtKP2ekB4nfLxhGtzGHnIKxA==", - "_location": "/mongodb", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mongodb@3.1.13", - "name": "mongodb", - "escapedName": "mongodb", - "rawSpec": "3.1.13", - "saveSpec": null, - "fetchSpec": "3.1.13" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.13.tgz", - "_shasum": "f8cdcbb36ad7a08b570bd1271c8525753f75f9f4", - "_spec": "mongodb@3.1.13", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongoose", - "bugs": { - "url": "https://github.com/mongodb/node-mongodb-native/issues" - }, - "bundleDependencies": false, - "dependencies": { - "mongodb-core": "3.1.11", - "safe-buffer": "^5.1.2" - }, - "deprecated": false, - "description": "The official MongoDB driver for Node.js", - "devDependencies": { - "bluebird": "3.5.0", - "bson": "^1.0.4", - "chai": "^4.1.1", - "chai-subset": "^1.6.0", - "co": "4.6.0", - "coveralls": "^2.11.6", - "eslint": "^4.5.0", - "eslint-plugin-prettier": "^2.2.0", - "istanbul": "^0.4.5", - "jsdoc": "3.5.5", - "lodash.camelcase": "^4.3.0", - "mocha-sinon": "^2.1.0", - "mongodb-extjson": "^2.1.1", - "mongodb-mock-server": "^1.0.0", - "mongodb-test-runner": "^1.1.18", - "prettier": "~1.12.0", - "semver": "^5.5.0", - "sinon": "^4.3.0", - "sinon-chai": "^3.2.0", - "standard-version": "^4.4.0", - "worker-farm": "^1.5.0" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js", - "lib" - ], - "homepage": "https://github.com/mongodb/node-mongodb-native", - "keywords": [ - "mongodb", - "driver", - "official" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "mongodb", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" - }, - "scripts": { - "bench": "node test/driverBench/", - "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/unit test/functional", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", - "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js", - "lint": "eslint lib test", - "release": "standard-version -i HISTORY.md", - "test": "npm run lint && mongodb-test-runner -t 60000 test/unit test/functional" - }, - "version": "3.1.13" -} diff --git a/node_modules/mongoose-legacy-pluralize/LICENSE b/node_modules/mongoose-legacy-pluralize/LICENSE deleted file mode 100644 index 261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64..0000000000000000000000000000000000000000 --- a/node_modules/mongoose-legacy-pluralize/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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-legacy-pluralize/README.md b/node_modules/mongoose-legacy-pluralize/README.md deleted file mode 100644 index 3296efb8b49709c2795870e449724a5122aba2ef..0000000000000000000000000000000000000000 --- a/node_modules/mongoose-legacy-pluralize/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# mongoose-legacy-pluralize -Legacy pluralization logic for mongoose diff --git a/node_modules/mongoose-legacy-pluralize/index.js b/node_modules/mongoose-legacy-pluralize/index.js deleted file mode 100644 index 1dd451d778d96fd1ef4b6afde79584e6ef338549..0000000000000000000000000000000000000000 --- a/node_modules/mongoose-legacy-pluralize/index.js +++ /dev/null @@ -1,95 +0,0 @@ -module.exports = pluralize; - -/** - * Pluralization rules. - * - * These rules are applied while processing the argument to `toCollectionName`. - * - * @deprecated remove in 4.x gh-1350 - */ - -exports.pluralization = [ - [/(m)an$/gi, '$1en'], - [/(pe)rson$/gi, '$1ople'], - [/(child)$/gi, '$1ren'], - [/^(ox)$/gi, '$1en'], - [/(ax|test)is$/gi, '$1es'], - [/(octop|vir)us$/gi, '$1i'], - [/(alias|status)$/gi, '$1es'], - [/(bu)s$/gi, '$1ses'], - [/(buffal|tomat|potat)o$/gi, '$1oes'], - [/([ti])um$/gi, '$1a'], - [/sis$/gi, 'ses'], - [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'], - [/(hive)$/gi, '$1s'], - [/([^aeiouy]|qu)y$/gi, '$1ies'], - [/(x|ch|ss|sh)$/gi, '$1es'], - [/(matr|vert|ind)ix|ex$/gi, '$1ices'], - [/([m|l])ouse$/gi, '$1ice'], - [/(kn|w|l)ife$/gi, '$1ives'], - [/(quiz)$/gi, '$1zes'], - [/s$/gi, 's'], - [/([^a-z])$/, '$1'], - [/$/gi, 's'] -]; -var rules = exports.pluralization; - -/** - * Uncountable words. - * - * These words are applied while processing the argument to `toCollectionName`. - * @api public - */ - -exports.uncountables = [ - 'advice', - 'energy', - 'excretion', - 'digestion', - 'cooperation', - 'health', - 'justice', - 'labour', - 'machinery', - 'equipment', - 'information', - 'pollution', - 'sewage', - 'paper', - 'money', - 'species', - 'series', - 'rain', - 'rice', - 'fish', - 'sheep', - 'moose', - 'deer', - 'news', - 'expertise', - 'status', - 'media' -]; -var uncountables = exports.uncountables; - -/*! - * Pluralize function. - * - * @author TJ Holowaychuk (extracted from _ext.js_) - * @param {String} string to pluralize - * @api private - */ - -function pluralize(str) { - var found; - str = str.toLowerCase(); - if (!~uncountables.indexOf(str)) { - found = rules.filter(function(rule) { - return str.match(rule[0]); - }); - if (found[0]) { - return str.replace(found[0][0], found[0][1]); - } - } - return str; -} diff --git a/node_modules/mongoose-legacy-pluralize/package.json b/node_modules/mongoose-legacy-pluralize/package.json deleted file mode 100644 index 0fe4b23742a46d7885b48da0c3aee18478563a9c..0000000000000000000000000000000000000000 --- a/node_modules/mongoose-legacy-pluralize/package.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "_from": "mongoose-legacy-pluralize@1.0.2", - "_id": "mongoose-legacy-pluralize@1.0.2", - "_inBundle": false, - "_integrity": "sha512-Yo/7qQU4/EyIS8YDFSeenIvXxZN+ld7YdV9LqFVQJzTLye8unujAWPZ4NWKfFA+RNjh+wvTWKY9Z3E5XM6ZZiQ==", - "_location": "/mongoose-legacy-pluralize", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mongoose-legacy-pluralize@1.0.2", - "name": "mongoose-legacy-pluralize", - "escapedName": "mongoose-legacy-pluralize", - "rawSpec": "1.0.2", - "saveSpec": null, - "fetchSpec": "1.0.2" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/mongoose-legacy-pluralize/-/mongoose-legacy-pluralize-1.0.2.tgz", - "_shasum": "3ba9f91fa507b5186d399fb40854bff18fb563e4", - "_spec": "mongoose-legacy-pluralize@1.0.2", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongoose", - "author": { - "name": "Valeri Karpov", - "email": "val@karpov.io" - }, - "bugs": { - "url": "https://github.com/vkarpov15/mongoose-legacy-pluralize/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Legacy pluralization logic for mongoose", - "homepage": "https://github.com/vkarpov15/mongoose-legacy-pluralize", - "keywords": [ - "mongoose", - "mongodb" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "mongoose-legacy-pluralize", - "peerDependencies": { - "mongoose": "*" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/vkarpov15/mongoose-legacy-pluralize.git" - }, - "version": "1.0.2" -} diff --git a/node_modules/mongoose/.travis.yml b/node_modules/mongoose/.travis.yml deleted file mode 100644 index d1529aa1d2d6d68329303ef9bcff51e0dc2ef8d9..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -language: node_js -sudo: false -node_js: [10, 9, 8, 7, 6, 5, 4] -install: - - travis_retry npm install -before_script: - - wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.6.6.tgz - - tar -zxvf mongodb-linux-x86_64-3.6.6.tgz - - mkdir -p ./data/db/27017 - - mkdir -p ./data/db/27000 - - printf "\n--timeout 8000" >> ./test/mocha.opts - - ./mongodb-linux-x86_64-3.6.6/bin/mongod --fork --dbpath ./data/db/27017 --syslog --port 27017 - - sleep 2 -matrix: - include: - - name: "👕Linter" - node_js: 10 - before_script: skip - script: npm run lint -notifications: - email: false diff --git a/node_modules/mongoose/History.md b/node_modules/mongoose/History.md deleted file mode 100644 index f63b88f7a0149d279377ef212d05b375819c810f..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/History.md +++ /dev/null @@ -1,4909 +0,0 @@ -5.4.12 / 2019-02-13 -=================== - * fix(connection): dont emit reconnected due to socketTimeoutMS #7452 - * fix(schema): revert check for `false` schema paths #7516 #7512 - * fix(model): don't delete unaliased keys in translateAliases #7510 [chrischen](https://github.com/chrischen) - * fix(document): run single nested schematype validator if nested path has a default and subpath is modified #7493 - * fix(query): copy mongoose options when using `Query#merge()` #1790 - * fix(timestamps): don't call createdAt getters when setting updatedAt on new doc #7496 - * docs: improve description of ValidationError #7515 [JulioJu](https://github.com/JulioJu) - * docs: add an asterisk before comment, otherwise the comment line is not generated #7513 [JulioJu](https://github.com/JulioJu) - -5.4.11 / 2019-02-09 -=================== - * fix(schema): handle `_id: false` in schema paths as a shortcut for setting the `_id` option to `false` #7480 - * fix(update): handle $addToSet and $push with ObjectIds and castNonArrays=false #7479 - * docs(model): document `session` option to `save()` #7484 - * chore: fix gitignore syntax #7498 [JulioJu](https://github.com/JulioJu) - * docs: document that Document#validateSync returns ValidationError #7499 - * refactor: use consolidated `isPOJO()` function instead of constructor checks #7500 - -5.4.10 / 2019-02-05 -=================== - * docs: add search bar and /search page #6706 - * fix: support dotted aliases #7478 [chrischen](https://github.com/chrischen) - * fix(document): copy atomics when setting document array to an existing document array #7472 - * chore: upgrade to mongodb driver 3.1.13 #7488 - * docs: remove confusing references to executing a query "immediately" #7461 - * docs(guides+schematypes): link to custom schematypes docs #7407 - -5.4.9 / 2019-02-01 -================== - * fix(document): make `remove()`, `updateOne()`, and `update()` use the document's associated session #7455 - * fix(document): support passing args to hooked custom methods #7456 - * fix(document): avoid double calling single nested getters on `toObject()` #7442 - * fix(discriminator): handle global plugins modifying top-level discriminator options with applyPluginsToDiscriminators: true #7458 - * docs(documents): improve explanation of documents and use more modern syntax #7463 - * docs(middleware+api): fix a couple typos in examples #7474 [arniu](https://github.com/arniu) - -5.4.8 / 2019-01-30 -================== - * fix(query): fix unhandled error when casting object in array filters #7431 - * fix(query): cast query $elemMatch to discriminator schema if discriminator key set #7449 - * docs: add table of contents to all guides #7430 - -5.4.7 / 2019-01-26 -================== - * fix(populate): set `populated()` when using virtual populate #7440 - * fix(discriminator): defer applying plugins to embedded discriminators until model compilation so global plugins work #7435 - * fix(schema): report correct pathtype underneath map so setting dotted paths underneath maps works #7448 - * fix: get debug from options using the get helper #7451 #7446 [LucGranato](https://github.com/LucGranato) - * fix: use correct variable name #7443 [esben-semmle](https://github.com/esben-semmle) - * docs: fix broken QueryCursor link #7438 [shihabmridha](https://github.com/shihabmridha) - -5.4.6 / 2019-01-22 -================== - * fix(utils): make minimize leave empty objects in arrays instead of setting the array element to undefined #7322 - * fix(document): support passing `{document, query}` options to Schema#pre(regex) and Schema#post(regex) #7423 - * docs: add migrating to 5 guide to docs #7434 - * docs(deprecations): add instructions for fixing `count()` deprecation #7419 - * docs(middleware): add description and example for aggregate hooks #7402 - -4.13.18 / 2019-01-21 -==================== - * fix(model): handle setting populated path set via `Document#populate()` #7302 - * fix(cast): backport fix from #7290 to 4.x - -5.4.5 / 2019-01-18 -================== - * fix(populate): handle nested array `foreignField` with virtual populate #7374 - * fix(query): support not passing any arguments to `orFail()` #7409 - * docs(query): document what the resolved value for `deleteOne()`, `deleteMany()`, and `remove()` contains #7324 - * fix(array): allow opting out of converting non-arrays into arrays with `castNonArrays` option #7371 - * fix(query): ensure updateOne() doesnt unintentionally double call Schema#post(regexp) #7418 - -5.4.4 / 2019-01-14 -================== - * fix(query): run casting on arrayFilters option #7079 - * fix(document): support skipping timestamps on save() with `save({ timestamps: false })` #7357 - * fix(model): apply custom where on `Document#remove()` so we attach the shardKey #7393 - * docs(mongoose): document `mongoose.connections` #7338 - -5.4.3 / 2019-01-09 -================== - * fix(populate): handle `count` option when using `Document#populate()` on a virtual #7380 - * fix(connection): set connection state to DISCONNECTED if replica set has no primary #7330 - * fix(mongoose): apply global plugins to schemas nested underneath embedded discriminators #7370 - * fix(document): make modifiedPaths() return nested paths 1 level down on initial set #7313 - * fix(plugins): ensure sharding plugin works even if ObjectId has a `valueOf()` #7353 - -5.4.2 / 2019-01-03 -================== - * fix(document): ensure Document#updateOne() returns a query but still calls hooks #7366 - * fix(query): allow explicitly projecting out populated paths that are automatically projected in #7383 - * fix(document): support setting `flattenMaps` option for `toObject()` and `toJSON()` at schema level #7274 - * fix(query): handle merging objectids with `.where()` #7360 - * fix(schema): copy `.base` when cloning #7377 - * docs: remove links to plugins.mongoosejs.com in favor of plugins.mongoosejs.io #7364 - -5.4.1 / 2018-12-26 -================== - * fix(document): ensure doc array defaults get casted #7337 - * fix(document): make `save()` not crash if nested doc has a property 'get' #7316 - * fix(schema): allow using Schema.Types.Map as well as Map to declare a map type #7305 - * fix(map): make set after init mark correct path as modified #7321 - * fix(mongoose): don't recompile model if same collection and schema passed in to `mongoose.model()` #5767 - * fix(schema): improve error message when type is invalid #7303 - * fix(schema): add `populated` to reserved property names #7317 - * fix(model): don't run built-in middleware on custom methods and ensure timestamp hooks don't run if children don't have timestamps set #7342 - * docs(schematypes): clarify that you can add arbitrary options to a SchemaType #7340 - * docs(mongoose): clarify that passing same name+schema to `mongoose.model()` returns the model #5767 - * docs(index): add useNewUrlParser to example #7368 [JIBIN-P](https://github.com/JIBIN-P) - * docs(connection): add useNewUrlParser to examples #7362 [JIBIN-P](https://github.com/JIBIN-P) - * docs(discriminators): add back missing example from 'recursive embedded discriminators section' #7349 - * docs(schema): improve docs for string and boolean cast() #7351 - -5.4.0 / 2018-12-14 -================== - * feat(schematype): add `SchemaType.get()`, custom getters across all instances of a schematype #6912 - * feat(schematype): add `SchemaType.cast()`, configure casting for individual schematypes #7045 - * feat(schematype): add `SchemaType.checkRequired()`, configure what values pass `required` check for a schematype #7186 #7150 - * feat(model): add `Model.findOneAndReplace()` #7162 - * feat(model): add `Model.events` emitter that emits all `error`'s that occur with a given model #7125 - * feat(populate): add `count` option to populate virtuals, support returning # of populated docs instead of docs themselves #4469 - * feat(aggregate): add `.catch()` helper to make aggregations full thenables #7267 - * feat(query): add hooks for `deleteOne()` and `deleteMany()` #7195 - * feat(document): add hooks for `updateOne()` #7133 - * feat(query): add `Query#map()` for synchronously transforming results before post middleware runs #7142 - * feat(schema): support passing an array of objects or schemas to `Schema` constructor #7218 - * feat(populate): add `clone` option to ensure multiple docs don't share the same populated doc #3258 - * feat(query): add `Query#maxTimeMS()` helper #7254 - * fix(query): deprecate broken `Aggregate#addCursorFlag()` #7120 - * docs(populate): fix incorrect example #7335 [zcfan](https://github.com/zcfan) - * docs(middleware): add `findOneAndDelete` to middleware list #7327 [danielkesselberg](https://github.com/danielkesselberg) - -5.3.16 / 2018-12-11 -=================== - * fix(document): handle `__proto__` in queries #7290 - * fix(document): use Array.isArray() instead of checking constructor name for arrays #7290 - * docs(populate): add section about what happens when no document matches #7279 - * fix(mongoose): avoid crash on `import mongoose, {Schema} from 'mongoose'` #5648 - -5.3.15 / 2018-12-05 -=================== - * fix(query): handle `orFail()` with `findOneAndUpdate()` and `findOneAndDelete()` #7297 #7280 - * fix(document): make `save()` succeed if strict: false with a `collection` property #7276 - * fix(document): add `flattenMaps` option for toObject() #7274 - * docs(document): document flattenMaps option #7274 - * fix(populate): support populating individual subdoc path in document array #7273 - * fix(populate): ensure `model` option overrides `refPath` #7273 - * fix(map): don't call subdoc setters on init #7272 - * fix(document): use internal get() helper instead of lodash.get to support `null` projection param #7271 - * fix(document): continue running validateSync() for all elements in doc array after first error #6746 - -5.3.14 / 2018-11-27 -=================== - * docs(api): use `openUri()` instead of legacy `open()` #7277 [artemjackson](https://github.com/artemjackson) - * fix(document): don't mark date underneath single nested as modified if setting to string #7264 - * fix(update): set timestamps on subdocs if not using $set with no overwrite #7261 - * fix(document): use symbol instead of `__parent` so user code doesn't conflict #7230 - * fix(mongoose): allow using `mongoose.model()` without context, like `import {model} from 'mongoose'` #3768 - -5.3.13 / 2018-11-20 -=================== - * fix: bump mongodb driver -> 3.1.10 #7266 - * fix(populate): support setting a model as a `ref` #7253 - * docs(schematype): add ref() function to document what is a valid `ref` path in a schematype #7253 - * fix(array): clean modified subpaths when calling `splice()` #7249 - * docs(compatibility): don't show Mongoose 4.11 as compatible with MongoDB 3.6 re: MongoDB's official compatibility table #7248 [a-harrison](https://github.com/a-harrison) - * fix(document): report correct validation error if doc array set to primitive #7242 - * fix(mongoose): print warning when including server-side lib with jest jsdom environment #7240 - -5.3.12 / 2018-11-13 -=================== - * docs(compatibility): don't show Mongoose 4.11 as compatible with MongoDB 3.6 re: MongoDB's official compatibility table #7238 [a-harrison](https://github.com/a-harrison) - * fix(populate): use `instanceof` rather than class name for comparison #7237 [ivanseidel](https://github.com/ivanseidel) - * docs(api): make options show up as a nested list #7232 - * fix(document): don't mark array as modified on init if doc array has default #7227 - * docs(api): link to bulk write result object in `bulkWrite()` docs #7225 - -5.3.11 / 2018-11-09 -=================== - * fix(model): make parent pointers non-enumerable so they don't crash JSON.stringify() #7220 - * fix(document): allow saving docs with nested props with '.' using `checkKeys: false` #7144 - * docs(lambda): use async/await with lambda example #7019 - -5.3.10 / 2018-11-06 -=================== - * fix(discriminator): support reusing a schema for multiple discriminators #7200 - * fix(cursor): handle `lean(false)` correctly with query cursors #7197 - * fix(document): avoid manual populate if `ref` not set #7193 - * fix(schema): handle schema without `.base` for browser build #7170 - * docs: add further reading section - -5.3.9 / 2018-11-02 -================== - * fix: upgrade bson dep -> 1.1.0 to match mongodb-core #7213 [NewEraCracker](https://github.com/NewEraCracker) - * docs(api): fix broken anchor link #7210 [gfranco93](https://github.com/gfranco93) - * fix: don't set parent timestamps because a child has timestamps set to false #7203 #7202 [lineus](https://github.com/lineus) - * fix(document): run setter only once when doing `.set()` underneath a single nested subdoc #7196 - * fix(document): surface errors in subdoc pre validate #7187 - * fix(query): run default functions after hydrating the loaded document #7182 - * fix(query): handle strictQuery: 'throw' with nested path correctly #7178 - * fix(update): update timestamps on replaceOne() #7152 - * docs(transactions): add example of aborting a transaction #7113 - -5.3.8 / 2018-10-30 -================== - * fix: bump mongodb driver -> 3.1.8 to fix connecting to +srv uri with no credentials #7191 #6881 [lineus](https://github.com/lineus) - * fix(document): sets defaults correctly in child docs with projection #7159 - * fix(mongoose): handle setting custom type on a separate mongoose global #7158 - * fix: add unnecessary files to npmignore #7157 - * fix(model): set session when creating new subdoc #7104 - -5.3.7 / 2018-10-26 -================== - * fix(browser): fix buffer usage in browser build #7184 #7173 [lineus](https://github.com/lineus) - * fix(document): make depopulate() work on populate virtuals and unpopulated docs #7180 #6075 [lineus](https://github.com/lineus) - * fix(document): only pass properties as 2nd arg to custom validator if `propsParameter` set #7145 - * docs(schematypes): add note about nested paths with `type` getting converted to mixed #7143 - * fix(update): run update validators on nested doc when $set on an array #7135 - * fix(update): copy exact errors from array subdoc validation into top-level update validator error #7135 - -5.3.6 / 2018-10-23 -================== - * fix(cursor): fix undefined transforms error - -5.3.5 / 2018-10-22 -================== - * fix(model): make sure versionKey on `replaceOne()` always gets set at top level to prevent cast errors #7138 - * fix(cursor): handle non-boolean lean option in `eachAsync()` #7137 - * fix(update): correct cast update that overwrites a map #7111 - * fix(schema): handle arrays of mixed correctly #7109 - * fix(query): use correct path when getting schema for child timestamp update #7106 - * fix(document): make `$session()` propagate sessions to child docs #7104 - * fix(document): handle user setting `schema.options.strict = 'throw'` #7103 - * fix(types): use core Node.js buffer prototype instead of safe-buffer because safe-buffer is broken for Node.js 4.x #7102 - * fix(document): handle setting single doc with refPath to document #7070 - * fix(model): handle array filters when updating timestamps for subdocs #7032 - -5.3.4 / 2018-10-15 -================== - * fix(schema): make `add()` and `remove()` return the schema instance #7131 [lineus](https://github.com/lineus) - * fix(query): don't require passing model to `cast()` #7118 - * fix: support `useFindAndModify` as a connection-level option #7110 [lineus](https://github.com/lineus) - * fix(populate): handle plus path projection with virtual populate #7050 - * fix(schema): allow using ObjectId type as schema path type #7049 - * docs(schematypes): elaborate on how schematypes relate to types #7049 - * docs(deprecations): add note about gridstore deprecation #6922 - * docs(guide): add storeSubdocValidationError option to guide #6802 - -5.3.3 / 2018-10-12 -================== - * fix(document): enable storing mongoose validation error in MongoDB by removing `$isValidatorError` property #7127 - * docs(api): clarify that aggregate triggers aggregate middleware #7126 [lineus](https://github.com/lineus) - * fix(connection): handle Model.init() when an index exists on schema + autoCreate == true #7122 [jesstelford](https://github.com/jesstelford) - * docs(middleware): explain how to switch between document and query hooks for `remove()` #7093 - * docs(api): clean up encoding issues in SchemaType.prototype.validate docs #7091 - * docs(schema): add schema types to api docs and update links on schematypes page #7080 #7076 [lineus](https://github.com/lineus) - * docs(model): expand model constructor docs with examples and `fields` param #7077 - * docs(aggregate): remove incorrect description of noCursorTimeout and add description of aggregate options #7056 - * docs: re-add array type to API docs #7027 - * docs(connections): add note about `members.host` errors due to bad host names in replica set #7006 - -5.3.2 / 2018-10-07 -================== - * fix(query): make sure to return correct result from `orFail()` #7101 #7099 [gsandorx](https://github.com/gsandorx) - * fix(schema): handle `{ timestamps: false }` correctly #7088 #7074 [lineus](https://github.com/lineus) - * docs: fix markdown in options.useCreateIndex documentation #7085 [Cyral](https://github.com/Cyral) - * docs(schema): correct field name in timestamps example #7082 [kizmo04](https://github.com/kizmo04) - * docs(migrating_to_5): correct markdown syntax #7078 [gwuah](https://github.com/gwuah) - * fix(connection): add useFindAndModify option in connect #7059 [NormanPerrin](https://github.com/NormanPerrin) - * fix(document): dont mark single nested path as modified if setting to the same value #7048 - * fix(populate): use WeakMap to track lean populate models rather than leanPopulateSymbol #7026 - * fix(mongoose): avoid unhandled rejection when `mongoose.connect()` errors with a callback #6997 - * fix(mongoose): isolate Schema.Types between custom Mongoose instances #6933 - -5.3.1 / 2018-10-02 -================== - * fix(ChangeStream): expose driver's `close()` function #7068 #7022 [lineus](https://github.com/lineus) - * fix(model): avoid printing warning if `_id` index is set to "hashed" #7053 - * fix(populate): handle nested populate underneath lean array correctly #7052 - * fix(update): make timestamps not crash on a null or undefined update #7041 - * docs(schematypes+validation): clean up links from validation docs to schematypes docs #7040 - * fix(model): apply timestamps to nested docs in bulkWrite() #7032 - * docs(populate): rewrite refPath docs to be simpler and more direct #7013 - * docs(faq): explain why destructuring imports are not supported in FAQ #7009 - -5.3.0 / 2018-09-28 -================== - * feat(mongoose): support `mongoose.set('debug', WritableStream)` so you can pipe debug to stderr, file, or network #7018 - * feat(query): add useNestedStrict option #6973 #5144 [lineus](https://github.com/lineus) - * feat(query): add getPopulatedPaths helper to Query.prototype #6970 #6677 [lineus](https://github.com/lineus) - * feat(model): add `createCollection()` helper to make transactions easier #6948 #6711 [Fonger](https://github.com/Fonger) - * feat(schema): add ability to do `schema.add(otherSchema)` to merge hooks, virtuals, etc. #6897 - * feat(query): add `orFail()` helper that throws an error if no documents match `filter` #6841 - * feat(mongoose): support global toObject and toJSON #6815 - * feat(connection): add deleteModel() to remove a model from a connection #6813 - * feat(mongoose): add top-level mongoose.ObjectId, mongoose.Decimal128 for easier schema declarations #6760 - * feat(aggregate+query): support for/await/of (async iterators) #6737 - * feat(mongoose): add global `now()` function that you can stub for testing timestamps #6728 - * feat(schema): support `schema.pre(RegExp, fn)` and `schema.post(RegExp, fn)` #6680 - * docs(query): add better docs for the `mongooseOptions()` function #6677 - * feat(mongoose): add support for global strict object #6858 - * feat(schema+mongoose): add autoCreate option to automatically create collections #6489 - * feat(update): update timestamps on nested subdocs when using `$set` #4412 - * feat(query+schema): add query `remove` hook and ability to switch between query `remove` and document `remove` middleware #3054 - -5.2.18 / 2018-09-27 -=================== - * docs(migrating_to_5): add note about overwriting filter properties #7030 - * fix(query): correctly handle `select('+c')` if c is not in schema #7017 - * fix(document): check path exists before checking for required #6974 - * fix(document): retain user-defined key order on initial set with nested docs #6944 - * fix(populate): handle multiple localFields + foreignFields using `localField: function() {}` syntax #5704 - -5.2.17 / 2018-09-21 -=================== - * docs(guide): clarify that Mongoose only increments versionKey on `save()` and add a workaround for `findOneAndUpdate()` #7038 - * fix(model): correctly handle `createIndex` option to `ensureIndexes()` #7036 #6922 [lineus](https://github.com/lineus) - * docs(migrating_to_5): add a note about changing debug output from stderr to stdout #7034 #7018 [lineus](https://github.com/lineus) - * fix(query): add `setUpdate()` to allow overwriting update without changing op #7024 #7012 [lineus](https://github.com/lineus) - * fix(update): find top-level version key even if there are `$` operators in the update #7003 - * docs(model+query): explain which operators `count()` supports that `countDocuments()` doesn't #6911 - -5.2.16 / 2018-09-19 -=================== - * fix(index): use dynamic require only when needed for better webpack support #7014 #7010 [jaydp17](https://github.com/jaydp17) - * fix(map): handle arrays of mixed maps #6995 - * fix(populate): leave justOne as null if populating underneath a Mixed type #6985 - * fix(populate): add justOne option to allow overriding any bugs with justOne #6985 - * fix(query): add option to skip adding timestamps to an update #6980 - * docs(model+schematype): improve docs about background indexes and init() #6966 - * fix: bump mongodb -> 3.1.6 to allow connecting to srv url without credentials #6955 #6881 [lineus](https://github.com/lineus) - * fix(connection): allow specifying `useCreateIndex` at the connection level, overrides global-level #6922 - * fix(schema): throw a helpful error if setting `ref` to an invalid value #6915 - -5.2.15 / 2018-09-15 -=================== - * fix(populate): handle virtual justOne correctly if it isn't set #6988 - * fix(populate): consistently use lowercase `model` instead of `Model` so double-populating works with existing docs #6978 - * fix(model): allow calling `Model.init()` again after calling `dropDatabase()` #6967 - * fix(populate): find correct justOne when double-populating underneath an array #6798 - * docs(webpack): make webpack docs use es2015 preset for correct libs and use acorn to test output is valid ES5 #6740 - * fix(populate): add selectPopulatedPaths option to opt out of auto-adding `populate()`-ed fields to `select()` #6546 - * fix(model): set timestamps on bulkWrite `insertOne` and `replaceOne` #5708 - -5.2.14 / 2018-09-09 -=================== - * docs: fix wording on promise docs to not imply queries only return promises #6983 #6982 [lineus](https://github.com/lineus) - * fix(map): throw TypeError if keys are not string #6956 - * fix(document): ensure you can `validate()` a child doc #6931 - * fix(populate): avoid cast error if refPath points to localFields with 2 different types #6870 - * fix(populate): handle populating already-populated paths #6839 - * fix(schematype): make ObjectIds handle refPaths when checking required #6714 - * fix(model): set timestamps on bulkWrite() updates #5708 - -5.2.13 / 2018-09-04 -=================== - * fix(map): throw TypeError if keys are not string #6968 [Fonger](https://github.com/Fonger) - * fix(update): make array op casting work with strict:false and {} #6962 #6952 [lineus](https://github.com/lineus) - * fix(document): add doc.deleteOne(), doc.updateOne(), doc.replaceOne() re: deprecation warnings #6959 #6940 [lineus](https://github.com/lineus) - * docs(faq+schematypes): add note about map keys needing to be strings #6957 #6956 [lineus](https://github.com/lineus) - * fix(schematype): remove unused if statement #6950 #6949 [cacothi](https://github.com/cacothi) - * docs: add /docs/deprecations.html for dealing with MongoDB driver deprecation warnings #6922 - * fix(populate): handle refPath where first element in array has no refPath #6913 - * fix(mongoose): allow setting useCreateIndex option after creating a model but before initial connection succeeds #6890 - * fix(updateValidators): ensure $pull validators always get an array #6889 - -5.2.12 / 2018-08-30 -=================== - * fix(document): disallow setting `constructor` and `prototype` if strict mode false - -4.13.17 / 2018-08-30 -==================== - * fix(document): disallow setting `constructor` and `prototype` if strict mode false - -5.2.11 / 2018-08-30 -=================== - * fix(document): disallow setting __proto__ if strict mode false - * fix(document): run document middleware on docs embedded in maps #6945 #6938 [Fonger](https://github.com/Fonger) - * fix(query): make castForQuery return a CastError #6943 #6927 [lineus](https://github.com/lineus) - * fix(query): use correct `this` scope when casting query with legacy 2dsphere pairs defined in schema #6939 #6937 [Fonger](https://github.com/Fonger) - * fix(document): avoid crash when calling `get()` on deeply nested subdocs #6929 #6925 [jakemccloskey](https://github.com/jakemccloskey) - * fix(plugins): make saveSubdocs execute child post save hooks _after_ the actual save #6926 - * docs: add dbName to api docs for .connect() #6923 [p722](https://github.com/p722) - * fix(populate): convert to array when schema specifies array, even if doc doesn't have an array #6908 - * fix(populate): handle `justOne` virtual populate underneath array #6867 - * fix(model): dont set versionKey on upsert if it is already `$set` #5973 - -4.13.16 / 2018-08-30 -==================== - * fix(document): disallow setting __proto__ if strict mode false - * feat(error): backport adding modified paths to VersionError #6928 [freewil](https://github.com/freewil) - -5.2.10 / 2018-08-27 -=================== - * fix: bump mongodb driver -> 3.1.4 #6920 #6903 #6884 #6799 #6741 [Fonger](https://github.com/Fonger) - * fix(model): track `session` option for `save()` as the document's `$session()` #6909 - * fix(query): add Query.getOptions() helper #6907 [Fonger](https://github.com/Fonger) - * fix(document): ensure array atomics get cleared after save() #6900 - * fix(aggregate): add missing redact and readConcern helpers #6895 [Fonger](https://github.com/Fonger) - * fix: add global option `mongoose.set('useCreateIndex', true)` to avoid ensureIndex deprecation warning #6890 - * fix(query): use `projection` option to avoid deprecation warnings #6888 #6880 [Fonger](https://github.com/Fonger) - * fix(query): use `findOneAndReplace()` internally if using `overwrite: true` with `findOneAndUpdate()` #6888 [Fonger](https://github.com/Fonger) - * fix(document): ensure required cache gets cleared correctly between subsequent saves #6892 - * fix(aggregate): support session chaining correctly #6886 #6885 [Fonger](https://github.com/Fonger) - * fix(query): use `projection` instead of `fields` internally for `find()` and `findOne()` to avoid deprecation warning #6880 - * fix(populate): add `getters` option to opt in to calling getters on populate #6844 - -5.2.9 / 2018-08-17 -================== - * fix(document): correctly propagate write concern options in save() #6877 [Fonger](https://github.com/Fonger) - * fix: upgrade mongodb driver -> 3.1.3 for numerous fixes #6869 #6843 #6692 #6670 [simllll](https://github.com/simllll) - * fix: correct `this` scope of default functions for DocumentArray and Array #6868 #6840 [Fonger](https://github.com/Fonger) - * fix(types): support casting JSON form of buffers #6866 #6863 [Fonger](https://github.com/Fonger) - * fix(query): get global runValidators option correctly #6865 #6578 - * fix(query): add Query.prototype.setQuery() analogous to `getQuery()` #6855 #6854 - * docs(connections): add note about the `family` option for IPv4 vs IPv6 and add port to example URIs #6784 - * fix(query): get global runValidators option correctly #6578 - -4.13.15 / 2018-08-14 -==================== - * fix(mongoose): add global `usePushEach` option for easier Mongoose 4.x + MongoDB 3.6 #6858 - * chore: fix flakey tests for 4.x #6853 [Fonger](https://github.com/Fonger) - * feat(error): add version number to VersionError #6852 [freewil](https://github.com/freewil) - -5.2.8 / 2018-08-13 -================== - * docs: update `execPopulate()` code example #6851 [WJakub](https://github.com/WJakub) - * fix(document): allow passing callback to `execPopulate()` #6851 - * fix(populate): populate with undefined fields without error #6848 #6845 [Fonger](https://github.com/Fonger) - * docs(migrating_to_5): Add `objectIdGetter` option docs #6842 [jwalton](https://github.com/jwalton) - * chore: run lint in parallel and only on Node.js v10 #6836 [Fonger](https://github.com/Fonger) - * fix(populate): throw helpful error if refPath excluded in query #6834 - * docs(migrating_to_5): add note about removing runSettersOnQuery #6832 - * fix: use safe-buffer to avoid buffer deprecation errors in Node.js 10 #6829 [Fonger](https://github.com/Fonger) - * docs(query): fix broken links #6828 [yaynick](https://github.com/yaynick) - * docs(defaults): clarify that defaults only run on undefined #6827 - * chore: fix flakey tests #6824 [Fonger](https://github.com/Fonger) - * docs: fix custom inspect function deprecation warning in Node.js 10 #6821 [yelworc](https://github.com/yelworc) - * fix(document): ensure subdocs get set to init state after save() so validators can run again #6818 - * fix(query): make sure embedded query casting always throws a CastError #6803 - * fix(document): ensure `required` function only gets called once when validating #6801 - * docs(connections): note that you must specify port if using `useNewUrlParser: true` #6789 - * fix(populate): support `options.match` in virtual populate schema definition #6787 - * fix(update): strip out virtuals from updates if strict: 'throw' rather than returning an error #6731 - -5.2.7 / 2018-08-06 -================== - * fix(model): check `expireAfterSeconds` option when diffing indexes in syncIndexes() #6820 #6819 [christopherhex](https://github.com/christopherhex) - * chore: fix some common test flakes in travis #6816 [Fonger](https://github.com/Fonger) - * chore: bump eslint and webpack to avoid bad versions of eslint-scope #6814 - * test(model): add delay to session tests to improve pass rate #6811 [Fonger](https://github.com/Fonger) - * fix(model): support options in `deleteMany` #6810 [Fonger](https://github.com/Fonger) - * fix(query): don't use $each when pushing an array into an array #6809 [lineus](https://github.com/lineus) - * chore: bump mquery so eslint isn't a prod dependency #6800 - * fix(populate): correctly get schema type when calling `populate()` on already populated path #6798 - * fix(populate): propagate readConcern options in populate from parent query #6792 #6785 [Fonger](https://github.com/Fonger) - * docs(connection): add description of useNewUrlParser option #6789 - * fix(query): make select('+path') a no-op if no select prop in schema #6785 - * docs(schematype+validation): document using function syntax for custom validator message #6772 - * fix(update): throw CastError if updating with `$inc: null` #6770 - * fix(connection): throw helpful error when calling `createConnection(undefined)` #6763 - -5.2.6 / 2018-07-30 -================== - * fix(document): don't double-call deeply nested custom getters when using `get()` #6779 #6637 - * fix(query): upgrade mquery for readConcern() helper #6777 - * docs(schematypes): clean up typos #6773 [sajadtorkamani](https://github.com/sajadtorkamani) - * refactor(browser): fix webpack warnings #6771 #6705 - * fix(populate): make error reported when no `localField` specified catchable #6767 - * docs(connection): use correct form in createConnection example #6766 [lineus](https://github.com/lineus) - * fix(connection): throw helpful error when using legacy `mongoose.connect()` syntax #6756 - * fix(document): handle overwriting `$session` in `execPopulate()` #6754 - * fix(query): propagate top-level session down to `populate()` #6754 - * fix(aggregate): add `session()` helper for consistency with query api #6752 - * fix(map): avoid infinite recursion when update overwrites a map #6750 - * fix(model): be consistent about passing noop callback to mongoose.model() `init()` as well as db.model() #6707 - -5.2.5 / 2018-07-23 -================== - * fix(boolean): expose `convertToTrue` and `convertToFalse` for custom boolean casting #6758 - * docs(schematypes): add note about what values are converted to booleans #6758 - * fix(document): fix(document): report castError when setting single nested doc to array #6753 - * docs: prefix mongoose.Schema call with new operator #6751 [sajadtorkamani](https://github.com/sajadtorkamani) - * docs(query): add examples and links to schema writeConcern option for writeConcern helpers #6748 - * docs(middleware): clarify that init middleware is sync #6747 - * perf(model): create error rather than modifying stack for source map perf #6735 - * fix(model): throw helpful error when passing object to aggregate() #6732 - * fix(model): pass Model instance as context to applyGetters when calling getters for virtual populate #6726 [lineus](https://github.com/lineus) - * fix(documentarray): remove `isNew` and `save` listeners on CastError because otherwise they never get removed #6723 - * docs(model+query): clarify when to use `countDocuments()` vs `estimatedDocumentCount()` #6713 - * fix(populate): correctly set virtual nestedSchemaPath when calling populate() multiple times #6644 - * docs(connections): add note about the `family` option for IPv4 vs IPv6 and add port to example URIs #6566 - -5.2.4 / 2018-07-16 -================== - * docs: Model.insertMany rawResult option in api docs #6724 [lineus](https://github.com/lineus) - * docs: fix typo on migrating to 5 guide #6722 [iagowp](https://github.com/iagowp) - * docs: update doc about keepalive #6719 #6718 [simllll](https://github.com/simllll) - * fix: ensure debug mode doesn't crash with sessions #6712 - * fix(document): report castError when setting single nested doc to primitive value #6710 - * fix(connection): throw helpful error if using `new db.model(foo)(bar)` #6698 - * fix(model): throw readable error with better stack trace when non-cb passed to $wrapCallback() #6640 - -5.2.3 / 2018-07-11 -================== - * fix(populate): if a getter is defined on the localField, use it when populating #6702 #6618 [lineus](https://github.com/lineus) - * docs(schema): add example of nested aliases #6671 - * fix(query): add `session()` function to queries to avoid positional argument mistakes #6663 - * docs(transactions): use new session() helper to make positional args less confusing #6663 - * fix(query+model+schema): add support for `writeConcern` option and writeConcern helpers #6620 - * docs(guide): add `writeConcern` option and re-add description for `safe` option #6620 - * docs(schema): fix broken API links #6619 - * docs(connections): add information re: socketTimeoutMS and connectTimeoutMS #4789 - -5.2.2 / 2018-07-08 -================== - * fix(model+query): add missing estimatedDocumentCount() function #6697 - * docs(faq): improve array-defaults section #6695 [lineus](https://github.com/lineus) - * docs(model): fix countDocuments() docs, bad copy/paste from count() docs #6694 #6643 - * fix(connection): add `startSession()` helper to connection and mongoose global #6689 - * fix: upgrade mongodb driver -> 3.1.1 for countDocuments() fix #6688 #6666 - * docs(compatibility): add MongoDB 4 range #6685 - * fix(populate): add ability to define refPath as a function #6683 [lineus](https://github.com/lineus) - * docs: add rudimentary transactions guide #6672 - * fix(update): make setDefaultsOnInsert handle nested subdoc updates with deeply nested defaults #6665 - * docs: use latest acquit-ignore to handle examples that start with acquit:ignore:start #6657 - * fix(validation): format `properties.message` as well as `message` #6621 - -5.2.1 / 2018-07-03 -================== - * fix(connection): allow setting the mongodb driver's useNewUrlParser option, default to false #6656 #6648 #6647 - * fix(model): only warn on custom _id index if index only has _id key #6650 - -5.2.0 / 2018-07-02 -================== - * feat(model): add `countDocuments()` #6643 - * feat(model): make ensureIndexes() fail if specifying an index on _id #6605 - * feat(mongoose): add `objectIdGetter` option to remove ObjectId.prototype._id #6588 - * feat: upgrade mongodb -> 3.1.0 for full MongoDB 4.0 support #6579 - * feat(query): support `runValidators` as a global option #6578 - * perf(schema): use WeakMap instead of array for schema stack #6503 - * feat(model): decorate unique discriminator indexes with partialFilterExpressions #6347 - * feat(model): add `syncIndexes()`, drops indexes that aren't in schema #6281 - * feat(document): add default getter/setter if virtual doesn't have one #6262 - * feat(discriminator): support discriminators on nested doc arrays #6202 - * feat(update): add `Query.prototype.set()` #5770 - -5.1.8 / 2018-07-02 -================== - * fix: don't throw TypeError if calling save() after original save() failed with push() #6638 [evanhenke](https://github.com/evanhenke) - * fix(query): add explain() helper and don't hydrate explain output #6625 - * docs(query): fix `setOptions()` lists #6624 - * docs: add geojson docs #6607 - * fix: bump mongodb -> 3.0.11 to avoid cyclic dependency error with retryWrites #6109 - -5.1.7 / 2018-06-26 -================== - * docs: add npm badge to readme #6623 [VFedyk](https://github.com/VFedyk) - * fix(document): don't throw parallel save error if post save hooks in parallel #6614 #6611 [lineus](https://github.com/lineus) - * fix(populate): allow dynamic ref to handle >1 model getModelsMapForPopulate #6613 #6612 [jimmytsao](https://github.com/jimmytsao) - * fix(document): handle `push()` on triple nested document array #6602 - * docs(validation): improve update validator doc headers #6577 [joeytwiddle](https://github.com/joeytwiddle) - * fix(document): handle document arrays in `modifiedPaths()` with includeChildren option #5904 - -5.1.6 / 2018-06-19 -================== - * fix: upgrade mongodb -> 3.0.10 - * docs(model+document): clarify that `save()` returns `undefined` if passed a callback #6604 [lineus](https://github.com/lineus) - * fix(schema): apply alias when adding fields with .add() #6593 - * docs: add full list of guides and streamline nav #6592 - * docs(model): add `projection` option to `findOneAndUpdate()` #6590 [lineus](https://github.com/lineus) - * docs: support @static JSDoc declaration #6584 - * fix(query): use boolean casting logic for $exists #6581 - * fix(query): cast all $text options to correct values #6581 - * fix(model): add support synchronous pre hooks for `createModel` #6552 [profbiss](https://github.com/profbiss) - * docs: add note about the `applyPluginsToDiscriminators` option #4965 - -5.1.5 / 2018-06-11 -================== - * docs(guide): rework query helper example #6575 [lineus](https://github.com/lineus) - * fix(populate): handle virtual populate with embedded discriminator under single nested subdoc #6571 - * docs: add string option to projections that call query select #6563 [lineus](https://github.com/lineus) - * style: use ES6 in collection.js #6560 [l33ds](https://github.com/l33ds) - * fix(populate): add virtual ref function ability getModelsMapForPopulate #6559 #6554 [lineus](https://github.com/lineus) - * docs(queries): fix link #6557 [sun1x](https://github.com/sun1x) - * fix(schema): rename indexes -> getIndexes to avoid webpack duplicate declaration #6547 - * fix(document): support `toString()` as custom method #6538 - * docs: add @instance for instance methods to be more compliant with JSDoc #6516 [treble-snake](https://github.com/treble-snake) - * fix(populate): avoid converting to map when using mongoose-deep-populate #6460 - * docs(browser): create new browser docs page #6061 - -5.1.4 / 2018-06-04 -================== - * docs(faq): add hr tags for parallel save error #6550 [lineus](https://github.com/lineus) - * docs(connection): fix broken link #6545 [iblamefish](https://github.com/iblamefish) - * fix(populate): honor subpopulate options #6539 #6528 [lineus](https://github.com/lineus) - * fix(populate): allow population of refpath under array #6537 #6509 [lineus](https://github.com/lineus) - * fix(query): dont treat $set the same as the other ops in update casting #6535 [lineus](https://github.com/lineus) - * fix: bump async -> 2.6.1 #6534 #6505 [lineus](https://github.com/lineus) - * fix: support using a function as validation error message #6530 [lucandrade](https://github.com/lucandrade) - * fix(populate): propagate `lean()` down to subpopulate #6498 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs(lambda): add info on what happens if database does down between lambda function calls #6409 - * fix(update): allow updating embedded discriminator path if discriminator key is in filter #5841 - -5.1.3 / 2018-05-28 -================== - * fix(document): support set() on path underneath array embedded discriminator #6526 - * chore: update lodash and nsp dev dependencies #6514 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix(document): throw readable error when saving the same doc instance more than once in parallel #6511 #6456 #4064 [lineus](https://github.com/lineus) - * fix(populate): set correct nestedSchemaPath for virtual underneath embedded discriminator #6501 #6487 [lineus](https://github.com/lineus) - * docs(query): add section on promises and warning about not mixing promises and callbacks #6495 - * docs(connection): add concrete example of connecting to multiple hosts #6492 [lineus](https://github.com/lineus) - * fix(populate): handle virtual populate under single nested doc under embedded discriminator #6488 - * fix(schema): collect indexes from embedded discriminators for autoIndex build #6485 - * fix(document): handle `doc.set()` underneath embedded discriminator #6482 - * fix(document): handle set() on path under embedded discriminator with object syntax #6482 - * fix(document): handle setting nested property to object with only non-schema properties #6436 - -4.13.14 / 2018-05-25 -==================== - * fix(model): handle retainKeyOrder option in findOneAndUpdate() #6484 - -5.1.2 / 2018-05-21 -================== - * docs(guide): add missing SchemaTypes #6490 [distancesprinter](https://github.com/distancesprinter) - * fix(map): make MongooseMap.toJSON return a serialized object #6486 #6478 [lineus](https://github.com/lineus) - * fix(query): make CustomQuery inherit from model.Query for hooks #6483 #6455 [lineus](https://github.com/lineus) - * fix(document): prevent default falses from being skipped by $__dirty #6481 #6477 [lineus](https://github.com/lineus) - * docs(connection): document `useDb()` #6480 - * fix(model): skip redundant clone in insertMany #6479 [d1manson](https://github.com/d1manson) - * fix(aggregate): let replaceRoot accept objects as well as strings #6475 #6474 [lineus](https://github.com/lineus) - * docs(model): clarify `emit()` in mapReduce and how map/reduce are run #6465 - * fix(populate): flatten array to handle multi-level nested `refPath` #6457 - * fix(date): cast small numeric strings as years #6444 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(populate): remove unmatched ids when using virtual populate on already hydrated document #6435 - * fix(array): use custom array class to avoid clobbered property names #6431 - * fix(model): handle hooks for custom methods that return promises #6385 - -4.13.13 / 2018-05-17 -==================== - * fix(update): stop clobbering $in when casting update #6441 #6339 - * fix: upgrade async -> 2.6.0 re: security warning - -5.1.1 / 2018-05-14 -================== - * docs(schema): add notes in api and guide about schema.methods object #6470 #6440 [lineus](https://github.com/lineus) - * fix(error): add modified paths to VersionError #6464 #6433 [paglias](https://github.com/paglias) - * fix(populate): only call populate with full param signature when match is not present #6458 #6451 [lineus](https://github.com/lineus) - * docs: fix geoNear link in migration guide #6450 [kawache](https://github.com/kawache) - * fix(discriminator): throw readable error when `create()` with a non-existent discriminator key #6434 - * fix(populate): add `retainNullValues` option to avoid stripping out null keys #6432 - * fix(populate): handle populate in embedded discriminators underneath nested paths #6411 - * docs(model): add change streams and ToC, make terminology more consistent #5888 - -5.1.0 / 2018-05-10 -================== - * feat(ObjectId): add `_id` getter so you can get a usable id whether or not the path is populated #6415 #6115 - * feat(model): add Model.startSession() #6362 - * feat(document): add doc.$session() and set session on doc after query #6362 - * feat: add Map type that supports arbitrary keys #6287 #681 - * feat: add `cloneSchemas` option to mongoose global to opt in to always cloning schemas before use #6274 - * feat(model): add `findOneAndDelete()` and `findByIdAndDelete()` #6164 - * feat(document): support `$ignore()` on single nested and array subdocs #6152 - * feat(document): add warning about calling `save()` on subdocs #6152 - * fix(model): make `save()` use `updateOne()` instead of `update()` #6031 - * feat(error): add version number to VersionError #5966 - * fix(query): allow `[]` as a value for `$in` when casting #5913 - * fix(document): avoid running validators on single nested paths if only a child path is modified #5885 - * feat(schema): print warning if method conflicts with mongoose internals #5860 - -5.0.18 / 2018-05-09 -=================== - * fix(update): stop clobbering $in when casting update #6441 #6339 [lineus](https://github.com/lineus) - * fix: upgrade mongodb driver -> 3.0.8 to fix session issue #6437 #6357 [simllll](https://github.com/simllll) - * fix: upgrade bson -> 1.0.5 re: https://snyk.io/vuln/npm:bson:20180225 #6423 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix: look for `valueOf()` when casting to Decimal128 #6419 #6418 [lineus](https://github.com/lineus) - * fix: populate array of objects with space separated paths #6414 [lineus](https://github.com/lineus) - * test: add coverage for `mongoose.pluralize()` #6412 [FastDeath](https://github.com/FastDeath) - * fix(document): avoid running default functions on init() if path has value #6410 - * fix(document): allow saving document with `null` id #6406 - * fix: prevent casting of populated docs in document.init #6390 [lineus](https://github.com/lineus) - * fix: remove `toHexString()` helper that was added in 5.0.15 #6359 - -5.0.17 / 2018-04-30 -=================== - * docs(migration): certain chars in passwords may cause connection failures #6401 [markstos](https://github.com/markstos) - * fix(document): don't throw when `push()` on a nested doc array #6398 - * fix(model): apply hooks to custom methods if specified #6385 - * fix(schema): support opting out of one timestamp field but not the other for `insertMany()` #6381 - * fix(documentarray): handle `required: true` within documentarray definition #6364 - * fix(document): ensure `isNew` is set before default functions run on init #3793 - -5.0.16 / 2018-04-23 -=================== - * docs(api): sort api methods based on their string property #6374 [lineus](https://github.com/lineus) - * docs(connection): fix typo in `createCollection()` #6370 [mattc41190](https://github.com/mattc41190) - * docs(document): remove vestigial reference to `numAffected` #6367 [ekulabuhov](https://github.com/ekulabuhov) - * docs(schema): fix typo #6366 [dhritzkiv](https://github.com/dhritzkiv) - * docs(schematypes): add missing `minlength` and `maxlength` docs #6365 [treble-snake](https://github.com/treble-snake) - * docs(queries): fix formatting #6360 [treble-snake](https://github.com/treble-snake) - * docs(api): add cursors to API docs #6353 #6344 [lineus](https://github.com/lineus) - * docs(aggregate): remove reference to non-existent `.select()` method #6346 - * fix(update): handle `required` array with update validators and $pull #6341 - * fix(update): avoid setting __v in findOneAndUpdate if it is `$set` #5973 - -5.0.15 / 2018-04-16 -=================== - * fix: add ability for casting from number to decimal128 #6336 #6331 [lineus](https://github.com/lineus) - * docs(middleware): enumerate the ways to error out in a hook #6315 - * fix(document): respect schema-level depopulate option for toObject() #6313 - * fix: bump mongodb driver -> 3.0.6 #6310 - * fix(number): check for `valueOf()` function to support Decimal.js #6306 #6299 [lineus](https://github.com/lineus) - * fix(query): run array setters on query if input value is an array #6277 - * fix(versioning): don't require matching version when using array.pull() #6190 - * fix(document): add `toHexString()` function so you don't need to check whether a path is populated to get an id #6115 - -5.0.14 / 2018-04-09 -=================== - * fix(schema): clone aliases and alternative option syntax correctly - * fix(query): call utils.toObject in query.count like in query.find #6325 [lineus](https://github.com/lineus) - * docs(populate): add middleware examples #6320 [BorntraegerMarc](https://github.com/BorntraegerMarc) - * docs(compatibility): fix dead link #6319 [lacivert](https://github.com/lacivert) - * docs(api): fix markdown parsing for parameters #6318 #6314 [lineus](https://github.com/lineus) - * fix(populate): handle space-delimited paths in array populate #6296 #6284 [lineus](https://github.com/lineus) - * fix(populate): support basic virtual populate underneath embedded discriminators #6273 - -5.0.13 / 2018-04-05 -=================== - * docs(faq): add middleware to faq arrow function warning #6309 [lineus](https://github.com/lineus) - * docs(schema): add example to loadClass() docs #6308 - * docs: clean up misc typos #6304 [sfrieson](https://github.com/sfrieson) - * fix(document): apply virtuals when calling `toJSON()` on a nested path #6294 - * refactor(connection): use `client.db()` syntax rather than double-parsing the URI #6292 #6286 - * docs: document new behavior of required validator for arrays #6288 [daltones](https://github.com/daltones) - * fix(schema): treat set() options as user-provided options #6274 - * fix(schema): clone discriminators correctly #6274 - * fix(update): make setDefaultsOnInsert not create subdoc if only default is id #6269 - * docs(discriminator): clarify 3rd argument to Model.discriminator() #2596 - -5.0.12 / 2018-03-27 -=================== - * docs(query): updating model name in query API docs #6280 [lineus](https://github.com/lineus) - * docs: fix typo in tests #6275 [styler](https://github.com/styler) - * fix: add missing `.hint()` to aggregate #6272 #6251 [lineus](https://github.com/lineus) - * docs(api): add headers to each API docs section for easer nav #6261 - * fix(query): ensure hooked query functions always run on next tick for chaining #6250 - * fix(populate): ensure populated array not set to null if it isn't set #6245 - * fix(connection): set readyState to disconnected if initial connection fails #6244 #6131 - * docs(model): make `create()` params show up correctly in docs #6242 - * fix(model): make error handlers work with MongoDB server errors and `insertMany()` #6228 - * fix(browser): ensure browser document builds defaults for embedded arrays correctly #6175 - * fix(timestamps): set timestamps when using `updateOne()` and `updateMany()` #6282 [gualopezb](https://github.com/gualopezb) - -5.0.11 / 2018-03-19 -=================== - * fix(update): handle $pull with $in in update validators #6240 - * fix(query): don't convert undefined to null when casting so driver `ignoreUndefined` option works #6236 - * docs(middleware): add example of using async/await with middleware #6235 - * fix(populate): apply justOne option before `completeMany()` so it works with lean() #6234 - * fix(query): ensure errors in user callbacks aren't caught in init #6195 #6178 - * docs(connections): document dbName option for Atlas connections #6179 - * fix(discriminator): make child schema nested paths overwrite parent schema paths #6076 - -4.13.12 / 2018-03-13 -==================== - * fix(document): make virtual get() return undefined instead of null if no getters #6223 - * docs: fix url in useMongoClient error message #6219 #6217 [lineus](https://github.com/lineus) - * fix(discriminator): don't copy `discriminators` property from base schema #6122 #6064 - -5.0.10 / 2018-03-12 -=================== - * docs(schematype): add notes re: running setters on queries #6209 - * docs: fix typo #6208 [kamagatos](https://github.com/kamagatos) - * fix(query): only call setters once on query filter props for findOneAndUpdate and findOneAndRemove #6203 - * docs: elaborate on connection string changes in migration guide #6193 - * fix(document): skip applyDefaults if subdoc is null #6187 - * docs: fix schematypes docs and link to them #6176 - * docs(faq): add FAQs re: array defaults and casting aggregation pipelines #6184 #6176 #6170 [lineus](https://github.com/lineus) - * fix(document): ensure primitive defaults are set and built-in default functions run before setters #6155 - * fix(query): handle single embedded embedded discriminators in castForQuery #6027 - -5.0.9 / 2018-03-05 -================== - * perf: bump mongodb -> 3.0.4 to fix SSL perf issue #6065 - -5.0.8 / 2018-03-03 -================== - * docs: remove obsolete references to `emitIndexErrors` #6186 [isaackwan](https://github.com/isaackwan) - * fix(query): don't cast findOne() until exec() so setters don't run twice #6157 - * fix: remove document_provider.web.js file #6186 - * fix(discriminator): support custom discriminator model names #6100 [wentout](https://github.com/wentout) - * fix: support caching calls to `useDb()` #6036 [rocketspacer](https://github.com/rocketspacer) - * fix(query): add omitUndefined option so setDefaultsOnInsert can kick in on undefined #6034 - * fix: upgrade mongodb -> 3.0.3 for reconnectTries: 0 blocking process exit fix #6028 - -5.0.7 / 2018-02-23 -================== - * fix: support eachAsync options with aggregation cursor #6169 #6168 [vichle](https://github.com/vichle) - * docs: fix link to MongoDB compound indexes docs #6162 [br0p0p](https://github.com/br0p0p) - * docs(aggregate): use eachAsync instead of incorrect `each()` #6160 [simllll](https://github.com/simllll) - * chore: fix benchmarks #6158 [pradel](https://github.com/pradel) - * docs: remove dead link to old blog post #6154 [markstos](https://github.com/markstos) - * fix: don't convert dates to numbers when updating mixed path #6146 #6145 [s4rbagamble](https://github.com/s4rbagamble) - * feat(aggregate): add replaceRoot, count, sortByCount helpers #6142 [jakesjews](https://github.com/jakesjews) - * fix(document): add includedChildren flag to modifiedPaths() #6134 - * perf: don't create wrapper function if no hooks specified #6126 - * fix(schema): allow indexes on single nested subdocs for geoJSON #6113 - * fix(document): allow depopulating all fields #6073 - * feat(mongoose): add support for `useFindAndModify` option on singleton #5616 - -5.0.6 / 2018-02-15 -================== - * refactor(query.castUpdate): avoid creating error until necessary #6137 - * docs(api): fix missing api docs #6136 [lineus](https://github.com/lineus) - * fix(schema): copy virtuals when using `clone()` #6133 - * fix(update): avoid digging into buffers with upsert and replaceOne #6124 - * fix(schema): support `enum` on arrays of strings #6102 - * fix(update): cast `$addToSet: [1, 2]` -> `$addToSet: { $each: [1, 2] }` #6086 - -5.0.5 / 2018-02-13 -================== - * docs: make > show up correctly in API docs #6114 - * fix(query): support `where()` overwriting primitive with object #6097 - * fix(schematype): don't run internal `resetId` setter on queries with _id #6093 - * fix(discriminator): don't copy `discriminators` property from base schema #6064 - * fix(utils): respect `valueOf()` when merging object for update #6059 - * docs(validation): fix typo 'maxLength' #4720 - * fix(document): apply defaults after setting initial value so default functions don't see empty doc #3781 - -5.0.4 / 2018-02-08 -================== - * docs: add lambda guide #6107 - * fix(connection): add `dbName` option to work around `mongodb+srv` not supporting db name in URI #6106 - * fix(schematype): fix regexp typo in ObjectId #6098 [JoshuaWise](https://github.com/JoshuaWise) - * perf(document): re-use the modifiedPaths list #6092 [tarun1793](https://github.com/tarun1793) - * fix: use console.info() instead of console.error() for debug output #6088 [yuristsepaniuk](https://github.com/yuristsepaniuk) - * docs(validation): clean up runValidators and isAsync options docs for 5.x #6083 - * docs(model): use array instead of spread consistently for aggregate() #6070 - * fix(schema): make aliases handle mongoose-lean-virtuals #6069 - * docs(layout): add link to subdocs guide #6056 - * fix(query): make strictQuery: true strip out fields that aren't in the schema #6032 - * docs(guide): add notes for `strictQuery` option #6032 - -4.13.11 / 2018-02-07 -==================== - * docs: fix links in 4.x docs #6081 - * chore: add release script that uses --tag for npm publish for 4.x releases #6063 - -5.0.3 / 2018-01-31 -================== - * fix: consistently use process.nextTick() to avoid sinon.useFakeTimers() causing ops to hang #6074 - * docs(aggregate): fix typo #6072 [adursun](https://github.com/adursun) - * chore: add return type to `mongoose.model()` docs [bryant1410](https://github.com/bryant1410) - * fix(document): depopulate push()-ed docs when saving #6048 - * fix: upgrade mongodb -> 3.0.2 #6019 - -5.0.2 / 2018-01-28 -================== - * fix(schema): do not overwrite default values in schema when nested timestamps are provided #6024 [cdeveas](https://github.com/cdeveas) - * docs: fix syntax highlighting in models.jade, schematypes.jade, subdocs.jade #6058 [lineus](https://github.com/lineus) - * fix: use lazy loading so we can build mongoose with webpack #5993 #5842 - * docs(connections): clarify multi-mongos with useMongoClient for 4.x docs #5984 - * fix(populate): handle populating embedded discriminator paths #5970 - -4.13.10 / 2018-01-28 -==================== - * docs(model+query): add lean() option to Model helpers #5996 [aguyinmontreal](https://github.com/aguyinmontreal) - * fix: use lazy loading so we can build mongoose with webpack #5993 #5842 - * docs(connections): clarify multi-mongos with useMongoClient for 4.x docs #5984 - * fix(populate): handle populating embedded discriminator paths #5970 - * docs(query+aggregate): add more detail re: maxTimeMS #4066 - -5.0.1 / 2018-01-19 -================== - * fix(document): make validate() not resolve to document #6014 - * fix(model): make save() not return DocumentNotFoundError if using fire-and-forget writes #6012 - * fix(aggregate): make options() work as advertised #6011 [spederiva](https://github.com/spederiva) - * docs(queries): fix code samples #6008 - -5.0.0 / 2018-01-17 -================== - * test: refactor tests to use start fewer connections #5985 [fenanquin](https://github.com/fenanquin) - * feat: add global bufferCommands option #5879 - * docs: new docs site and build system #5976 - * test: increase timeout on slow test cases #5968 [fenanquin](https://github.com/fenanquin) - * fix: avoid casting out array filter elements #5965 - * feat: add Model.watch() wrapper #5964 - * chore: replace istanbul with nyc #5962 [ChristianMurphy](https://github.com/ChristianMurphy) - -4.13.9 / 2018-01-07 -=================== - * chore: update marked (dev dependency) re: security vulnerability #5951 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix: upgrade mongodb -> 2.2.34 for ipv6 and autoReconnect fixes #5794 #5760 - * docs: use useMongooseAggCursor for aggregate docs #2955 - -5.0.0-rc2 / 2018-01-04 -====================== - * fix: add cleaner warning about no longer needing `useMongoClient` in 5.x #5961 - * chore: update acquit -> 0.5.1 for minor security patch #5961 [ChristianMurphy](https://github.com/ChristianMurphy) - * docs: add docs for mongoose 4.x at http://mongoosejs.com/docs/4.x #5959 - * docs: add link to migration guide #5957 - * chore: update eslint to version 4.14.0 #5955 [ChristianMurphy](https://github.com/ChristianMurphy) - * chore: update mocha to version 4.1.0 [ChristianMurphy](https://github.com/ChristianMurphy) - -5.0.0-rc1 / 2018-01-02 -====================== - * fix(index): use pluralize correctly for `mongoose.model()` #5958 - * fix: make mquery use native promises by default #5945 - * fix(connection): ensure 'joined' and 'left' events get bubbled up #5944 - -5.0.0-rc0 / 2017-12-28 -====================== - * BREAKING CHANGE: always use mongoose aggregation cursor when using `.aggregate().cursor()` #5941 - * BREAKING CHANGE: attach query middleware when compiling model #5939 - * BREAKING CHANGE: `emitIndexErrors` is on by default, failing index build will throw uncaught error if not handled #5910 - * BREAKING CHANGE: remove precompiled browser bundle #5895 - * feat: add `mongoose.pluralize()` function #5877 - * BREAKING CHANGE: remove `passRawResult` option for `findOneAndUpdate`, use `rawResult` #5869 - * BREAKING CHANGE: implicit async validators (based on number of function args) are removed, return a promise instead #5824 - * BREAKING CHANGE: fail fast if user sets a unique index on `_id` #5820 [varunjayaraman](https://github.com/varunjayaraman) - * BREAKING CHANGE: mapReduce resolves to an object with 2 keys rather than 2 separate args #5816 - * BREAKING CHANGE: `mongoose.connect()` returns a promise, removed MongooseThenable #5796 - * BREAKING CHANGE: query stream removed, use `cursor()` instead #5795 - * BREAKING CHANGE: connection `open()` and `openSet()` removed, use `openUri()` instead #5795 - * BREAKING CHANGE: use MongoDB driver 3.0.0, drop support for MongoDB server < 3.0.0 #5791 #4740 - * BREAKING CHANGE: remove support for `$pushAll`, remove `usePushEach` option #5670 - * BREAKING CHANGE: make date casting use native Date #5395 [varunjayaraman](https://github.com/varunjayaraman) - * BREAKING CHANGE: remove `runSettersOnQuery`, always run setters on query #5340 - * BREAKING CHANGE: array of length 0 now satisfies `required: true` for arays #5139 [wlingke](https://github.com/wlingke) - * BREAKING CHANGE: remove `saveErrorIfNotFound`, always error out if `save()` did not update a document #4973 - * BREAKING CHANGE: don't execute getters in reverse order #4835 - * BREAKING CHANGE: make boolean casting more strict #4245 - * BREAKING CHANGE: `toObject()` and `toJSON()` option parameter merges with defaults rather than overwriting #4131 - * feat: allow setting `default` on `_id` #4069 - * BREAKING CHANGE: `deleteX()` and `remove()` promise resolves to the write object result #4013 - * feat: support returning a promise from middleware functions #3779 - * BREAKING CHANGE: don't return a promise if callback specified #3670 - * BREAKING CHANGE: only cast `update()`, `updateX()`, `replaceOne()`, `remove()`, `deleteX()` in exec #3529 - * BREAKING CHANGE: sync errors in middleware functions are now handled #3483 - * BREAKING CHANGE: post hooks get flow control #3232 - * BREAKING CHANGE: deduplicate hooks when merging discriminator schema #2945 - * BREAKING CHANGE: use native promises by default, remove support for mpromise #2917 - * BREAKING CHANGE: remove `retainKeyOrder`, always use forward order when iterating through objects #2749 - * BREAKING CHANGE: `aggregate()` no longer accepts a spread #2716 - -4.13.8 / 2017-12-27 -=================== - * docs(guide): use more up-to-date syntax for autoIndex example #5933 - * docs: fix grammar #5927 [abagh0703](https://github.com/abagh0703) - * fix: propagate lean options to child schemas #5914 - * fix(populate): use correct model with discriminators + nested populate #5858 - -4.13.7 / 2017-12-11 -=================== - * docs(schematypes): fix typo #5889 [gokaygurcan](https://github.com/gokaygurcan) - * fix(cursor): handle `reject(null)` with eachAsync callback #5875 #5874 [ZacharyRSmith](https://github.com/ZacharyRSmith) - * fix: disallow setting `mongoose.connection` to invalid values #5871 [jinasonlin](https://github.com/jinasonlin) - * docs(middleware): suggest using `return next()` to stop middleware execution #5866 - * docs(connection): improve connection string query param docs #5864 - * fix(document): run validate hooks on array subdocs even if not directly modified #5861 - * fix(discriminator): don't treat $meta as defining projection when querying #5859 - * fix(types): handle Decimal128 when using bson-ext on server side #5850 - * fix(document): ensure projection with only $slice isn't treated as inclusive for discriminators #4991 - * fix(model): throw error when passing non-object to create() #2037 - -4.13.6 / 2017-12-02 -=================== - * fix(schema): support strictBool option in schema #5856 [ekulabuhov](https://github.com/ekulabuhov) - * fix(update): make upsert option consistently handle truthy values, not just booleans, for updateOne() #5839 - * refactor: remove unnecessary constructor check #2057 - * docs(query): correct function signature for .mod() helper #1806 - * fix(query): report ObjectParameterError when passing non-object as filter to find() and findOne() #1698 - -4.13.5 / 2017-11-24 -=================== - * fix(model): handle update cast errors correctly with bulkWrite #5845 [Michael77](https://github.com/Michael77) - * docs: add link to bufferCommands option #5844 [ralphite](https://github.com/ralphite) - * fix(model): allow virtual ref function to return arrays #5834 [brunohcastro](https://github.com/brunohcastro) - * fix(query): don't throw uncaught error if query filter too big #5812 - * fix(document): if setting unselected nested path, don't overwrite nested path #5800 - * fix(document): support calling `populate()` on nested document props #5703 - * fix: add `strictBool` option for schema type boolean #5344 #5211 #4245 - * docs(faq): add faq re: typeKey #1886 - * docs(query): add more detailed docs re: options #1702 - -4.13.4 / 2017-11-17 -=================== - * fix(aggregate): add chainable .option() helper for setting arbitrary options #5829 - * fix(aggregate): add `.pipeline()` helper to get the current pipeline #5825 - * docs: grammar fixes for `unique` FAQ #5823 [mfluehr](https://github.com/mfluehr) - * chore: add node 9 to travis #5822 [superheri](https://github.com/superheri) - * fix(model): fix infinite recursion with recursive embedded discriminators #5821 [Faibk](https://github.com/Faibk) - -4.13.3 / 2017-11-15 -=================== - * chore: add node 8 to travis #5818 [superheri](https://github.com/superheri) - * fix(document): don't apply transforms to nested docs when updating already saved doc #5807 - -4.13.2 / 2017-11-11 -=================== - * feat(buffer): add support for subtype prop #5530 - -4.13.1 / 2017-11-08 -=================== - * fix: accept multiple paths or array of paths to depopulate #5798 #5797 [adamreisnz](https://github.com/adamreisnz) - * fix(document): pass default array as actual array rather than taking first element #5780 - * fix(model): increment version when $set-ing it in a save() that requires a version bump #5779 - * fix(query): don't explicitly project in discriminator key if user projected in parent path #5775 #5754 - * fix(model): cast query option to geoNear() #5765 - * fix(query): don't treat projection with just $slice as inclusive #5737 - * fix(discriminator): defer applying embedded discriminator hooks until top-level model is compiled #5706 - * docs(discriminator): add warning to always attach hooks before calling discriminator() #5706 - -4.13.0 / 2017-11-02 -=================== - * feat(aggregate): add $addFields helper #5740 [AyushG3112](https://github.com/AyushG3112) - * feat(connection): add connection-level bufferCommands #5720 - * feat(connection): add createCollection() helper #5712 - * feat(populate): support setting localField and foreignField to functions #5704 #5602 - * feat(query): add multipleCastError option for aggregating cast errors when casting update #5609 - * feat(populate): allow passing a function to virtual ref #5602 - * feat(schema): add excludeIndexes option to optionally prevent collecting indexes from nested schemas #5575 - * feat(model): report validation errors from `insertMany()` if using `ordered: false` and `rawResult: true` #5337 - * feat(aggregate): add pre/post aggregate middleware #5251 - * feat(schema): allow using `set` as a schema path #1939 - -4.12.6 / 2017-11-01 -=================== - * fix(schema): make clone() copy query helpers correctly #5752 - * fix: undeprecate `ensureIndex()` and use it by default #3280 - -4.12.5 / 2017-10-29 -=================== - * fix(query): correctly handle `$in` and required for $pull and update validators #5744 - * feat(aggegate): add $addFields pipeline operator #5740 [AyushG3112](https://github.com/AyushG3112) - * fix(document): catch sync errors in document pre hooks and report as error #5738 - * fix(populate): handle slice projections correctly when automatically selecting populated fields #5737 - * fix(discriminator): fix hooks for embedded discriminators #5706 [wlingke](https://github.com/wlingke) - * fix(model): throw sane error when customer calls `mongoose.Model()` over `mongoose.model()` #2005 - -4.12.4 / 2017-10-21 -=================== - * test(plugins): add coverage for idGetter with id as a schema property #5713 [wlingke](https://github.com/wlingke) - * fix(model): avoid copying recursive $$context object when creating discriminator after querying #5721 - * fix(connection): ensure connection promise helpers are removed before emitting 'connected' #5714 - * docs(schema): add notes about runSettersOnQuery to schema setters #5705 - * fix(collection): ensure queued operations run on the next tick #5562 - -4.12.3 / 2017-10-16 -=================== - * fix(connection): emit 'reconnect' event as well as 'reconnected' for consistency with driver #5719 - * fix: correctly bubble up left/joined events for replica set #5718 - * fix(connection): allow passing in `autoIndex` as top-level option rather than requiring `config.autoIndex` #5711 - * docs(connection): improve docs regarding reconnectTries, autoReconnect, and bufferMaxEntries #5711 - * fix(query): handle null with addToSet/push/pull/pullAll update validators #5710 - * fix(model): handle setDefaultsOnInsert option for bulkWrite updateOne and updateMany #5708 - * fix(query): avoid infinite recursion edge case when cloning a buffer #5702 - -4.12.2 / 2017-10-14 -=================== - * docs(faq): add FAQ about using arrow functions for getters/setters, virtuals, and methods #5700 - * docs(schema): document the childSchemas property and add to public API #5695 - * fix(query): don't project in populated field if parent field is already projected in #5669 - * fix: bump mongodb -> 2.2.33 for issue with autoReconnect #4513 - -4.12.1 / 2017-10-08 -=================== - * fix(document): create new doc when setting single nested, no more set() on copy of priorVal #5693 - * fix(model): recursively call applyMethods on child schemas for global plugins #5690 - * docs: fix bad promise lib example on home page #5686 - * fix(query): handle false when checking for inclusive/exclusive projection #5685 - * fix(discriminator): allow reusing child schema #5684 - * fix: make addToSet() on empty array with subdoc trigger manual population #5504 - -4.12.0 / 2017-10-02 -=================== - * docs(validation): add docs coverage for ValidatorError.reason #5681 - * feat(discriminator): always add discriminatorKey to base schema to allow updating #5613 - * fix(document): make nested docs no longer inherit parent doc's schema props #5586 #5546 #5470 - * feat(query): run update validators on $pull and $pullAll #5555 - * feat(query): add .error() helper to query to error out in pre hooks #5520 - * feat(connection): add dropCollection() helper #5393 - * feat(schema): add schema-level collation option #5295 - * feat(types): add `discriminator()` function for single nested subdocs #5244 - * feat(document): add $isDeleted() getter/setter for better support for soft deletes #4428 - * feat(connection): bubble up reconnectFailed event when driver gives up reconnecting #4027 - * fix(query): report error if passing array or other non-object as filter to update query #3677 - * fix(collection): use createIndex() instead of deprecated ensureIndex() #3280 - -4.11.14 / 2017-09-30 -==================== - * chore: add nsp check to the CI build #5679 [hairyhenderson](https://github.com/hairyhenderson) - * fix: bump mquery because of security issue with debug package #5677 #5675 [jonathanprl](https://github.com/jonathanprl) - * fix(populate): automatically select() populated()-ed fields #5669 - * fix(connection): make force close work as expected #5664 - * fix(document): treat $elemMatch as inclusive projection #5661 - * docs(model/query): clarify which functions fire which middleware #5654 - * fix(model): make `init()` public and return a promise that resolves when indexes are done building #5563 - -4.11.13 / 2017-09-24 -==================== - * fix(query): correctly run replaceOne with update validators #5665 [sime1](https://github.com/sime1) - * fix(schema): replace mistype in setupTimestamp method #5656 [zipp3r](https://github.com/zipp3r) - * fix(query): avoid throwing cast error for strict: throw with nested id in query #5640 - * fix(model): ensure class gets combined schema when using class syntax with discriminators #5635 - * fix(document): handle setting doc array to array of top-level docs #5632 - * fix(model): handle casting findOneAndUpdate() with overwrite and upsert #5631 - * fix(update): correctly handle $ in updates #5628 - * fix(types): handle manual population consistently for unshift() and splice() #5504 - -4.11.12 / 2017-09-18 -==================== - * docs(model): asterisk should not render as markdown bullet #5644 [timkinnane](https://github.com/timkinnane) - * docs: use useMongoClient in connection example #5627 [GabrielNicolasAvellaneda](https://github.com/GabrielNicolasAvellaneda) - * fix(connection): call callback when initial connection failed #5626 - * fix(query): apply select correctly if a given nested schema is used for 2 different paths #5603 - * fix(document): add graceful fallback for setting a doc array value and `pull()`-ing a doc #3511 - -4.11.11 / 2017-09-10 -==================== - * fix(connection): properly set readyState in response to driver 'close' and 'reconnect' events #5604 - * fix(document): ensure single embedded doc setters only get called once, with correct value #5601 - * fix(timestamps): allow enabling updatedAt without createdAt #5598 - * test: improve unique validator test by making create run before ensureIndex #5595 #5562 - * fix(query): ensure find callback only gets called once when post init hook throws error #5592 - -4.11.10 / 2017-09-03 -==================== - * docs: add KeenIO tracking #5612 - * fix(schema): ensure validators declared with `.validate()` get copied with clone() #5607 - * fix: remove unnecessary jest warning #5480 - * fix(discriminator): prevent implicit discriminator schema id from clobbering base schema custom id #5591 - * fix(schema): hide schema objectid warning for non-hex strings of length 24 #5587 - * docs(populate): use story schema defined key author instead of creator #5578 [dmric](https://github.com/dmric) - * docs(document): describe usage of `.set()` #5576 - * fix(document): ensure correct scope in single nested validators #5569 - * fix(populate): don't mark path as populated until populate() is done #5564 - * fix(document): make push()-ing a doc onto an empty array act as manual population #5504 - * fix(connection): emit timeout event on socket timeout #4513 - -4.11.9 / 2017-08-27 -=================== - * fix(error): avoid using arguments.callee because that breaks strict mode #5572 - * docs(schematypes): fix spacing #5567 - * fix(query): enforce binary subtype always propagates to mongodb #5551 - * fix(query): only skip castForQuery for mongoose arrays #5536 - * fix(browser): rely on browser entrypoint to decide whether to use BrowserDocument or NodeDocument #5480 - -4.11.8 / 2017-08-23 -=================== - * feat: add warning about using schema ObjectId as type ObjectId #5571 [efkan](https://github.com/efkan) - * fix(schema): allow setting `id` property after schema was created #5570 #5548 - * docs(populate): remove confusing _ from populate docs #5560 - * fix(connection): expose parsed uri fields (host, port, dbname) when using openUri() #5556 - * docs: added type boolean to options documentation #5547 [ndabAP](https://github.com/ndabAP) - * test: add test coverage for stopping/starting server #5524 - * fix(aggregate): pull read preference from schema by default #5522 - -4.11.7 / 2017-08-14 -=================== - * fix: correct properties when calling toJSON() on populated virtual #5544 #5442 [davidwu226](https://github.com/davidwu226) - * docs: fix spelling #5535 [et](https://github.com/et) - * fix(error): always set name before stack #5533 - * fix: add warning about running jest in jsdom environment #5532 #5513 #4943 - * fix(document): ensure overwriting a doc array cleans out individual docs #5523 - * fix(schema): handle creating arrays of single nested using type key #5521 - * fix: upgrade mongodb -> 2.2.31 to support user/pass options #5419 - -4.11.6 / 2017-08-07 -=================== - * fix: limiting number of async operations per time in insertMany #5529 [andresattler](https://github.com/andresattler) - * fix: upgrade mongodb -> 2.2.30 #5517 - * fix(browserDocument): prevent stack overflow caused by double-wrapping embedded doc save() in jest #5513 - * fix(document): clear single nested doc when setting to empty object #5506 - * fix(connection): emit reconnected and disconnected events correctly with useMongoClient #5498 - * fix(populate): ensure nested virtual populate gets set even if top-level property is null #5431 - -4.11.5 / 2017-07-30 -=================== - * docs: fix link to $lookup #5516 [TalhaAwan](https://github.com/TalhaAwan) - * fix: better parallelization for eachAsync #5502 [lchenay](https://github.com/lchenay) - * docs(document): copy docs for save from model to doc #5493 - * fix(document): handle dotted virtuals in toJSON output #5473 - * fix(populate): restore user-provided limit after mutating so cursor() works with populate limit #5468 - * fix(query): don't throw StrictModeError if geo query with upsert #5467 - * fix(populate): propagate readPreference from query to populate queries by default #5460 - * docs: warn not to use arrow functions for statics and methods #5458 - * fix(query): iterate over all condition keys for setDefaultsOnInsert #5455 - * docs(connection): clarify server/replset/mongos option deprecation with useMongoClient #5442 - -4.11.4 / 2017-07-23 -=================== - * fix: handle next() errors in `eachAsync()` #5486 [lchenay](https://github.com/lchenay) - * fix(schema): propagate runSettersOnQuery option to implicitly created schemas #5479 [https://github.com/ValYouW] - * fix(query): run castConditions() correctly in update ops #5477 - * fix(query): ensure castConditions called for findOne and findOneAnd* #5477 - * docs: clarify relationship between $lookup and populate #5475 [TalhaAwan](https://github.com/TalhaAwan) - * test: add coverage for arrays of arrays [zbjornson](https://github.com/zbjornson) - * fix(middleware): ensure that error handlers for save get doc as 2nd param #5466 - * fix: handle strict: false correctly #5454 #5453 [wookieb](https://github.com/wookieb) - * fix(query): apply schema excluded paths if only projection is a $slice #5450 - * fix(query): correct discriminator handling for schema `select: false` fields in schema #5448 - * fix(cursor): call next() in series when parallel option used #5446 - * chore: load bundled driver first to avoid packaging problem #5443 [prototypeme](https://github.com/prototypeme) - * fix(query): defer condition casting until final exec #5434 - * fix(aggregate): don't rely on mongodb aggregate to put a cursor in the callback #5394 - * docs(aggregate): add useMongooseAggCursor docs #5394 - * docs(middleware): clarify context for document, query, and model middleware #5381 - -4.11.3 / 2017-07-14 -=================== - * fix(connection): remove .then() before resolving to prevent infinite recursion #5471 - -4.11.2 / 2017-07-13 -=================== - * docs: fix comment typo in connect example #5435 [ConnorMcF](https://github.com/ConnorMcF) - * fix(update): correctly cast document array in update validators with exec() #5430 - * fix(connection): handle autoIndex with useMongoClient #5423 - * fix(schema): handle `type: [Array]` in schemas #5416 - * fix(timestamps): if overwrite is set and there's a $set, use $set instead of top-level update #5413 - * fix(document): don't double-validate deeply nested doc array elements #5411 - * fix(schematype): clone default objects so default not shared across object instances unless `shared` specified #5407 - * fix(document): reset down the nested subdocs when resetting parent doc #5406 - * fix: don't pass error arg twice to error handlers #5405 - * fix(connection): make openUri() return connection decorated with then() and catch() #5404 - * fix: enforce $set on an array must be an array #5403 - * fix(document): don't crash if calling `validateSync()` after overwriting doc array index #5389 - * fix(discriminator): ensure discriminator key doesn't count as user-selected field for projection #4629 - -4.11.1 / 2017-07-02 -=================== -* docs: populate virtuals fix justOne description #5427 [fredericosilva](https://github.com/fredericosilva) - * fix(connection): make sure to call onOpen in openUri() #5404 - * docs(query): justOne is actually single, and it default to false #5402 [zbjornson](https://github.com/zbjornson) - * docs: fix small typo in lib/schema.js #5398 #5396 [pjo336](https://github.com/pjo336) - * fix: emit remove on single nested subdocs when removing parent #5388 - * fix(update): handle update with defaults and overwrite but no update validators #5384 - * fix(populate): handle undefined refPath values in middle of array #5377 - * fix(document): ensure consistent setter context for single nested #5363 - * fix(query): support runSettersOnQuery as query option #5350 - -4.11.0 / 2017-06-25 -=================== - * feat(query): execute setters with query as context for `runSettersOnQuery` #5339 - * feat(model): add translateAliases function #5338 [rocketspacer](https://github.com/rocketspacer) - * feat(connection): add `useMongoClient` and `openUri` functions, deprecate current connect logic #5304 - * refactor(schema): make id virtual not access doc internals #5279 - * refactor: handle non-boolean lean #5279 - * feat(cursor): add addCursorFlag() support to query and agg cursors #4814 - * feat(cursor): add parallel option to eachAsync #4244 - * feat(schema): allow setting custom error constructor for custom validators #4009 - -4.10.8 / 2017-06-21 -=================== - * docs: fix small formatting typo on schematypes #5374 [gianpaj](https://github.com/gianpaj) - * fix(model): allow null as an _id #5370 - * fix(populate): don't throw async uncaught exception if model not found in populate #5364 - * fix: correctly cast decimals in update #5361 - * fix(error): don't use custom getter for ValidationError message #5359 - * fix(query): handle runSettersOnQuery in built-in _id setter #5351 - * fix(document): ensure consistent context for nested doc custom validators #5347 - -4.10.7 / 2017-06-18 -=================== - * docs(validation): show overriding custom validator error with 2nd cb arg #5358 - * fix: `parseOption` mutates user passed option map #5357 [igwejk](https://github.com/igwejk) - * docs: fix guide.jade typo #5356 [CalebAnderson2014](https://github.com/CalebAnderson2014) - * fix(populate): don't set populate virtual to ids when match fails #5336 - * fix(query): callback with cast error if remove and delete* args have a cast error #5323 - -4.10.6 / 2017-06-12 -=================== - * fix(cursor): handle custom model option for populate #5334 - * fix(populate): handle empty virtual populate with Model.populate #5331 - * fix(model): make ensureIndexes() run with autoIndex: false unless called internally #5328 #5324 #5317 - * fix: wait for all connections to close before resolving disconnect() promise #5316 - * fix(document): handle setting populated path with custom typeKey in schema #5313 - * fix(error): add toJSON helper to ValidationError so `message` shows up with JSON.stringify #5309 - * feat: add `getPromiseConstructor()` to prevent need for `mongoose.Promise.ES6` #5305 - * fix(document): handle conditional required with undefined props #5296 - * fix(model): clone options before inserting in save() #5294 - * docs(populate): clarify that multiple populate() calls on same path overwrite #5274 - -4.10.5 / 2017-06-06 -=================== - * chore: improve contrib guide for building docs #5312 - * fix(populate): handle init-ing nested virtuals properly #5311 - * fix(update): report update validator error if required path under single nested doc not set - * fix(schema): remove default validate pre hook that was causing issues with jest #4943 - -4.10.4 / 2017-05-29 -=================== - * chore: dont store test data in same directory #5303 - * chore: add data dirs to npmignore #5301 [Starfox64](https://github.com/Starfox64) - * docs(query): add docs about runSettersOnQuery #5300 - -4.10.3 / 2017-05-27 -=================== - * docs: correct inconsistent references to updateOne and replaceOne #5297 [dhritzkiv](https://github.com/dhritzkiv) - * docs: fix dropdowns in docs #5292 [nathanallen](https://github.com/nathanallen) - * docs: add description of alias option #5287 - * fix(document): prevent infinite loop if validating nested array #5282 - * fix(schema): correctly handle ref ObjectIds from different mongoose libs #5259 - * fix(schema): load child class methods after base class methods to allow override #5227 - -4.10.2 / 2017-05-22 -=================== - * fix: bump ms -> 2.0.0 and mquery -> 2.3.1 for minor security vulnerability #5275 - -4.10.1 / 2017-05-21 -=================== - * fix(aggregate): handle sorting by text score correctly #5258 - * fix(populate): handle doc.populate() with virtuals #5240 - * fix(schema): enforce that `_id` is never null #5236 - -4.10.0 / 2017-05-18 -=================== - * fix(schema): update clone method to include indexes #5268 [clozanosanchez](https://github.com/clozanosanchez) - * feat(schema): support aliases #5184 [rocketspacer](https://github.com/rocketspacer) - * feat(aggregate): add mongoose-specific aggregation cursor option #5145 - * refactor(model): make sharding into a plugin instead of core #5105 - * fix(document): make nested doc mongoose internals not enumerable again #5078 - * feat(model): pass params to pre hooks #5064 - * feat(timestamps): support already defined timestamp paths in schema #4868 - * feat(query): add runSettersOnQuery option #4569 - * fix(query): add strictQuery option that throws when not querying on field not in schema #4136 - * fix(update): more complete handling for overwrite option with update validators #3556 - * feat: support `unique: true` in arrays via the mongoose-unique-array plugin #3347 - * fix(model): always emit 'index', even if no indexes #3347 - * fix(schema): set unique indexes on primitive arrays #3347 - * feat(validation): include failed paths in error message and inspect output #3064 #2135 - * fix(model): return saved docs when create() fails #2190 - -4.9.10 / 2017-05-17 -=================== - * fix(connection): ensure callback arg to openSet() is handled properly #5249 - * docs: remove dead plugins repo and add content links #5247 - * fix(model): skip index build if connecting after model init and autoIndex false #5176 - -4.9.9 / 2017-05-13 -================== - * docs: correct value for Query#regex() #5230 - * fix(connection): don't throw if .catch() on open() promise #5229 - * fix(schema): allow update with $currentDate for updatedAt to succeed #5222 - * fix(model): versioning doesn't fail if version key undefined #5221 [basileos](https://github.com/basileos) - * fix(document): don't emit model error if callback specified for consistency with docs #5216 - * fix(document): handle errors in subdoc pre validate #5215 - -4.9.8 / 2017-05-07 -================== - * docs(subdocs): rewrite subdocs guide #5217 - * fix(document): avoid circular JSON if error in doc array under single nested subdoc #5208 - * fix(document): set intermediate empty objects for deeply nested undefined paths before path itself #5206 - * fix(schema): throw error if first param to schema.plugin() is not a function #5201 - * perf(document): major speedup in validating subdocs (50x in some cases) #5191 - -4.9.7 / 2017-04-30 -================== - * docs: fix typo #5204 [phutchins](https://github.com/phutchins) - * fix(schema): ensure correct path for deeply nested schema indexes #5199 - * fix(schema): make remove a reserved name #5197 - * fix(model): handle Decimal type in insertMany correctly #5190 - * fix: upgrade kareem to handle async pre hooks correctly #5188 - * docs: add details about unique not being a validator #5179 - * fix(validation): handle returning a promise with isAsync: true #5171 - -4.9.6 / 2017-04-23 -================== - * fix: update `parentArray` references when directly assigning document arrays #5192 [jhob](https://github.com/jhob) - * docs: improve schematype validator docs #5178 [milesbarr](https://github.com/milesbarr) - * fix(model): modify discriminator() class in place #5175 - * fix(model): handle bulkWrite updateMany casting #5172 [tzellman](https://github.com/tzellman) - * docs(model): fix replaceOne example for bulkWrite #5168 - * fix(document): don't create a new array subdoc when creating schema array #5162 - * fix(model): merge query hooks from discriminators #5147 - * fix(document): add parent() function to subdocument to match array subdoc #5134 - -4.9.5 / 2017-04-16 -================== - * fix(query): correct $pullAll casting of null #5164 [Sebmaster](https://github.com/Sebmaster) - * docs: add advanced schemas docs for loadClass #5157 - * fix(document): handle null/undefined gracefully in applyGetters() #5143 - * fix(model): add resolveToObject option for mapReduce with ES6 promises #4945 - -4.9.4 / 2017-04-09 -================== - * fix(schema): clone query middleware correctly #5153 #5141 [clozanosanchez](https://github.com/clozanosanchez) - * docs(aggregate): fix typo #5142 - * fix(query): cast .$ update to underlying array type #5130 - * fix(populate): don't mutate populate result in place #5128 - * fix(query): handle $setOnInsert consistent with $set #5126 - * docs(query): add strict mode option for findOneAndUpdate #5108 - -4.9.3 / 2017-04-02 -================== - * docs: document.js fixes for functions prepended with `$` #5131 [krmannix](https://github.com/krmannix) - * fix: Avoid exception on constructor check #5129 [monkbroc](https://github.com/monkbroc) - * docs(schematype): explain how to use `isAsync` with validate() #5125 - * docs(schematype): explain custom message with required function #5123 - * fix(populate): only apply refPath duplicate id optimization if not array #5114 - * fix(document): copy non-objects to doc when init() #5111 - * perf(populate): dont clone whole options every time #5103 - * feat(document): add isDirectSelected() to minimize isSelected() changes #5063 - * docs(schematypes): explain some subtleties with arrays #5059 - -4.9.2 / 2017-03-26 -================== - * fix(discriminator): handle class names consistently #5104 - * fix(schema): make clone() work with reusing discriminator schemas #5098 - * fix(querycursor): run pre find hooks with .cursor() #5096 - * fix(connection): throw error if username:password includes @ or : #5091 - * fix(timestamps): handle overwriting createdAt+updatedAt consistently #5088 - * fix(document): ensure subdoc post save runs after parent save #5085 - * docs(model): improve update docs #5076 [bertolo1988](https://github.com/bertolo1988) - -4.9.1 / 2017-03-19 -================== - * fix(query): handle $type for arrays #5080 #5079 [zoellner](https://github.com/zoellner) - * fix(model): handle ordered param for `insertMany` validation errors #5072 [sjorssnoeren](https://github.com/sjorssnoeren) - * fix(populate): avoid duplicate ids in dynref queries #5054 - * fix(timestamps): dont set timestamps in update if user set it #5045 - * fix(update): dont double-call setters on arrays #5041 - * fix: upgrade driver -> 2.2.25 for jest fix #5033 - * fix(model): get promise each time save() is called rather than once #5030 - * fix(connection): make connect return value consistent #5006 - -4.9.0 / 2017-03-13 -================== - * feat(document): return this from `depopulate()` #5027 - * fix(drivers): stop emitting timeouts as errors #5026 - * feat(schema): add a clone() function for schemas #4983 - * feat(query): add rawResult option to replace passRawResult, deprecate passRawResult #4977 #4925 - * feat(schematype): support isAsync validator option and handle returning promises from validators, deprecate implicit async validators #4290 - * feat(query): add `replaceOne()`, `deleteOne()`, `deleteMany()` #3998 - * feat(model): add `bulkWrite()` #3998 - -4.8.7 / 2017-03-12 -================== - * fix(model): if last arg in spread is falsy, treat it as a callback #5061 - * fix(document): use $hook instead of hook to enable 'hook' as a path name #5047 - * fix(populate): dont select foreign field if parent field is selected #5037 - * fix(populate): handle passing no args to query.populate #5036 - * fix(update): use correct method for casting nested arrays #5032 - * fix(discriminator): handle array discriminators when casting $push #5009 - -4.8.6 / 2017-03-05 -================== - * docs(document): remove text that implies that transform is false by default #5023 - * fix(applyHooks): dont wrap a function if it is already wrapped #5019 - * fix(document): ensure nested docs' toObject() clones #5008 - -4.8.5 / 2017-02-25 -================== - * fix: check for empty schemaPath before accessing property $isMongooseDocumentArray #5017 [https://github.com/randyhoulahan](randyhoulahan) - * fix(discriminators): handle create() and push() for embedded discriminators #5001 - * fix(querycursor): ensure close emitted after last data event #4998 - * fix(discriminators): remove fields not selected in child when querying by base model #4991 - -4.8.4 / 2017-02-19 -================== - * docs(discriminators): explain embedded discriminators #4997 - * fix(query): fix TypeError when findOneAndUpdate errors #4990 - * fix(update): handle nested single embedded in update validators correctly #4989 - * fix(browser): make browser doc constructor not crash #4987 - -4.8.3 / 2017-02-15 -================== - * chore: upgrade mongodb driver -> 2.2.24 - * docs(connections): addd some details about callbacks #4986 - * fix: ensure class is created with new keyword #4972 #4947 [benhjames](https://github.com/benhjames) - * fix(discriminator): add applyPluginsToDiscriminators option #4965 - * fix(update): properly cast array subdocs when casting update #4960 - * fix(populate): ensure foreign field is selected for virtual populate #4959 - * docs(query): document some query callback params #4949 - * fix(document): ensure errors in validators get caught #2185 - -4.8.2 / 2017-02-10 -================== - * fix(update): actually run validators on addToSet #4953 - * fix(update): improve buffer error handling #4944 [ValYouW](https://github.com/ValYouW) - * fix(discriminator): handle subclassing with loadClass correctly #4942 - * fix(query): allow passing Map to sort() #4941 - * fix(document): handle setting discriminator doc #4935 - * fix(schema): return correct value from pre init hook #4928 - * fix(query): ensure consistent params in error handlers if pre hook errors #4927 - -4.8.1 / 2017-01-30 -================== - * fix(query): handle $exists for arrays and embedded docs #4937 - * fix(query): handle passing string to hint() #4931 - -4.8.0 / 2017-01-28 -================== - * feat(schema): add saveErrorIfNotFound option and $where property #4924 #4004 - * feat(query): add $in implicitly if passed an array #4912 [QuotableWater7](https://github.com/QuotableWater7) - * feat(aggregate): helper for $facet #4904 [varunjayaraman](https://github.com/varunjayaraman) - * feat(query): add collation method #4839 - * feat(schema): propogate strict option to implicit array subschemas #4831 [dkrosso](https://github.com/dkrosso) - * feat(aggregate): add helper for graphLookup #4819 [varunjayaraman](https://github.com/varunjayaraman) - * feat(types): support Decimal128 #4759 - * feat(aggregate): add eachAsync() to aggregate cursor #4300 - * feat(query): add updateOne and updateMany #3997 - * feat(model): support options for insertMany #3893 - * fix(document): run validation on single nested docs if not directly modified #3884 - * feat(model): use discriminator constructor based on discriminatorKey in create() #3624 - * feat: pass collection as context to debug function #3261 - * feat(query): support push and addToSet for update validators #2933 - * perf(document): refactor registerHooksFromSchema so hooks are defined on doc prototype #2754 - * feat(types): add discriminator() function to doc arrays #2723 #1856 - * fix(populate): return an error if sorting underneath a doc array #2202 - -4.7.9 / 2017-01-27 -================== - * fix(query): handle casting $exists under $not #4933 - * chore: upgrade mongodb -> 2.2.22 re: #4931 - -4.7.8 / 2017-01-23 -================== - * fix(populate): better handling for virtual populate under arrays #4923 - * docs: upgrade contributors count #4918 [AdamZaczek](https://github.com/AdamZaczek) - * fix(query): don't set nested path default if setting parent path #4911 - * docs(promise): add missing bracket #4907 - * fix(connection): ensure error handling is consistently async #4905 - * fix: handle authMechanism in query string #4900 - * fix(document): ensure error handlers run for validate #4885 - -4.7.7 / 2017-01-15 -================== - * fix(utils): don't crash if to[key] is null #4881 - * fix: upgrade mongodb -> 2.2.21 #4867 - * fix: add a toBSON to documents for easier querying #4866 - * fix: suppress bluebird warning #4854 [davidwu226](https://github.com/davidwu226) - * fix(populate): handle nested virtuals in virtual populate #4851 - -4.7.6 / 2017-01-02 -================== - * fix(model): allow passing non-array to insertMany #4846 - * fix(populate): use base model name if no discriminator for backwards compat #4843 - * fix: allow internal validate callback to be optional #4842 [arciisine](https://github.com/arciisine) - * fix(document): don't skip pointCut if save not defined (like in browser doc) #4841 - * chore: improve benchmarks #4838 [billouboq](https://github.com/billouboq) - * perf: remove some unused parameters #4837 [billouboq](https://github.com/billouboq) - * fix(query): don't call error handler if passRawResult is true and no error occurred #4836 - -4.7.5 / 2016-12-26 -================== - * docs(model): fix spelling mistake #4828 [paulinoj](https://github.com/paulinoj) - * fix(aggregate): remove unhandled rejection when using aggregate.then() #4824 - * perf: remove try/catch that kills optimizer #4821 - * fix(model): handles populating with discriminators that may not have a ref #4817 - * fix(document): handle setting array of discriminators #3575 - -4.7.4 / 2016-12-21 -================== - * docs: fix typo #4810 [GEEKIAM](https://github.com/GEEKIAM) - * fix(query): timestamps with $push + $each #4805 - * fix(document): handle buffers correctly in minimize #4800 - * fix: don't disallow overwriting default and cast fns #4795 [pdspicer](https://github.com/pdspicer) - * fix(document): don't convert single nested docs to POJOs #4793 - * fix(connection): handle reconnect to replica set correctly #4972 [gfzabarino](https://github.com/gfzabarino) - -4.7.3 / 2016-12-16 -================== - * fix: upgrade mongodb driver -> 2.2.16 for several bug fixes and 3.4 support #4799 - * fix(model): ensure discriminator key is correct for child schema on discriminator #4790 - * fix(document): handle mark valid in subdocs correctly #4778 - * fix(query): check for objects consistently #4775 - -4.7.2 / 2016-12-07 -================== - * test(populate): fix justOne test #4772 [cblanc](https://github.com/cblanc) - * chore: fix benchmarks #4769 [billouboq](https://github.com/billouboq) - * fix(document): handle setting subdoc to null after setting parent doc #4766 - * fix(query): support passRawResult with lean #4762 #4761 [mhfrantz](https://github.com/mhfrantz) - * fix(query): throw StrictModeError if upsert with nonexisting field in condition #4757 - * test: fix a couple of sort tests #4756 [japod](https://github.com/japod) - * chore: upgrade mongodb driver -> 2.2.12 #4753 [mdlavin](https://github.com/mdlavin) - * fix(query): handle update with upsert and overwrite correctly #4749 - -4.7.1 / 2016-11-30 -================== - * fix(schema): throw error if you use prototype as a schema path #4746 - * fix(schema): throw helpful error if you define a virtual with the same path as a real path #4744 - * fix(connection): make createConnection not throw rejected promises #4742 - * fix(populate): allow specifiying options in model schema #4741 - * fix(document): handle selected nested elements with defaults #4739 - * fix(query): add model to cast error if possible #4729 - * fix(query): handle timestamps with overwrite #4054 - -4.7.0 / 2016-11-23 -================== - * docs: clean up schematypes #4732 [kidlj](https://github.com/kidlj) - * perf: only get stack when necessary with VersionError #4726 [Sebmaster](https://github.com/Sebmaster) - * fix(query): ensure correct casting when setting array element #4724 - * fix(connection): ensure db name gets set when you pass 4 params #4721 - * fix: prevent TypeError in node v7 #4719 #4706 - * feat(document): support .set() on virtual subpaths #4716 - * feat(populate): support populate virtuals on nested schemas #4715 - * feat(querycursor): support transform option and .map() #4714 #4705 [cblanc](https://github.com/cblanc) - * fix(document): dont set defaults on not-selected nested paths #4707 - * fix(populate): don't throw if empty string passed to populate #4702 - * feat(model): add `loadClass()` function for importing schema from ES6 class #4668 [rockmacaca](https://github.com/rockmacaca) - -4.6.8 / 2016-11-14 -================== - * fix(querycursor): clear stack when iterating onto next doc #4697 - * fix: handle null keys in validation error #4693 #4689 [arciisine](https://github.com/arciisine) - * fix(populate): handle pre init middleware correctly with populate virtuals #4683 - * fix(connection): ensure consistent return value for open and openSet #4659 - * fix(schema): handle falsy defaults for arrays #4620 - -4.6.7 / 2016-11-10 -================== - * fix(document): only invalidate in subdoc if using update validators #4681 - * fix(document): don't create subdocs when excluded in projection #4669 - * fix(document): ensure single embedded schema validator runs with correct context #4663 - * fix(document): make sure to depopulate top level for sharding #4658 - * fix(connection): throw more helpful error when .model() called incorrectly #4652 - * fix(populate): throw more descriptive error when trying to populate a virtual that doesn't have proper options #4602 - * fix(document): ensure subtype gets set properly when saving with a buffer id #4506 - * fix(query): handle setDefaultsOnInsert with defaults on doc arrays #4456 - * fix(drivers): make debug output better by calling toBSON() #4356 - -4.6.6 / 2016-11-03 -================== - * chore: upgrade deps #4674 [TrejGun](https://github.com/TrejGun) - * chore: run tests on node v7 #4673 [TrejGun](https://github.com/TrejGun) - * perf: make setDefaultsOnInsert more efficient if upsert is off #4672 [CamHenlin](https://github.com/CamHenlin) - * fix(populate): ensure document array is returned #4656 - * fix(query): cast doc arrays with positionals correctly for update #4655 - * fix(document): ensure single nested doc validators run with correct context #4654 - * fix: handle reconnect failed error in new version of driver #4653 [loris](https://github.com/loris) - * fix(populate): if setting a populated doc, take its id #4632 - * fix(populate): handle populated virtuals in init #4618 - -4.6.5 / 2016-10-23 -================== - * docs: fix grammar issues #4642 #4640 #4639 [silvermanj7](https://github.com/silvermanj7) - * fix(populate): filter out nonexistant values for dynref #4637 - * fix(query): handle $type as a schematype operator #4632 - * fix(schema): better handling for uppercase: false and lowercase: false #4622 - * fix(query): don't run transforms on updateForExec() #4621 - * fix(query): handle id = 0 in findById #4610 - * fix(query): handle buffers in mergeClone #4609 - * fix(document): handle undefined with conditional validator for validateSync #4607 - * fix: upgrade to mongodb driver 2.2.11 #4581 - * docs(schematypes): clarify schema.path() #4518 - * fix(query): ensure path is defined before checking in timestamps #4514 - * fix(model): set version key in upsert #4505 - * fix(document): never depopulate top-level doc #3057 - * refactor: ensure sync for setting non-capped collections #2690 - -4.6.4 / 2016-10-16 -================== - * fix(query): cast $not correctly #4616 #4592 [prssn](https://github.com/prssn) - * fix: address issue with caching global plugins #4608 #4601 [TrejGun](https://github.com/TrejGun) - * fix(model): make sure to depopulate in insertMany #4590 - * fix(model): buffer autoIndex if bufferCommands disabled #4589 - * fix(populate): copy ids array before modifying #4585 - * feat(schema): add retainKeyOrder prop #4542 - * fix(document): return isModified true for children of direct modified paths #4528 - * fix(connection): add dropDatabase() helper #4490 - * fix(model): add usePushEach option for schemas #4455 - * docs(connections): add some warnings about buffering #4413 - * fix: add ability to set promise implementation in browser #4395 - -4.6.3 / 2016-10-05 -================== - * fix(document): ensure single nested docs get initialized correctly when setting nested paths #4578 - * fix: turn off transforms when writing nested docs to db #4574 - * fix(document): don't set single nested subdocs to null when removing parent doc #4566 - * fix(model): ensure versionKey gets set in insertMany #4561 - * fix(schema): handle typeKey in arrays #4548 - * feat(schema): set $implicitlyCreated on schema if created by interpretAsType #4443 - -4.6.2 / 2016-09-30 -================== - * chore: upgrade to async 2.0.1 internally #4579 [billouboq](https://github.com/billouboq) - * fix(types): ensure nested single doc schema errors reach update validators #4557 #4519 - * fix(connection): handle rs names with leading numbers (muri 1.1.1) #4556 - * fix(model): don't throw if method name conflicts with Object.prototype prop #4551 - * docs: fix broken link #4544 [VFedyk](https://github.com/VFedyk) - * fix: allow overwriting model on mongoose singleton #4541 [Nainterceptor](https://github.com/Nainterceptor) - * fix(document): don't use init: true when building doc defaults #4540 - * fix(connection): use replSet option if replset not specified #4535 - * fix(query): cast $not objects #4495 - -4.6.1 / 2016-09-20 -================== - * fix(query): improve handling of $not with $elemMatch #4531 #3719 [timbowhite](https://github.com/timbowhite) - * fix: upgrade mongodb -> 2.2.10 #4517 - * chore: fix webpack build issue #4512 [saiichihashimoto](https://github.com/saiichihashimoto) - * fix(query): emit error on next tick when exec callback errors #4500 - * test: improve test case #4496 [isayme](https://github.com/isayme) - * fix(schema): use same check for array types and top-level types #4493 - * style: fix indentation in docs #4489 [dhurlburtusa](https://github.com/dhurlburtusa) - * fix(schema): expose original object passed to constructor #4486 - * fix(query): handle findOneAndUpdate with array of arrays #4484 #4470 [fedotov](https://github.com/fedotov) - * feat(document): add $ignore to make a path ignored #4480 - * fix(query): properly handle setting single embedded in update #4475 #4466 #4465 - * fix(updateValidators): handle single nested schema subpaths correctly #4479 - * fix(model): throw handy error when method name conflicts with property name #4475 - * fix(schema): handle .set() with array field #4472 - * fix(query): check nested path when avoiding double-validating Mixed #4441 - * fix(schema): handle calling path.trim() with no args correctly #4042 - -4.6.0 / 2016-09-02 -================== - * docs(document): clarify the findById and findByIdAndUpdate examples #4471 [mdcanham](https://github.com/mdcanham) - * docs(schematypes): add details re: options #4452 - * docs(middleware): add docs for insertMany hooks #4451 - * fix(schema): create new array when copying from existing object to preserve change tracking #4449 - * docs: fix typo in index.jade #4448 - * fix(query): allow array for populate options #4446 - * fix(model): create should not cause unhandle reject promise #4439 - * fix: upgrade to mongodb driver 2.2.9 #4363 #4341 #4311 (see [comments here](https://github.com/mongodb/js-bson/commit/aa0b54597a0af28cce3530d2144af708e4b66bf0#commitcomment-18850498) if you use node 0.10) - -4.5.10 / 2016-08-23 -=================== - * docs: fix typo on documents.jade #4444 [Gabri3l](https://github.com/Gabri3l) - * chore: upgrade mocha to 3.0.2 #4437 [TrejGun](https://github.com/TrejGun) - * fix: subdocuments causing error with parent timestamp on update #4434 [dyang108](https://github.com/dyang108) - * fix(query): don't crash if timestamps on and update doesn't have a path #4425 #4424 #4418 - * fix(query): ensure single nested subdoc is hydrated when running update validators #4420 - * fix(query): cast non-$geometry operators for $geoWithin #4419 - * docs: update contributor count #4415 [AdamZaczek](https://github.com/AdamZaczek) - * docs: add more clarification re: the index event #4410 - * fix(document): only skip modifying subdoc path if parent is direct modified #4405 - * fix(schema): throw cast error if provided date invalid #4404 - * feat(error): use util.inspect() so CastError never prints "[object Object]" #4398 - * fix(model): dont error if the discriminator key is unchanged #4387 - * fix(query): don't throw unhandled rejection with bluebird when using cbs #4379 - -4.5.9 / 2016-08-14 -================== - * docs: add mixed schema doc for Object literal #4400 [Kikobeats](https://github.com/Kikobeats) - * fix(query): cast $geoWithin and convert mongoose objects to POJOs before casting #4392 - * fix(schematype): dont cast defaults without parent doc #4390 - * fix(query): disallow passing empty string to findOne() #4378 - * fix(document): set single nested doc isNew correctly #4369 - * fix(types): checks field name correctly with nested arrays and populate #4365 - * fix(drivers): make debug output copy-pastable into mongodb shell #4352 - * fix(services): run update validators on nested paths #4332 - * fix(model): handle typeKey with discriminators #4339 - * fix(query): apply timestamps to child schemas when explicitly specified in update #4049 - * fix(schema): set prefix as nested path with add() #1730 - -4.5.8 / 2016-08-01 -================== - * fix(model): make changing the discriminator key cause a cast error #4374 - * fix(query): pass projection fields to cursor #4371 #4342 [Corei13](https://github.com/Corei13) - * fix(document): support multiple paths for isModified #4370 [adambuczynski](https://github.com/adambuczynski) - * fix(querycursor): always cast fields before returning cursor #4355 - * fix(query): support projection as alias for fields in findOneAndUpdate #4315 - * fix(schema): treat index false + unique false as no index #4304 - * fix(types): dont mark single nested subpath as modified if whole doc already modified #4224 - -4.5.7 / 2016-07-25 -================== - * fix(document): ensure no unhandled rejections if callback specified for save #4364 - -4.5.6 / 2016-07-23 -================== - * fix(schema): don't overwrite createdAt if it isn't selected #4351 [tusbar](https://github.com/tusbar) - * docs(api): fix link to populate() and add a new one from depopulate() #4345 [Delapouite](https://github.com/Delapouite) - * fix(types): ownerDocument() works properly with single nested docs #4344 [vichle](https://github.com/vichle) - * fix(populate): dont use findOne when justOne option set #4329 - * fix(document): dont trigger .then() deprecated warning when calling doc.remove() #4291 - * docs(connection): add promiseLibrary option #4280 - * fix(plugins): apply global plugins to subschemas #4271 - * fix(model): ensure `ensureIndex()` never calls back in the same tick #4246 - * docs(schema): improve post hook docs on schema #4238 - -4.5.5 / 2016-07-18 -================== - * fix(document): handle setting root to empty obj if minimize false #4337 - * fix: downgrade to mongodb 2.1.18 #4335 #4334 #4328 #4323 - * perf(types): remove defineProperty usage in documentarray #4333 - * fix(query): correctly pass model in .toConstructor() #4318 - * fix(services): avoid double-validating mixed types with update validators #4305 - * docs(middleware): add docs describing error handling middleware #4229 - * fix(types): throw correct error when invalidating doc array #3602 - -4.5.4 / 2016-07-11 -================== - * fix(types): fix removing embedded documents #4309 [RoCat](https://github.com/RoCat) - * docs: various docs improvements #4302 #4294 [simonxca](https://github.com/simonxca) - * fix: upgrade mongodb -> 2.1.21 #4295 #4202 [RoCat](https://github.com/RoCat) - * fix(populate): convert single result to array for virtual populate because of lean #4288 - * fix(populate): handle empty results for populate virtuals properly #4285 #4284 - * fix(query): dont cast $inc to number if type is long #4283 - * fix(types): allow setting single nested doc to null #4281 - * fix(populate): handle deeply nested virtual populate #4278 - * fix(document): allow setting empty obj if strict mode is false #4274 - * fix(aggregate): allow passing obj to .unwind() #4239 - * docs(document): add return statements to transform examples #1963 - -4.5.3 / 2016-06-30 -================== - * fix(query): pass correct options to QueryCursor #4277 #4266 - * fix(querycursor): handle lean option correctly #4276 [gchudnov](https://github.com/gchudnov) - * fix(document): fix error handling when no error occurred #4275 - * fix(error): use strict mode for version error #4272 - * docs(populate): fix crashing compilation for populate.jade #4267 - * fix(populate): support `justOne` option for populate virtuals #4263 - * fix(populate): ensure model param gets used for populate virtuals #4261 #4243 - * fix(querycursor): add ability to properly close the cursor #4258 - * docs(model): correct link to Document #4250 - * docs(populate): correct path for refPath populate #4240 - * fix(document): support validator.isEmail as validator #4064 - -4.5.2 / 2016-06-24 -================== - * fix(connection): add checks for collection presence for `onOpen` and `onClose` #4259 [nodkz](https://github.com/nodkz) - * fix(cast): allow strings for $type operator #4256 - * fix(querycursor): support lean() #4255 [pyramation](https://github.com/pyramation) - * fix(aggregate): allow setting noCursorTimeout option #4241 - * fix(document): handle undefined for Array.pull #4222 [Sebmaster](https://github.com/Sebmaster) - * fix(connection): ensure promise.catch() catches initial connection error #4135 - * fix(document): show additional context for VersionError #2633 - -4.5.1 / 2016-06-18 -================== - * fix(model): ensure wrapped insertMany() returns a promise #4237 - * fix(populate): dont overwrite populateVirtuals when populating multiple paths #4234 - * docs(model): clarify relationship between create() and save() #4233 - * fix(types): handle option param in subdoc remove() #4231 [tdebarochez](https://github.com/tdebarochez) - * fix(document): dedupe modified paths #4226 #4223 [adambuczynski](https://github.com/adambuczynski) - * fix(model): don't modify user-provided options object #4221 - * fix(document): handle setting nested path to empty object #4218 #4182 - * fix(document): clean subpaths when removing single nested #4216 - * fix(document): don't force transform on subdocs with inspect #4213 - * fix(error): allow setting .messages object #4207 - -4.5.0 / 2016-06-13 -================== - * feat(query): added Query.prototype.catch() #4215 #4173 [adambuczynski](https://github.com/adambuczynski) - * feat(query): add Query.prototype.cursor() as a .stream() alternative #4117 #3637 #1907 - * feat(document): add markUnmodified() function #4092 [vincentcr](https://github.com/vincentcr) - * feat(aggregate): convert aggregate object to a thenable #3995 #3946 [megagon](https://github.com/megagon) - * perf(types): remove defineProperties call for array (**Note:** Because of this, a mongoose array will no longer `assert.deepEqual()` a plain old JS array) #3886 - * feat(model): add hooks for insertMany() #3846 - * feat(schema): add support for custom query methods #3740 #2372 - * feat(drivers): emit error on 'serverClosed' because that means that reconnect failed #3615 - * feat(model): emit error event when callback throws exception #3499 - * feat(model): inherit options from discriminator base schema #3414 #1818 - * feat(populate): expose mongoose-populate-virtuals inspired populate API #2562 - * feat(document): trigger remove hooks on subdocs when removing parent #2348 - * feat(schema): add support for express-style error handling middleware #2284 - * fix(model): disallow setting discriminator key #2041 - * feat(schema): add support for nested arrays #1361 - -4.4.20 / 2016-06-05 -=================== - * docs: clarify command buffering when using driver directly #4195 - * fix(promise): correct broken mpromise .catch() #4189 - * fix(document): clean modified subpaths when set path to empty obj #4182 - * fix(query): support minDistance with query casting and `.near()` #4179 - * fix(model): remove unnecessary .save() promise #4177 - * fix(schema): cast all valid ObjectId strings to object ids #3365 - * docs: remove unclear "unsafe" term in query docs #3282 - -4.4.19 / 2016-05-21 -=================== - * fix(model): handle insertMany if timestamps not set #4171 - -4.4.18 / 2016-05-21 -=================== - * docs: add missing period #4170 [gitname](https://github.com/gitname) - * docs: change build badge to svg #4158 [a0viedo](https://github.com/a0viedo) - * fix(model): update timestamps when setting `createdAt` #4155 - * fix(utils): make sure to require in document properly #4152 - * fix(model): throw overwrite error when discriminator name conflicts #4148 - -4.4.17 / 2016-05-13 -=================== - * docs: remove repetition in QueryStream docs #4147 [hugoabonizio](https://github.com/hugoabonizio) - * fix(document): dont double-validate doc array elements #4145 - * fix(document): call required function with correct scope #4142 [JedWatson](https://github.com/JedWatson) - -4.4.16 / 2016-05-09 -=================== - * refactor(document): use function reference #4133 [dciccale](https://github.com/dciccale) - * docs(querystream): clarify `destroy()` and close event #4126 [AnthonyCC](https://github.com/AnthonyCC) - * test: make before hook fail fast if it can't connect #4121 - * docs: add description of CastError constructor params #4120 - * fix(schematype): ensure single embedded defaults have $parent #4115 - * fix(document): mark nested paths for validation #4111 - * fix(schema): make sure element is always a subdoc in doc array validation #3816 - -4.4.15 / 2016-05-06 -=================== - * fix(schema): support overwriting array default #4109 - * fix(populate): assign values when resolving each populate #4104 - * fix(aggregate): dont send async option to server #4101 - * fix(model): ensure isNew set to false after insertMany #4099 - * fix(connection): emit on error if listeners and no callback #4098 - * fix(document): treat required fn that returns false as required: false #4094 - -4.4.14 / 2016-04-27 -=================== - * fix: upgrade mongodb -> 2.1.18 #4102 - * feat(connection): allow setting mongos as a uri query param #4093 #4035 [burtonjc](https://github.com/burtonjc) - * fix(populate): make sure to use correct assignment order for each model #4073 - * fix(schema): add complete set of geospatial operators for single embedded subdocs #4014 - -3.8.40 / 2016-04-24 -=================== - * upgraded; mquery -> 1.10.0 #3989 - -4.4.13 / 2016-04-21 -=================== - * docs: add docs favicons #4082 [robertjustjones](https://github.com/robertjustjones) - * docs(model): correct Model.remove() return value #4075 [Jokero](https://github.com/Jokero) - * fix(query): add $geoWithin query casting for single embedded docs #4044 - * fix(schema): handle setting trim option to falsy #4042 - * fix(query): handle setDefaultsOnInsert with empty update #3835 - -4.4.12 / 2016-04-08 -=================== - * docs(query): document context option for update and findOneAndUpdate #4055 - * docs(query): correct link to $geoWithin docs #4050 - * fix(project): upgrade to mongodb driver 2.1.16 #4048 [schmalliso](https://github.com/schmalliso) - * docs(validation): fix validation docs #4028 - * fix(types): improve .id() check for document arrays #4011 - * fix(query): remove premature return when using $rename #3171 - * docs(connection): clarify relationship between models and connections #2157 - -4.4.11 / 2016-04-03 -=================== - * fix: upgrade to mongodb driver 2.1.14 #4036 #4030 #3945 - * fix(connection): allow connecting with { mongos: true } to handle query params #4032 [burtonjc](https://github.com/burtonjc) - * docs(connection): add autoIndex example #4026 [tilleps](https://github.com/tilleps) - * fix(query): handle passRawResult option when zero results #4023 - * fix(populate): clone options before modifying #4022 - * docs: add missing whitespace #4019 [chenxsan](https://github.com/chenxsan) - * chore: upgrade to ESLint 2.4.0 #4015 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix(types): single nested subdocs get ids by default #4008 - * chore(project): add dependency status badge #4007 [Maheshkumar-Kakade](http://github.com/Maheshkumar-Kakade) - * fix: make sure timestamps don't trigger unnecessary updates #4005 #3991 [tommarien](https://github.com/tommarien) - * fix(document): inspect inherits schema options #4001 - * fix(populate): don't mark populated path as modified if setting to object w/ same id #3992 - * fix(document): support kind argument to invalidate #3965 - -4.4.10 / 2016-03-24 -=================== - * fix(document): copy isNew when copying a document #3982 - * fix(document): don't override defaults with undefined keys #3981 - * fix(populate): merge multiple deep populate options for the same path #3974 - -4.4.9 / 2016-03-22 -================== - * fix: upgrade mongodb -> 2.1.10 re https://jira.mongodb.org/browse/NODE-679 #4010 - * docs: add syntax highlighting for acquit examples #3975 - -4.4.8 / 2016-03-18 -================== - * docs(aggregate): clarify promises #3990 [megagon](https://github.com/megagon) - * fix: upgrade mquery -> 1.10 #3988 [matskiv](https://github.com/matskiv) - * feat(connection): 'all' event for repl sets #3986 [xizhibei](https://github.com/xizhibei) - * docs(types): clarify Array.pull #3985 [seriousManual](https://github.com/seriousManual) - * feat(query): support array syntax for .sort() via mquery 1.9 #3980 - * fix(populate): support > 3 level nested populate #3973 - * fix: MongooseThenable exposes connection correctly #3972 - * docs(connection): add note about reconnectTries and reconnectInterval #3969 - * feat(document): invalidate returns the new validationError #3964 - * fix(query): .eq() as shorthand for .equals #3953 [Fonger](https://github.com/Fonger) - * docs(connection): clarify connection string vs passed options #3941 - * docs(query): select option for findOneAndUpdate #3933 - * fix(error): ValidationError.properties no longer enumerable #3925 - * docs(validation): clarify how required validators work with nested schemas #3915 - * fix: upgrade mongodb driver -> 2.1.8 to make partial index errors more sane #3864 - -4.4.7 / 2016-03-11 -================== - * fix(query): stop infinite recursion caused by merging a mongoose buffer #3961 - * fix(populate): handle deep populate array -> array #3954 - * fix(schema): allow setting timestamps with .set() #3952 #3951 #3907 [Fonger](https://github.com/Fonger) - * fix: MongooseThenable doesn't overwrite constructors #3940 - * fix(schema): don't cast boolean to date #3935 - * fix(drivers): support sslValidate in connection string #3929 - * fix(types): correct markModified() for single nested subdocs #3910 - * fix(drivers): catch and report any errors that occur in driver methods #3906 - * fix(populate): get subpopulate model correctly when array under nested #3904 - * fix(document): allow fields named 'pre' and 'post' #3902 - * docs(query): clarify runValidators and setDefaultsOnInsert options #3892 - * docs(validation): show how to use custom required messages in schema #2616 - -4.4.6 / 2016-03-02 -================== - * fix: upgrade mongodb driver to 2.1.7 #3938 - * docs: fix plugins link #3917 #3909 [fbertone](https://github.com/fbertone) - * fix(query): sort+select with count works #3914 - * fix(query): improve mergeUpdate's ability to handle nested docs #3890 - -4.4.5 / 2016-02-24 -================== - * fix(query): ability to select a length field (upgrade to mquery 1.7.0) #3903 - * fix: include nested CastError as reason for array CastError #3897 [kotarou3](https://github.com/kotarou3) - * fix(schema): check for doc existence before taking fields #3889 - * feat(schema): useNestedStrict option to take nested strict mode for update #3883 - * docs(validation): clarify relationship between required and checkRequired #3822 - * docs(populate): dynamic reference docs #3809 - * docs: expand dropdown when clicking on file name #3807 - * docs: plugins.mongoosejs.io is up #3127 - * fix(schema): ability to add a virtual with same name as removed path #2398 - -4.4.4 / 2016-02-17 -================== - * fix(schema): handle field selection when casting single nested subdocs #3880 - * fix(populate): populating using base model with multiple child models in result #3878 - * fix: ability to properly use return value of `mongoose.connect()` #3874 - * fix(populate): dont hydrate populated subdoc if lean option set #3873 - * fix(connection): dont re-auth if already connected with useDb #3871 - * docs: cover how to set underlying driver's promise lib #3869 - * fix(document): handle conflicting names in validation errors with subdocs #3867 - * fix(populate): set undefined instead of null consistently when populate couldn't find results #3859 - * docs: link to `execPopulate()` in `doc.populate()` docs #3836 - * docs(plugin): link to the `mongoose.plugin()` function #3732 - -4.4.3 / 2016-02-09 -================== - * fix: upgrade to mongodb 2.1.6 to remove kerberos log output #3861 #3860 [cartuchogl](https://github.com/cartuchogl) - * fix: require('mongoose') is no longer a pseudo-promise #3856 - * fix(query): update casting for single nested docs #3820 - * fix(populate): deep populating multiple paths with same options #3808 - * docs(middleware): clarify save/validate hook order #1149 - -4.4.2 / 2016-02-05 -================== - * fix(aggregate): handle calling .cursor() with no options #3855 - * fix: upgrade mongodb driver to 2.1.5 for GridFS memory leak fix #3854 - * docs: fix schematype.html conflict #3853 #3850 #3843 - * fix(model): bluebird unhandled rejection with ensureIndexes() on init #3837 - * docs: autoIndex option for createConnection #3805 - -4.4.1 / 2016-02-03 -================== - * fix: linting broke some cases where we use `== null` as shorthand #3852 - * docs: fix up schematype.html conflict #3848 #3843 [mynameiscoffey](https://github.com/mynameiscoffey) - * fix: backwards breaking change with `.connect()` return value #3847 - * docs: downgrade dox and highlight.js to fix docs build #3845 - * docs: clean up typo #3842 [Flash-](https://github.com/Flash-) - * fix(document): storeShard handles undefined values #3841 - * chore: more linting #3838 [TrejGun](https://github.com/TrejGun) - * fix(schema): handle `text: true` as a way to declare a text index #3824 - -4.4.0 / 2016-02-02 -================== - * docs: fix expireAfterSeconds index option name #3831 [Flash-](https://github.com/Flash-) - * chore: run lint after test #3829 [ChristianMurphy](https://github.com/ChristianMurphy) - * chore: use power-assert instead of assert #3828 [TrejGun](https://github.com/TrejGun) - * chore: stricter lint #3827 [TrejGun](https://github.com/TrejGun) - * feat(types): casting moment to date #3813 [TrejGun](https://github.com/TrejGun) - * chore: comma-last lint for test folder #3810 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix: upgrade async mpath, mpromise, muri, and sliced #3801 [TrejGun](https://github.com/TrejGun) - * fix(query): geo queries now return proper ES2015 promises #3800 [TrejGun](https://github.com/TrejGun) - * perf(types): use `Object.defineProperties()` for array #3799 [TrejGun](https://github.com/TrejGun) - * fix(model): mapReduce, ensureIndexes, remove, and save properly return ES2015 promises #3795 #3628 #3595 [TrejGun](https://github.com/TrejGun) - * docs: fixed dates in History.md #3791 [Jokero](https://github.com/Jokero) - * feat: connect, open, openSet, and disconnect return ES2015 promises #3790 #3622 [TrejGun](https://github.com/TrejGun) - * feat: custom type for int32 via mongoose-int32 npm package #3652 #3102 - * feat: basic custom schema type API #995 - * feat(model): `insertMany()` for more performant bulk inserts #723 - -4.3.7 / 2016-01-23 -================== - * docs: grammar fix in timestamps docs #3786 [zclancy](https://github.com/zclancy) - * fix(document): setting nested populated docs #3783 [slamuu](https://github.com/slamuu) - * fix(document): don't call post save hooks twice for pushed docs #3780 - * fix(model): handle `_id=0` correctly #3776 - * docs(middleware): async post hooks #3770 - * docs: remove confusing sentence #3765 [marcusmellis89](https://github.com/marcusmellis89) - -3.8.39 / 2016-01-15 -=================== - * fixed; casting a number to a buffer #3764 - * fixed; enumerating virtual property with nested objects #3743 [kusold](https://github.com/kusold) - -4.3.6 / 2016-01-15 -================== - * fix(types): casting a number to a buffer #3764 - * fix: add "listener" to reserved keywords #3759 - * chore: upgrade uglify #3757 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix: broken execPopulate() in 4.3.5 #3755 #3753 - * fix: ability to remove() a single embedded doc #3754 - * style: comma-last in test folder #3751 [ChristianMurphy](https://github.com/ChristianMurphy) - * docs: clarify versionKey option #3747 - * fix: improve colorization for arrays #3744 [TrejGun](https://github.com/TrejGun) - * fix: webpack build #3713 - -4.3.5 / 2016-01-09 -================== - * fix(query): throw when 4th parameter to update not a function #3741 [kasselTrankos](https://github.com/kasselTrankos) - * fix(document): separate error type for setting an object to a primitive #3735 - * fix(populate): Model.populate returns ES6 promise #3734 - * fix(drivers): re-register event handlers after manual reconnect #3729 - * docs: broken links #3727 - * fix(validation): update validators run array validation #3724 - * docs: clarify the need to use markModified with in-place date ops #3722 - * fix(document): mark correct path as populated when manually populating array #3721 - * fix(aggregate): support for array pipeline argument to append #3718 [dbkup](https://github.com/dbkup) - * docs: clarify `.connect()` callback #3705 - * fix(schema): properly validate nested single nested docs #3702 - * fix(types): handle setting documentarray of wrong type #3701 - * docs: broken links #3700 - * fix(drivers): debug output properly displays '0' #3689 - -3.8.38 / 2016-01-07 -=================== - * fixed; aggregate.append an array #3730 [dbkup](https://github.com/dbkup) - -4.3.4 / 2015-12-23 -================== - * fix: upgrade mongodb driver to 2.1.2 for repl set error #3712 [sansmischevia](https://github.com/sansmischevia) - * docs: validation docs typo #3709 [ivanmaeder](https://github.com/ivanmaeder) - * style: remove unused variables #3708 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix(schema): duck-typing for schemas #3703 [mgcrea](https://github.com/mgcrea) - * docs: connection sample code issue #3697 - * fix(schema): duck-typing for schemas #3693 [mgcrea](https://github.com/mgcrea) - * docs: clarify id schema option #3638 - -4.3.3 / 2015-12-18 -================== - * fix(connection): properly support 'replSet' as well as 'replset' #3688 [taxilian](https://github.com/taxilian) - * fix(document): single nested doc pre hooks called before nested doc array #3687 [aliatsis](https://github.com/aliatsis) - -4.3.2 / 2015-12-17 -================== - * fix(document): .set() into single nested schemas #3686 - * fix(connection): support 'replSet' as well as 'replset' option #3685 - * fix(document): bluebird unhandled rejection when validating doc arrays #3681 - * fix(document): hooks for doc arrays in single nested schemas #3680 - * fix(document): post hooks for single nested schemas #3679 - * fix: remove unused npm module #3674 [sybarite](https://github.com/sybarite) - * fix(model): don't swallow exceptions in nested doc save callback #3671 - * docs: update keepAlive info #3667 [ChrisZieba](https://github.com/ChrisZieba) - * fix(document): strict 'throw' throws a specific mongoose error #3662 - * fix: flakey test #3332 - * fix(query): more robust check for RegExp #2969 - -4.3.1 / 2015-12-11 -================== - * feat(aggregate): `.sample()` helper #3665 - * fix(query): bitwise query operators with buffers #3663 - * docs(migration): clarify `new` option and findByIdAndUpdate #3661 - -4.3.0 / 2015-12-09 -================== - * feat(query): support for mongodb 3.2 bitwise query operators #3660 - * style: use comma-last style consistently #3657 [ChristianMurphy](https://github.com/ChristianMurphy) - * feat: upgrade mongodb driver to 2.1.0 for full MongoDB 3.2 support #3656 - * feat(aggregate): `.lookup()` helper #3532 - -4.2.10 / 2015-12-08 -=================== - * fixed; upgraded marked #3653 [ChristianMurphy](https://github.com/ChristianMurphy) - * docs; cross-db populate #3648 - * docs; update mocha URL #3646 [ojhaujjwal](https://github.com/ojhaujjwal) - * fixed; call close callback asynchronously #3645 - * docs; virtuals.html issue #3644 [Psarna94](https://github.com/Psarna94) - * fixed; single embedded doc casting on init #3642 - * docs; validation docs improvements #3640 - -4.2.9 / 2015-12-02 -================== - * docs; defaults docs #3625 - * fix; nested numeric keys causing an embedded document crash #3623 - * fix; apply path getters before virtual getters #3618 - * fix; casting for arrays in single nested schemas #3616 - -4.2.8 / 2015-11-25 -================== - * docs; clean up README links #3612 [ReadmeCritic](https://github.com/ReadmeCritic) - * fix; ESLint improvements #3605 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix; assigning single nested subdocs #3601 - * docs; describe custom logging functions in `mongoose.set()` docs #3557 - -4.2.7 / 2015-11-20 -================== - * fixed; readPreference connection string option #3600 - * fixed; pulling from manually populated arrays #3598 #3579 - * docs; FAQ about OverwriteModelError #3597 [stcruy](https://github.com/stcruy) - * fixed; setting single embedded schemas to null #3596 - * fixed; indexes for single embedded schemas #3594 - * docs; clarify projection for `findOne()` #3593 [gunar](https://github.com/gunar) - * fixed; .ownerDocument() method on single embedded schemas #3589 - * fixed; properly throw casterror for query on single embedded schema #3580 - * upgraded; mongodb driver -> 2.0.49 for reconnect issue fix #3481 - -4.2.6 / 2015-11-16 -================== - * fixed; ability to manually populate an array #3575 - * docs; clarify `isAsync` parameter to hooks #3573 - * fixed; use captureStackTrace if possible instead #3571 - * fixed; crash with buffer and update validators #3565 [johnpeb](https://github.com/johnpeb) - * fixed; update casting with operators overwrite: true #3564 - * fixed; validation with single embedded docs #3562 - * fixed; inline docs inherit parents $type key #3560 - * docs; bad grammar in populate docs #3559 [amaurymedeiros](https://github.com/amaurymedeiros) - * fixed; properly handle populate option for find() #2321 - -3.8.37 / 2015-11-16 -=================== - * fixed; use retainKeyOrder for cloning update op #3572 - -4.2.5 / 2015-11-09 -================== - * fixed; handle setting fields in pre update hooks with exec #3549 - * upgraded; ESLint #3547 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; bluebird unhandled rejections with cast errors and .exec #3543 - * fixed; min/max validators handling undefined #3539 - * fixed; standalone mongos connections #3537 - * fixed; call `.toObject()` when setting a single nested doc #3535 - * fixed; single nested docs now have methods #3534 - * fixed; single nested docs with .create() #3533 #3521 [tusbar](https://github.com/tusbar) - * docs; deep populate docs #3528 - * fixed; deep populate schema ref handling #3507 - * upgraded; mongodb driver -> 2.0.48 for sort overflow issue #3493 - * docs; clarify default ids for discriminators #3482 - * fixed; properly support .update(doc) #3221 - -4.2.4 / 2015-11-02 -================== - * fixed; upgraded `ms` package for security vulnerability #3524 [fhemberger](https://github.com/fhemberger) - * fixed; ESlint rules #3517 [ChristianMurphy](https://github.com/ChristianMurphy) - * docs; typo in aggregation docs #3513 [rafakato](https://github.com/rafakato) - * fixed; add `dontThrowCastError` option to .update() for promises #3512 - * fixed; don't double-cast buffers in node 4.x #3510 #3496 - * fixed; population with single embedded schemas #3501 - * fixed; pre('set') hooks work properly #3479 - * docs; promises guide #3441 - -4.2.3 / 2015-10-26 -================== - * docs; remove unreferenced function in middleware.jade #3506 - * fixed; handling auth with no username/password #3500 #3498 #3484 [mleanos](https://github.com/mleanos) - * fixed; more ESlint rules #3491 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; swallowing exceptions in save callback #3478 - * docs; fixed broken links in subdocs guide #3477 - * fixed; casting booleans to numbers #3475 - * fixed; report CastError for subdoc arrays in findOneAndUpdate #3468 - * fixed; geoNear returns ES6 promise #3458 - -4.2.2 / 2015-10-22 -================== - * fixed; go back to old pluralization code #3490 - -4.2.1 / 2015-10-22 -================== - * fixed; pluralization issues #3492 [ChristianMurphy](https://github.com/ChristianMurphy) - -4.2.0 / 2015-10-22 -================== - * added; support for skipVersioning for document arrays #3467 [chazmo03](https://github.com/chazmo03) - * added; ability to customize schema 'type' key #3459 #3245 - * fixed; writeConcern for index builds #3455 - * added; emit event when individual index build starts #3440 [objectiveSee](https://github.com/objectiveSee) - * added; 'context' option for update validators #3430 - * refactor; pluralization now in separate pluralize-mongoose npm module #3415 [ChristianMurphy](https://github.com/ChristianMurphy) - * added; customizable error validation messages #3406 [geronime](https://github.com/geronime) - * added; support for passing 'minimize' option to update #3381 - * added; ability to customize debug logging format #3261 - * added; baseModelName property for discriminator models #3202 - * added; 'emitIndexErrors' option #3174 - * added; 'async' option for aggregation cursor to support buffering #3160 - * added; ability to skip validation for individual save() calls #2981 - * added; single embedded schema support #2689 #585 - * added; depopulate function #2509 - -4.1.12 / 2015-10-19 -=================== - * docs; use readPreference instead of slaveOk for Query.setOptions docs #3471 [buunguyen](https://github.com/buunguyen) - * fixed; more helpful error when regexp contains null bytes #3456 - * fixed; x509 auth issue #3454 [NoxHarmonium](https://github.com/NoxHarmonium) - -3.8.36 / 2015-10-18 -=================== - * fixed; Make array props non-enumerable #3461 [boblauer](https://github.com/boblauer) - -4.1.11 / 2015-10-12 -=================== - * fixed; update timestamps for update() if they're enabled #3450 [isayme](https://github.com/isayme) - * fixed; unit test error on node 0.10 #3449 [isayme](https://github.com/isayme) - * docs; timestamp option docs #3448 [isayme](https://github.com/isayme) - * docs; fix unexpected indent #3443 [isayme](https://github.com/isayme) - * fixed; use ES6 promises for Model.prototype.remove() #3442 - * fixed; don't use unused 'safe' option for index builds #3439 - * fixed; elemMatch casting bug #3437 #3435 [DefinitelyCarter](https://github.com/DefinitelyCarter) - * docs; schema.index docs #3434 - * fixed; exceptions in save() callback getting swallowed on mongodb 2.4 #3371 - -4.1.10 / 2015-10-05 -=================== - * docs; improve virtuals docs to explain virtuals schema option #3433 [zoyaH](https://github.com/zoyaH) - * docs; MongoDB server version compatibility guide #3427 - * docs; clarify that findById and findByIdAndUpdate fire hooks #3422 - * docs; clean up Model.save() docs #3420 - * fixed; properly handle projection with just id #3407 #3412 - * fixed; infinite loop when database document is corrupted #3405 - * docs; clarify remove middleware #3388 - -4.1.9 / 2015-09-28 -================== - * docs; minlength and maxlength string validation docs #3368 #3413 [cosmosgenius](https://github.com/cosmosgenius) - * fixed; linting for infix operators #3397 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; proper casting for $all #3394 - * fixed; unhandled rejection warnings with .create() #3391 - * docs; clarify update validators on paths that aren't explicitly set #3386 - * docs; custom validator examples #2778 - -4.1.8 / 2015-09-21 -================== - * docs; fixed typo in example #3390 [kmctown](https://github.com/kmctown) - * fixed; error in toObject() #3387 [guumaster](https://github.com/guumaster) - * fixed; handling for casting null dates #3383 [alexmingoia](https://github.com/alexmingoia) - * fixed; passing composite ids to `findByIdAndUpdate` #3380 - * fixed; linting #3376 #3375 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; added NodeJS v4 to Travis #3374 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; casting $elemMatch inside of $not #3373 [gaguirre](https://github.com/gaguirre) - * fixed; handle case where $slice is 0 #3369 - * fixed; avoid running getters if path is populated #3357 - * fixed; cast documents to objects when setting to a nested path #3346 - -4.1.7 / 2015-09-14 -================== - * docs; typos in SchemaType documentation #3367 [jasson15](https://github.com/jasson15) - * fixed; MONGOOSE_DRIVER_PATH env variable again #3360 - * docs; added validateSync docs #3353 - * fixed; set findOne op synchronously in query #3344 - * fixed; handling for `.pull()` on a documentarray without an id #3341 - * fixed; use natural order for cloning update conditions #3338 - * fixed; issue with strict mode casting for mixed type updates #3337 - -4.1.6 / 2015-09-08 -================== - * fixed; MONGOOSE_DRIVER_PATH env variable #3345 [g13013](https://github.com/g13013) - * docs; global autoIndex option #3335 [albertorestifo](https://github.com/albertorestifo) - * docs; model documentation typos #3330 - * fixed; report reason for CastError #3320 - * fixed; .populate() no longer returns true after re-assigning #3308 - * fixed; discriminators with aggregation geoNear #3304 - * docs; discriminator docs #2743 - -4.1.5 / 2015-09-01 -================== - * fixed; document.remove() removing all docs #3326 #3325 - * fixed; connect() checks for rs_name in options #3299 - * docs; examples for schema.set() #3288 - * fixed; checkKeys issue with bluebird #3286 [gregthegeek](https://github.com/gregthegeek) - -4.1.4 / 2015-08-31 -================== - * fixed; ability to set strict: false for update #3305 - * fixed; .create() properly uses ES6 promises #3297 - * fixed; pre hooks on nested subdocs #3291 #3284 [aliatsis](https://github.com/aliatsis) - * docs; remove unclear text in .remove() docs #3282 - * fixed; pre hooks called twice for 3rd-level nested doc #3281 - * fixed; nested transforms #3279 - * upgraded; mquery -> 1.6.3 #3278 #3272 - * fixed; don't swallow callback errors by default #3273 #3222 - * fixed; properly get nested paths from nested schemas #3265 - * fixed; remove() with id undefined deleting all docs #3260 [thanpolas](https://github.com/thanpolas) - * fixed; handling for non-numeric projections #3256 - * fixed; findById with id undefined returning first doc #3255 - * fixed; use retainKeyOrder for update #3215 - * added; passRawResult option to findOneAndUpdate for backwards compat #3173 - -4.1.3 / 2015-08-16 -================== - * fixed; getUpdate() in pre update hooks #3520 [gregthegeek](https://github.com/gregthegeek) - * fixed; handleArray() ensures arg is an array #3238 [jloveridge](https://github.com/jloveridge) - * fixed; refresh required path cache when recreating docs #3199 - * fixed; $ operator on unwind aggregation helper #3197 - * fixed; findOneAndUpdate() properly returns raw result as third arg to callback #3173 - * fixed; querystream with dynamic refs #3108 - -3.8.35 / 2015-08-14 -=================== - * fixed; handling for minimize on nested objects #2930 - * fixed; don't crash when schema.path.options undefined #1824 - -4.1.2 / 2015-08-10 -================== - * fixed; better handling for Jade templates #3241 [kbadk](https://github.com/kbadk) - * added; ESlint trailing spaces #3234 [ChristianMurphy](https://github.com/ChristianMurphy) - * added; ESlint #3191 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; properly emit event on disconnect #3183 - * fixed; copy options properly using Query.toConstructor() #3176 - * fixed; setMaxListeners() issue in browser build #3170 - * fixed; node driver -> 2.0.40 to not store undefined keys as null #3169 - * fixed; update validators handle positional operator #3167 - * fixed; handle $all + $elemMatch query casting #3163 - * fixed; post save hooks don't swallow extra args #3155 - * docs; spelling mistake in index.jade #3154 - * fixed; don't crash when toObject() has no fields #3130 - * fixed; apply toObject() recursively for find and update queries #3086 [naoina](https://github.com/naoina) - -4.1.1 / 2015-08-03 -================== - * fixed; aggregate exec() crash with no callback #3212 #3198 [jpgarcia](https://github.com/jpgarcia) - * fixed; pre init hooks now properly synchronous #3207 [burtonjc](https://github.com/burtonjc) - * fixed; updateValidators doesn't flatten dates #3206 #3194 [victorkohl](https://github.com/victorkohl) - * fixed; default fields don't make document dirty between saves #3205 [burtonjc](https://github.com/burtonjc) - * fixed; save passes 0 as numAffected rather than undefined when no change #3195 [burtonjc](https://github.com/burtonjc) - * fixed; better handling for positional operator in update #3185 - * fixed; use Travis containers #3181 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; leaked variable #3180 [ChristianMurphy](https://github.com/ChristianMurphy) - -4.1.0 / 2015-07-24 -================== - * added; `schema.queue()` now public #3193 - * added; raw result as third parameter to findOneAndX callback #3173 - * added; ability to run validateSync() on only certain fields #3153 - * added; subPopulate #3103 [timbur](https://github.com/timbur) - * added; $isDefault function on documents #3077 - * added; additional properties for built-in validator messages #3063 [KLicheR](https://github.com/KLicheR) - * added; getQuery() and getUpdate() functions for Query #3013 - * added; export DocumentProvider #2996 - * added; ability to remove path from schema #2993 [JohnnyEstilles](https://github.com/JohnnyEstilles) - * added; .explain() helper for aggregate #2714 - * added; ability to specify which ES6-compatible promises library mongoose uses #2688 - * added; export Aggregate #1910 - -4.0.8 / 2015-07-20 -================== - * fixed; assignment with document arrays #3178 [rosston](https://github.com/rosston) - * docs; remove duplicate paragraph #3164 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * docs; improve findOneAndXYZ parameter descriptions #3159 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * docs; add findOneAndRemove to list of supported middleware #3158 - * docs; clarify ensureIndex #3156 - * fixed; refuse to save/remove document without id #3118 - * fixed; hooks next() no longer accidentally returns promise #3104 - * fixed; strict mode for findOneAndUpdate #2947 - * added; .min.js.gz file for browser component #2806 - -3.8.34 / 2015-07-20 -=================== - * fixed; allow using $rename #3171 - * fixed; no longer modifies update arguments #3008 - -4.0.7 / 2015-07-11 -================== - * fixed; documentarray id method when using object id #3157 [siboulet](https://github.com/siboulet) - * docs; improve findById docs #3147 - * fixed; update validators handle null properly #3136 [odeke-em](https://github.com/odeke-em) - * docs; jsdoc syntax errors #3128 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * docs; fix typo #3126 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * docs; proper formatting in queries.jade #3121 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * docs; correct example for string maxlength validator #3111 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * fixed; setDefaultsOnInsert with arrays #3107 - * docs; LearnBoost -> Automattic in package.json #3099 - * docs; pre update hook example #3094 [danpe](https://github.com/danpe) - * docs; clarify query middleware example #3051 - * fixed; ValidationErrors in strict mode #3046 - * fixed; set findOneAndUpdate properties before hooks run #3024 - -3.8.33 / 2015-07-10 -=================== - * upgraded; node driver -> 1.4.38 - * fixed; dont crash when `match` validator undefined - -4.0.6 / 2015-06-21 -================== - * upgraded; node driver -> 2.0.34 #3087 - * fixed; apply setters on addToSet, etc #3067 [victorkohl](https://github.com/victorkohl) - * fixed; missing semicolons #3065 [sokolikp](https://github.com/sokolikp) - * fixed; proper handling for async doc hooks #3062 [gregthegeek](https://github.com/gregthegeek) - * fixed; dont set failed populate field to null if other docs are successfully populated #3055 [eloytoro](https://github.com/eloytoro) - * fixed; setDefaultsOnInsert with document arrays #3034 [taxilian](https://github.com/taxilian) - * fixed; setters fired on array items #3032 - * fixed; stop validateSync() on first error #3025 [victorkohl](https://github.com/victorkohl) - * docs; improve query docs #3016 - * fixed; always exclude _id when its deselected #3010 - * fixed; enum validator kind property #3009 - * fixed; mquery collection names #3005 - * docs; clarify mongos option #3000 - * docs; clarify that query builder has a .then() #2995 - * fixed; race condition in dynamic ref #2992 - -3.8.31 / 2015-06-20 -=================== - * fixed; properly handle text search with discriminators and $meta #2166 - -4.0.5 / 2015-06-05 -================== - * fixed; ObjectIds and buffers when mongodb driver is a sibling dependency #3050 #3048 #3040 #3031 #3020 #2988 #2951 - * fixed; warn user when 'increment' is used in schema #3039 - * fixed; setDefaultsOnInsert with array in schema #3035 - * fixed; dont use default Object toString to cast to string #3030 - * added; npm badge #3020 [odeke-em](https://github.com/odeke-em) - * fixed; proper handling for calling .set() with a subdoc #2782 - * fixed; dont throw cast error when using $rename on non-string path #1845 - -3.8.30 / 2015-06-05 -=================== - * fixed; enable users to set all options with tailable() #2883 - -4.0.4 / 2015-05-28 -================== - * docs; findAndModify new parameter correct default value #3012 [JonForest](https://github.com/JonForest) - * docs; clarify pluralization rules #2999 [anonmily](https://github.com/anonmily) - * fix; discriminators with schema methods #2978 - * fix; make `isModified` a schema reserved keyword #2975 - * fix; properly fire setters when initializing path with object #2943 - * fix; can use `setDefaultsOnInsert` without specifying `runValidators` #2938 - * fix; always set validation errors `kind` property #2885 - * upgraded; node driver -> 2.0.33 #2865 - -3.8.29 / 2015-05-27 -=================== - * fixed; Handle JSON.stringify properly for nested docs #2990 - -4.0.3 / 2015-05-13 -================== - * upgraded; mquery -> 1.5.1 #2983 - * docs; clarify context for query middleware #2974 - * docs; fix missing type -> kind rename in History.md #2961 - * fixed; broken ReadPreference include on Heroku #2957 - * docs; correct form for cursor aggregate option #2955 - * fixed; sync post hooks now properly called after function #2949 #2925 - * fixed; fix sub-doc validate() function #2929 - * upgraded; node driver -> 2.0.30 #2926 - * docs; retainKeyOrder for save() #2924 - * docs; fix broken class names #2913 - * fixed; error when using node-clone on a doc #2909 - * fixed; no more hard references to bson #2908 #2906 - * fixed; dont overwrite array values #2907 [naoina](https://github.com/naoina) - * fixed; use readPreference=primary for findOneAndUpdate #2899 #2823 - * docs; clarify that update validators only run on $set and $unset #2889 - * fixed; set kind consistently for built-in validators #2885 - * docs; single field populated documents #2884 - * fixed; nested objects are now enumerable #2880 [toblerpwn](https://github.com/toblerpwn) - * fixed; properly populate field when ref, lean, stream used together #2841 - * docs; fixed migration guide jade error #2807 - -3.8.28 / 2015-05-12 -=================== - * fixed; proper handling for toJSON options #2910 - * fixed; dont attach virtuals to embedded docs in update() #2046 - -4.0.2 / 2015-04-23 -================== - * fixed; error thrown when calling .validate() on subdoc not in an array #2902 - * fixed; rename define() to play nice with webpack #2900 [jspears](https://github.com/jspears) - * fixed; pre validate called twice with discriminators #2892 - * fixed; .inspect() on mongoose.Types #2875 - * docs; correct callback params for Model.update #2872 - * fixed; setDefaultsOnInsert now works when runValidators not specified #2870 - * fixed; Document now wraps EventEmitter.addListener #2867 - * fixed; call non-hook functions in schema queue #2856 - * fixed; statics can be mocked out for tests #2848 [ninelb](https://github.com/ninelb) - * upgraded; mquery 1.4.0 for bluebird bug fix #2846 - * fixed; required validators run first #2843 - * docs; improved docs for new option to findAndMody #2838 - * docs; populate example now uses correct field #2837 [swilliams](https://github.com/swilliams) - * fixed; pre validate changes causing VersionError #2835 - * fixed; get path from correct place when setting CastError #2832 - * docs; improve docs for Model.update() function signature #2827 [irnc](https://github.com/irnc) - * fixed; populating discriminators #2825 [chetverikov](https://github.com/chetverikov) - * fixed; discriminators with nested schemas #2821 - * fixed; CastErrors with embedded docs #2819 - * fixed; post save hook context #2816 - * docs; 3.8.x -> 4.x migration guide #2807 - * fixed; proper _distinct copying for query #2765 [cdelauder](https://github.com/cdelauder) - -3.8.27 / 2015-04-22 -=================== - * fixed; dont duplicate db calls on Q.ninvoke() #2864 - * fixed; Model.find arguments naming in docs #2828 - * fixed; Support ipv6 in connection strings #2298 - -3.8.26 / 2015-04-07 -=================== - * fixed; TypeError when setting date to undefined #2833 - * fixed; handle CastError properly in distinct() with no callback #2786 - * fixed; broken links in queries docs #2779 - * fixed; dont mark buffer as modified when setting type initially #2738 - * fixed; dont crash when using slice with populate #1934 - -4.0.1 / 2015-03-28 -================== - * fixed; properly handle empty cast doc in update() with promises #2796 - * fixed; unstable warning #2794 - * fixed; findAndModify docs now show new option is false by default #2793 - -4.0.0 / 2015-03-25 -================== - * fixed; on-the-fly schema docs typo #2783 [artiifix](https://github.com/artiifix) - * fixed; cast error validation handling #2775 #2766 #2678 - * fixed; discriminators with populate() #2773 #2719 [chetverikov](https://github.com/chetverikov) - * fixed; increment now a reserved path #2709 - * fixed; avoid sending duplicate object ids in populate() #2683 - * upgraded; mongodb to 2.0.24 to properly emit reconnect event multiple times #2656 - -4.0.0-rc4 / 2015-03-14 -====================== - * fixed; toObject virtuals schema option handled properly #2751 - * fixed; update validators work on document arrays #2733 - * fixed; check for cast errors on $set #2729 - * fixed; instance field set for all schema types #2727 [csdco](https://github.com/csdco) - * fixed; dont run other validators if required fails #2725 - * fixed; custom getters execute on ref paths #2610 - * fixed; save defaults if they were set when doc was loaded from db #2558 - * fixed; pre validate now runs before pre save #2462 - * fixed; no longer throws errors with --use_strict #2281 - -3.8.25 / 2015-03-13 -=================== - * fixed; debug output reverses order of aggregation keys #2759 - * fixed; $eq is a valid query selector in 3.0 #2752 - * fixed; upgraded node driver to 1.4.32 for handling non-numeric poolSize #2682 - * fixed; update() with overwrite sets _id for nested docs #2658 - * fixed; casting for operators in $elemMatch #2199 - -4.0.0-rc3 / 2015-02-28 -====================== - * fixed; update() pre hooks run before validators #2706 - * fixed; setters not called on arrays of refs #2698 [brandom](https://github.com/brandom) - * fixed; use node driver 2.0.18 for nodejs 0.12 support #2685 - * fixed; comments reference file that no longer exists #2681 - * fixed; populated() returns _id of manually populated doc #2678 - * added; ability to exclude version key in toObject() #2675 - * fixed; dont allow setting nested path to a string #2592 - * fixed; can cast objects with _id field to ObjectIds #2581 - * fixed; on-the-fly schema getters #2360 - * added; strict option for findOneAndUpdate() #1967 - -3.8.24 / 2015-02-25 -=================== - * fixed; properly apply child schema transforms #2691 - * fixed; make copy of findOneAndUpdate options before modifying #2687 - * fixed; apply defaults when parent path is selected #2670 #2629 - * fixed; properly get ref property for nested paths #2665 - * fixed; node driver makes copy of authenticate options before modifying them #2619 - * fixed; dont block process exit when auth fails #2599 - * fixed; remove redundant clone in update() #2537 - -4.0.0-rc2 / 2015-02-10 -====================== - * added; io.js to travis build - * removed; browser build dependencies not installed by default - * added; dynamic refpaths #2640 [chetverikov](https://github.com/chetverikov) - * fixed; dont call child schema transforms on parent #2639 [chetverikov](https://github.com/chetverikov) - * fixed; get rid of remove option if new is set in findAndModify #2598 - * fixed; aggregate all document array validation errors #2589 - * fixed; custom setters called when setting value to undefined #1892 - -3.8.23 / 2015-02-06 -=================== - * fixed; unset opts.remove when upsert is true #2519 - * fixed; array saved as object when path is object in array #2442 - * fixed; inline transforms #2440 - * fixed; check for callback in count() #2204 - * fixed; documentation for selecting fields #1534 - -4.0.0-rc1 / 2015-02-01 -====================== - * fixed; use driver 2.0.14 - * changed; use transform: true by default #2245 - -4.0.0-rc0 / 2015-01-31 -=================== - * fixed; wrong order for distinct() params #2628 - * fixed; handling no query argument to remove() #2627 - * fixed; createModel and discriminators #2623 [ashaffer](https://github.com/ashaffer) - * added; pre('count') middleware #2621 - * fixed; double validation calls on document arrays #2618 - * added; validate() catches cast errors #2611 - * fixed; respect replicaSet parameter in connection string #2609 - * added; can explicitly exclude paths from versioning #2576 [csabapalfi](https://github.com/csabapalfi) - * upgraded; driver to 2.0.15 #2552 - * fixed; save() handles errors more gracefully in ES6 #2371 - * fixed; undefined is now a valid argument to findOneAndUpdate #2272 - * changed; `new` option to findAndModify ops is false by default #2262 - -3.8.22 / 2015-01-24 -=================== - * upgraded; node-mongodb-native to 1.4.28 #2587 [Climax777](https://github.com/Climax777) - * added; additional documentation for validators #2449 - * fixed; stack overflow when creating massive arrays #2423 - * fixed; undefined is a valid id for queries #2411 - * fixed; properly create nested schema index when same schema used twice #2322 - * added; link to plugin generator in docs #2085 [huei90](https://github.com/huei90) - * fixed; optional arguments documentation for findOne() #1971 [nachinius](https://github.com/nachinius) - -3.9.7 / 2014-12-19 -=================== - * added; proper cursors for aggregate #2539 [changyy](https://github.com/changyy) - * added; min/max built-in validators for dates #2531 [bshamblen](https://github.com/bshamblen) - * fixed; save and validate are now reserved keywords #2380 - * added; basic documentation for browser component #2256 - * added; find and findOne hooks (query middleware) #2138 - * fixed; throw a DivergentArrayError when saving positional operator queries #2031 - * added; ability to use options as a document property #1416 - * fixed; document no longer inherits from event emitter and so domain and _events are no longer reserved #1351 - * removed; setProfiling #1349 - -3.8.21 / 2014-12-18 -=================== - * fixed; syntax in index.jade #2517 [elderbas](https://github.com/elderbas) - * fixed; writable statics #2510 #2528 - * fixed; overwrite and explicit $set casting #2515 - -3.9.6 / 2014-12-05 -=================== - * added; correctly run validators on each element of array when entire array is modified #661 #1227 - * added; castErrors in validation #1013 [jondavidjohn](https://github.com/jondavidjohn) - * added; specify text indexes in schema fields #1401 [sr527](https://github.com/sr527) - * added; ability to set field with validators to undefined #1594 [alabid](https://github.com/alabid) - * added; .create() returns an array when passed an array #1746 [alabid](https://github.com/alabid) - * added; test suite and docs for use with co and yield #2177 #2474 - * fixed; subdocument toObject() transforms #2447 [chmanie](https://github.com/chmanie) - * fixed; Model.create() with save errors #2484 - * added; pass options to .save() and .remove() #2494 [jondavidjohn](https://github.com/jondavidjohn) - -3.8.20 / 2014-12-01 -=================== - * fixed; recursive readPref #2490 [kjvalencik](https://github.com/kjvalencik) - * fixed; make sure to copy parameters to update() before modifying #2406 [alabid](https://github.com/alabid) - * fixed; unclear documentation about query callbacks #2319 - * fixed; setting a schema-less field to an empty object #2314 [alabid](https://github.com/alabid) - * fixed; registering statics and methods for discriminators #2167 [alabid](https://github.com/alabid) - -3.9.5 / 2014-11-10 -=================== - * added; ability to disable autoIndex on a per-connection basis #1875 [sr527](https://github.com/sr527) - * fixed; `geoNear()` no longer enforces legacy coordinate pairs - supports GeoJSON #1987 [alabid](https://github.com/alabid) - * fixed; browser component works when minified with mangled variable names #2302 - * fixed; `doc.errors` now cleared before `validate()` called #2302 - * added; `execPopulate()` function to make `doc.populate()` compatible with promises #2317 - * fixed; `count()` no longer throws an error when used with `sort()` #2374 - * fixed; `save()` no longer recursively calls `save()` on populated fields #2418 - -3.8.19 / 2014-11-09 -=================== - * fixed; make sure to not override subdoc _ids on find #2276 [alabid](https://github.com/alabid) - * fixed; exception when comparing two documents when one lacks _id #2333 [slawo](https://github.com/slawo) - * fixed; getters for properties with non-strict schemas #2439 [alabid](https://github.com/alabid) - * fixed; inconsistent URI format in docs #2414 [sr527](https://github.com/sr527) - -3.9.4 / 2014-10-25 -================== - * fixed; statics no longer can be overwritten #2343 [nkcmr](https://github.com/chetverikov) - * added; ability to set single populated paths to documents #1530 - * added; setDefaultsOnInsert and runValidator options for findOneAndUpdate() #860 - -3.8.18 / 2014-10-22 -================== - * fixed; Dont use all toObject options in save #2340 [chetverikov](https://github.com/chetverikov) - -3.9.3 / 2014-10-01 -================= - * added; support for virtuals that return objects #2294 - * added; ability to manually hydrate POJOs into mongoose objects #2292 - * added; setDefaultsOnInsert and runValidator options for update() #860 - -3.8.17 / 2014-09-29 -================== - * fixed; use schema options retainKeyOrder in save() #2274 - * fixed; fix skip in populate when limit is set #2252 - * fixed; fix stack overflow when passing MongooseArray to findAndModify #2214 - * fixed; optimize .length usage in populate #2289 - -3.9.2 / 2014-09-08 -================== - * added; test coverage for browser component #2255 - * added; in-order execution of validators #2243 - * added; custom fields for validators #2132 - * removed; exception thrown when find() used with count() #1950 - -3.8.16 / 2014-09-08 -================== - * fixed; properly remove modified array paths if array has been overwritten #1638 - * fixed; key check errors #1884 - * fixed; make sure populate on an array always returns a Mongoose array #2214 - * fixed; SSL connections with node 0.11 #2234 - * fixed; return sensible strings for promise errors #2239 - -3.9.1 / 2014-08-17 -================== - * added; alpha version of browser-side schema validation #2254 - * added; support passing a function to schemas `required` field #2247 - * added; support for setting updatedAt and createdAt timestamps #2227 - * added; document.validate() returns a promise #2131 - -3.8.15 / 2014-08-17 -================== - * fixed; Replica set connection string example in docs #2246 - * fixed; bubble up parseError event #2229 - * fixed; removed buggy populate cache #2176 - * fixed; dont $inc versionKey if its being $set #1933 - * fixed; cast $or and $and in $pull #1932 - * fixed; properly cast to schema in stream() #1862 - * fixed; memory leak in nested objects #1565 #2211 [devongovett](https://github.com/devongovett) - -3.8.14 / 2014-07-26 -================== - * fixed; stringifying MongooseArray shows nested arrays #2002 - * fixed; use populated doc schema in toObject and toJSON by default #2035 - * fixed; dont crash on arrays containing null #2140 - * fixed; model.update w/ upsert has same return values on .exec and promise #2143 - * fixed; better handling for populate limit with multiple documents #2151 - * fixed; dont prevent users from adding weights to text index #2183 - * fixed; helper for aggregation cursor #2187 - * updated; node-mongodb-native to 1.4.7 - -3.8.13 / 2014-07-15 -================== - * fixed; memory leak with isNew events #2159 - * fixed; docs for overwrite option for update() #2144 - * fixed; storeShard() handles dates properly #2127 - * fixed; sub-doc changes not getting persisted to db after save #2082 - * fixed; populate with _id: 0 actually removes _id instead of setting to undefined #2123 - * fixed; save versionKey on findOneAndUpdate w/ upsert #2122 - * fixed; fix typo in 2.8 docs #2120 [shakirullahi](https://github.com/shakirullahi) - * fixed; support maxTimeMs #2102 [yuukinajima](https://github.com/yuukinajima) - * fixed; support $currentDate #2019 - * fixed; $addToSet handles objects without _ids properly #1973 - * fixed; dont crash on invalid nearSphere query #1874 - -3.8.12 / 2014-05-30 -================== - * fixed; single-server reconnect event fires #1672 - * fixed; sub-docs not saved when pushed into populated array #1794 - * fixed; .set() sometimes converts embedded docs to pojos #1954 [archangel-irk](https://github.com/archangel-irk) - * fixed; sub-doc changes not getting persisted to db after save #2082 - * fixed; custom getter might cause mongoose to mistakenly think a path is dirty #2100 [pgherveou](https://github.com/pgherveou) - * fixed; chainable helper for allowDiskUse option in aggregation #2114 - -3.9.0 (unstable) / 2014-05-22 -================== - * changed; added `domain` to reserved keywords #1338 #2052 [antoinepairet](https://github.com/antoinepairet) - * added; asynchronous post hooks #1977 #2081 [chopachom](https://github.com/chopachom) [JasonGhent](https://github.com/JasonGhent) - * added; using model for population, cross-db populate [mihai-chiorean](https://github.com/mihai-chiorean) - * added; can define a type for schema validators - * added; `doc.remove()` returns a promise #1619 [refack](https://github.com/refack) - * added; internal promises for hooks, pre-save hooks run in parallel #1732 [refack](https://github.com/refack) - * fixed; geoSearch hanging when no results returned #1846 [ghartnett](https://github.com/ghartnett) - * fixed; do not set .type property on ValidationError, use .kind instead #1323 - -3.8.11 / 2014-05-22 -================== - * updated; node-mongodb-native to 1.4.5 - * reverted; #2052, fixes #2097 - -3.8.10 / 2014-05-20 -================== - - * updated; node-mongodb-native to 1.4.4 - * fixed; _.isEqual false negatives bug in js-bson #2070 - * fixed; missing check for schema.options #2014 - * fixed; missing support for $position #2024 - * fixed; options object corruption #2049 - * fixed; improvements to virtuals docs #2055 - * fixed; added `domain` to reserved keywords #2052 #1338 - -3.8.9 / 2014-05-08 -================== - - * updated; mquery to 0.7.0 - * updated; node-mongodb-native to 1.4.3 - * fixed; $near failing against MongoDB 2.6 - * fixed; relying on .options() to determine if collection exists - * fixed; $out aggregate helper - * fixed; all test failures against MongoDB 2.6.1, with caveat #2065 - -3.8.8 / 2014-02-22 -================== - - * fixed; saving Buffers #1914 - * updated; expose connection states for user-land #1926 [yorkie](https://github.com/yorkie) - * updated; mquery to 0.5.3 - * updated; added get / set to reserved path list #1903 [tstrimple](https://github.com/tstrimple) - * docs; README code highlighting, syntax fixes #1930 [IonicaBizau](https://github.com/IonicaBizau) - * docs; fixes link in the doc at #1925 [kapeels](https://github.com/kapeels) - * docs; add a missed word 'hook' for the description of the post-hook api #1924 [ipoval](https://github.com/ipoval) - -3.8.7 / 2014-02-09 -================== - - * fixed; sending safe/read options in Query#exec #1895 - * fixed; findOneAnd..() with sort #1887 - -3.8.6 / 2014-01-30 -================== - - * fixed; setting readPreferences #1895 - -3.8.5 / 2014-01-23 -================== - - * fixed; ssl setting when using URI #1882 - * fixed; findByIdAndUpdate now respects the overwrite option #1809 [owenallenaz](https://github.com/owenallenaz) - -3.8.4 / 2014-01-07 -================== - - * updated; mongodb driver to 1.3.23 - * updated; mquery to 0.4.1 - * updated; mpromise to 0.4.3 - * fixed; discriminators now work when selecting fields #1820 [daemon1981](https://github.com/daemon1981) - * fixed; geoSearch with no results timeout #1846 [ghartnett](https://github.com/ghartnett) - * fixed; infitite recursion in ValidationError #1834 [chetverikov](https://github.com/chetverikov) - -3.8.3 / 2013-12-17 -================== - - * fixed; setting empty array with model.update #1838 - * docs; fix url - -3.8.2 / 2013-12-14 -================== - - * fixed; enum validation of multiple values #1778 [heroicyang](https://github.com/heroicyang) - * fixed; global var leak #1803 - * fixed; post remove now fires on subdocs #1810 - * fixed; no longer set default empty array for geospatial-indexed fields #1668 [shirish87](https://github.com/shirish87) - * fixed; model.stream() not hydrating discriminators correctly #1792 [j](https://github.com/j) - * docs: Stablility -> Stability [nikmartin](https://github.com/nikmartin) - * tests; improve shard error handling - -3.8.1 / 2013-11-19 -================== - - * fixed; mishandling of Dates with minimize/getters #1764 - * fixed; Normalize bugs.email, so `npm` will shut up #1769 [refack](https://github.com/refack) - * docs; Improve the grammar where "lets us" was used #1777 [alexyoung](https://github.com/alexyoung) - * docs; Fix some grammatical issues in the documentation #1777 [alexyoung](https://github.com/alexyoung) - * docs; fix Query api exposure - * docs; fix return description - * docs; Added Notes on findAndUpdate() #1750 [sstadelman](https://github.com/sstadelman) - * docs; Update version number in README #1762 [Fodi69](https://github.com/Fodi69) - -3.8.0 / 2013-10-31 -================== - - * updated; warn when using an unstable version - * updated; error message returned in doc.save() #1595 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * updated; mquery to 0.3.2 - * updated; mocha to 1.12.0 - * updated; mpromise 0.3.0 - * updated; sliced 0.0.5 - * removed; mongoose.Error.DocumentError (never used) - * removed; namedscope (undocumented and broken) #679 #642 #455 #379 - * changed; no longer offically supporting node 0.6.x - * changed; query.within getter is now a method -> query.within() - * changed; query.intersects getter is now a method -> query.intersects() - * added; custom error msgs for built-in validators #747 - * added; discriminator support #1647 #1003 [j](https://github.com/j) - * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) - * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) - * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) - * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) - * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) - * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) - * added; promise support to model.mapReduce() - * added; promise support to model.ensureIndexes() - * added; promise support to model.populate() - * added; benchmarks [ebensing](https://github.com/ebensing) - * added; publicly exposed connection states #1585 - * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) - * added; query method chain validation - * added; model.update `overwrite` option - * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) - * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) - * added; MongooseBuffer#subtype() - * added; model.create() now returns a promise #1340 - * added; support for `awaitdata` query option - * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) - * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) - * fixed; document.toObject when using `minimize` and `getters` options #1607 [JedWatson](https://github.com/JedWatson) - * fixed; Mixed types can now be required #1722 [Reggino](https://github.com/Reggino) - * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals() when _id option is set to false #1687 - * fixed; strict mode warnings #1686 - * fixed; $near GeoJSON casting #1683 - * fixed; nearSphere GeoJSON query builder - * fixed; population field selection w/ strings #1669 - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; handle another versioning edge case #1520 - * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) - * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) - * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) - * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) - * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) - * fixed; model.remove() removes only what is necessary #1649 - * fixed; update() now only runs with cb or explicit true #1644 - * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) - * fixed; model.update "overwrite" option works as documented - * fixed; query#remove() works as documented - * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) - * fixed; benchmarks to actually output valid json - * deprecated; promise#addBack (use promise#onResolve) - * deprecated; promise#complete (use promise#fulfill) - * deprecated; promise#addCallback (use promise#onFulFill) - * deprecated; promise#addErrback (use promise#onReject) - * deprecated; query.nearSphere() (use query.near) - * deprecated; query.center() (use query.circle) - * deprecated; query.centerSphere() (use query.circle) - * deprecated; query#slaveOk (use query#read) - * docs; custom validator messages - * docs; 10gen -> MongoDB - * docs; add Date method caveats #1598 - * docs; more validation details - * docs; state which branch is stable/unstable - * docs; mention that middleware does not run on Models - * docs; promise.fulfill() - * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) - * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) - * website; add "show code" for properties - * website; move "show code" links down - * website; update guide - * website; add unstable docs - * website; many improvements - * website; fix copyright #1439 - * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) - * tests; refactor 1703 - * tests; add test generator - * tests; validate formatMessage() throws - * tests; add script for continuously running tests - * tests; fixed versioning tests - * tests; race conditions in tests - * tests; added for nested and/or queries - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; replace deprecated method names - * tests; convert id to string - * tests; fix sharding tests for MongoDB 2.4.5 - * tests; now 4-5 seconds faster - * tests; fix race condition - * make; suppress warning msg in test - * benchmarks; updated for pull requests - * examples; improved and expanded [ebensing](https://github.com/ebensing) - -3.7.4 (unstable) / 2013-10-01 -============================= - - * updated; mquery to 0.3.2 - * removed; mongoose.Error.DocumentError (never used) - * added; custom error msgs for built-in validators #747 - * added; discriminator support #1647 #1003 [j](https://github.com/j) - * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) - * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals() when _id option is set to false #1687 - * fixed; strict mode warnings #1686 - * fixed; $near GeoJSON casting #1683 - * fixed; nearSphere GeoJSON query builder - * fixed; population field selection w/ strings #1669 - * docs; custom validator messages - * docs; 10gen -> MongoDB - * docs; add Date method caveats #1598 - * docs; more validation details - * website; add "show code" for properties - * website; move "show code" links down - * tests; refactor 1703 - * tests; add test generator - * tests; validate formatMessage() throws - -3.7.3 (unstable) / 2013-08-22 -============================= - - * updated; warn when using an unstable version - * updated; mquery to 0.3.1 - * updated; mocha to 1.12.0 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * changed; no longer offically supporting node 0.6.x - * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) - * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) - * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) - * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; handle another versioning edge case #1520 - * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) - * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) - * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) - * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) - * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) - * make; suppress warning msg in test - * docs; state which branch is stable/unstable - * docs; mention that middleware does not run on Models - * tests; add script for continuously running tests - * tests; fixed versioning tests - * benchmarks; updated for pull requests - -3.7.2 (unstable) / 2013-08-15 -================== - - * fixed; model.remove() removes only what is necessary #1649 - * fixed; update() now only runs with cb or explicit true #1644 - * tests; race conditions in tests - * website; update guide - -3.7.1 (unstable) / 2013-08-13 -============================= - - * updated; driver to 1.3.18 (fixes memory leak) - * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) - * added; promise support to model.mapReduce() - * added; promise support to model.ensureIndexes() - * added; promise support to model.populate() - * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) - * fixed; model.update "overwrite" option works as documented - * fixed; query#remove() works as documented - * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) - * fixed; benchmarks to actually output valid json - * tests; added for nested and/or queries - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; replace deprecated method names - * tests; convert id to string - * docs; promise.fulfill() - -3.7.0 (unstable) / 2013-08-05 -=================== - - * changed; query.within getter is now a method -> query.within() - * changed; query.intersects getter is now a method -> query.intersects() - * deprecated; promise#addBack (use promise#onResolve) - * deprecated; promise#complete (use promise#fulfill) - * deprecated; promise#addCallback (use promise#onFulFill) - * deprecated; promise#addErrback (use promise#onReject) - * deprecated; query.nearSphere() (use query.near) - * deprecated; query.center() (use query.circle) - * deprecated; query.centerSphere() (use query.circle) - * deprecated; query#slaveOk (use query#read) - * removed; namedscope (undocumented and broken) #679 #642 #455 #379 - * added; benchmarks [ebensing](https://github.com/ebensing) - * added; publicly exposed connection states #1585 - * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) - * added; query method chain validation - * added; model.update `overwrite` option - * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) - * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) - * added; MongooseBuffer#subtype() - * added; model.create() now returns a promise #1340 - * added; support for `awaitdata` query option - * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) - * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) - * updated; integrate mquery #1562 [ebensing](https://github.com/ebensing) - * updated; error msg in doc.save() #1595 - * updated; bump driver to 1.3.15 - * updated; mpromise 0.3.0 - * updated; sliced 0.0.5 - * tests; fix sharding tests for MongoDB 2.4.5 - * tests; now 4-5 seconds faster - * tests; fix race condition - * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) - * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) - * website; add unstable docs - * website; many improvements - * website; fix copyright #1439 - * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) - * examples; improved and expanded [ebensing](https://github.com/ebensing) - -3.6.20 (stable) / 2013-09-23 -=================== - - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals w/ _id false #1687 - * fixed; strict mode warning #1686 - * docs; near/nearSphere - -3.6.19 (stable) / 2013-09-04 -================== - - * fixed; population field selection w/ strings #1669 - * docs; Date method caveats #1598 - -3.6.18 (stable) / 2013-08-22 -=================== - - * updated; warn when using an unstable version of mongoose - * updated; mocha to 1.12.0 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; properly exclude subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; cast error in findAndModify #1643 [aheuermann](https://github.com/aheuermann) - * website; update guide - * website; added documentation for safe:false and versioning interaction - * docs; mention that middleware dont run on Models - * docs; fix indexes link - * make; suppress warning msg in test - * tests; moar - -3.6.17 / 2013-08-13 -=================== - - * updated; driver to 1.3.18 (fixes memory leak) - * fixed; casting ref docs on creation #1606 - * docs; query options - -3.6.16 / 2013-08-08 -=================== - - * added; publicly expose connection states #1585 - * fixed; limit applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; positional operator casting in updates #1572 [ebensing](https://github.com/ebensing) - * updated; MongoDB driver to 1.3.17 - * updated; sliced to 0.0.5 - * website; tweak homepage - * tests; fixed + added - * docs; fix some examples - * docs; multi-mongos support details - * docs; auto open browser after starting static server - -3.6.15 / 2013-07-16 -================== - - * added; mongos failover support #1037 - * updated; make schematype return vals return self #1580 - * docs; add note to model.update #571 - * docs; document third param to document.save callback #1536 - * tests; tweek mongos test timeout - -3.6.14 / 2013-07-05 -=================== - - * updated; driver to 1.3.11 - * fixed; issue with findOneAndUpdate not returning null on upserts #1533 [ebensing](https://github.com/ebensing) - * fixed; missing return statement in SchemaArray#$geoIntersects() #1498 [bsrykt](https://github.com/bsrykt) - * fixed; wrong isSelected() behavior #1521 [kyano](https://github.com/kyano) - * docs; note about toObject behavior during save() - * docs; add callbacks details #1547 [nikmartin](https://github.com/nikmartin) - -3.6.13 / 2013-06-27 -=================== - - * fixed; calling model.distinct without conditions #1541 - * fixed; regression in Query#count() #1542 - * now working on 3.6.13 - -3.6.12 / 2013-06-25 -=================== - - * updated; driver to 1.3.10 - * updated; clearer capped collection error message #1509 [bitmage](https://github.com/bitmage) - * fixed; MongooseBuffer subtype loss during casting #1517 [zedgu](https://github.com/zedgu) - * fixed; docArray#id when doc.id is disabled #1492 - * fixed; docArray#id now supports matches on populated arrays #1492 [pgherveou](https://github.com/pgherveou) - * website; fix example - * website; improve _id disabling example - * website; fix typo #1494 [dejj](https://github.com/dejj) - * docs; added a 'Requesting new features' section #1504 [shovon](https://github.com/shovon) - * docs; improve subtypes description - * docs; clarify _id disabling - * docs: display by alphabetical order the methods list #1508 [nicolasleger](https://github.com/nicolasleger) - * tests; refactor isSelected checks - * tests; remove pointless test - * tests; fixed timeouts - -3.6.11 / 2013-05-15 -=================== - - * updated; driver to 1.3.5 - * fixed; compat w/ Object.create(null) #1484 #1485 - * fixed; cloning objects w/ missing constructors - * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) - * docs; add doc.increment() example - * docs; add $size example - * docs; add "distinct" example - -3.6.10 / 2013-05-09 -================== - - * update driver to 1.3.3 - * fixed; increment() works without other changes #1475 - * website; fix links to posterous - * docs; fix link #1472 - -3.6.9 / 2013-05-02 -================== - - * fixed; depopulation of mixed documents #1471 - * fixed; use of $options in array #1462 - * tests; fix race condition - * docs; fix default example - -3.6.8 / 2013-04-25 -================== - - * updated; driver to 1.3.0 - * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) - * tests; 4-5 seconds faster - -3.6.7 / 2013-04-19 -================== - - * fixed; population regression in 3.6.6 #1444 - -3.6.6 / 2013-04-18 -================== - - * fixed; saving populated new documents #1442 - * fixed; population regession in 3.6.5 #1441 - * website; fix copyright #1439 - -3.6.5 / 2013-04-15 -================== - - * fixed; strict:throw edge case using .set(path, val) - * fixed; schema.pathType() on some numbericAlpha paths - * fixed; numbericAlpha path versioning - * fixed; setting nested mixed paths #1418 - * fixed; setting nested objects with null prop #1326 - * fixed; regression in v3.6 population performance #1426 [vedmalex](https://github.com/vedmalex) - * fixed; read pref typos #1422 [kyano](https://github.com/kyano) - * docs; fix method example - * website; update faq - * website; add more deep links - * website; update poolSize docs - * website; add 3.6 release notes - * website; note about keepAlive - -3.6.4 / 2013-04-03 -================== - - * fixed; +field conflict with $slice #1370 - * fixed; nested deselection conflict #1333 - * fixed; RangeError in ValidationError.toString() #1296 - * fixed; do not save user defined transforms #1415 - * tests; fix race condition - -3.6.3 / 2013-04-02 -================== - - * fixed; setting subdocuments deeply nested fields #1394 - * fixed; regression: populated streams #1411 - * docs; mention hooks/validation with findAndModify - * docs; mention auth - * docs; add more links - * examples; add document methods example - * website; display "see" links for properties - * website; clean up homepage - -3.6.2 / 2013-03-29 -================== - - * fixed; corrupted sub-doc array #1408 - * fixed; document#update returns a Query #1397 - * docs; readpref strategy - -3.6.1 / 2013-03-27 -================== - - * added; populate support to findAndModify varients #1395 - * added; text index type to schematypes - * expose allowed index types as Schema.indexTypes - * fixed; use of `setMaxListeners` as path - * fixed; regression in node 0.6 on docs with > 10 arrays - * fixed; do not alter schema arguments #1364 - * fixed; subdoc#ownerDocument() #1385 - * website; change search id - * website; add search from google [jackdbernier](https://github.com/jackdbernier) - * website; fix link - * website; add 3.5.x docs release - * website; fix link - * docs; fix geometry - * docs; hide internal constructor - * docs; aggregation does not cast arguments #1399 - * docs; querystream options - * examples; added for population - -3.6.0 / 2013-03-18 -================== - - * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) - * changed; Buffer arrays can now contain nulls - * added; QueryStream transform option - * added; support for authSource driver option - * added; {mongoose,db}.modelNames() - * added; $push w/ $slice,$sort support (MongoDB 2.4) - * added; hashed index type (MongoDB 2.4) - * added; support for mongodb 2.4 geojson (MongoDB 2.4) - * added; value at time of validation error - * added; support for object literal schemas - * added; bufferCommands schema option - * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) - * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) - * added; allow adding uncasted docs to populated arrays and properties #570 - * added; doc#populated(path) stores original populated _ids - * added; lean population #1260 - * added; query.populate() now accepts an options object - * added; document#populate(opts, callback) - * added; Model.populate(docs, opts, callback) - * added; support for rich nested path population - * added; doc.array.remove(value) subdoc with _id value support #1278 - * added; optionally allow non-strict sets and updates - * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) - * added; promise#then - * added; promise#end - * fixed; use of `model` as doc property - * fixed; lean population #1382 - * fixed; empty object mixed defaults #1380 - * fixed; populate w/ deselected _id using string syntax - * fixed; attempted save of divergent populated arrays #1334 related - * fixed; better error msg when attempting toObject as property name - * fixed; non population buffer casting from doc - * fixed; setting populated paths #570 - * fixed; casting when added docs to populated arrays #570 - * fixed; prohibit updating arrays selected with $elemMatch #1334 - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * fixed; manual reconnection to single mongod - * fixed; Constructor / version exposure #1124 - * fixed; CastError race condition - * fixed; no longer swallowing misuse of subdoc#invalidate() - * fixed; utils.clone retains RegExp opts - * fixed; population of non-schema property - * fixed; allow updating versionKey #1265 - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; can now deselect populated doc _ids #1331 - * fixed; properly pass subtype to Binary in MongooseBuffer - * fixed; casting _id from document with non-ObjectId _id - * fixed; specifying schema type edge case { path: [{type: "String" }] } - * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) - * updated; driver to 1.2.14 - * updated; muri to 0.3.1 - * updated; mpromise to 0.2.1 - * updated; mocha 1.8.1 - * updated; mpath to 0.1.1 - * deprecated; pluralization will die in 4.x - * refactor; rename private methods to something unusable as doc properties - * refactor MongooseArray#remove - * refactor; move expires index to SchemaDate #1328 - * refactor; internal document properties #1171 #1184 - * tests; added - * docs; indexes - * docs; validation - * docs; populate - * docs; populate - * docs; add note about stream compatibility with node 0.8 - * docs; fix for private names - * docs; Buffer -> mongodb.Binary #1363 - * docs; auth options - * docs; improved - * website; update FAQ - * website; add more api links - * website; add 3.5.x docs to prior releases - * website; Change mongoose-types to an active repo [jackdbernier](https://github.com/jackdbernier) - * website; compat with node 0.10 - * website; add news section - * website; use T for generic type - * benchmark; make adjustable - -3.6.0rc1 / 2013-03-12 -====================== - - * refactor; rename private methods to something unusable as doc properties - * added; {mongoose,db}.modelNames() - * added; $push w/ $slice,$sort support (MongoDB 2.4) - * added; hashed index type (MongoDB 2.4) - * added; support for mongodb 2.4 geojson (MongoDB 2.4) - * added; value at time of validation error - * added; support for object literal schemas - * added; bufferCommands schema option - * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) - * fixed; lean population #1382 - * fixed; empty object mixed defaults #1380 - * fixed; populate w/ deselected _id using string syntax - * fixed; attempted save of divergent populated arrays #1334 related - * fixed; better error msg when attempting toObject as property name - * fixed; non population buffer casting from doc - * fixed; setting populated paths #570 - * fixed; casting when added docs to populated arrays #570 - * fixed; prohibit updating arrays selected with $elemMatch #1334 - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * fixed; manual reconnection to single mongod - * fixed; Constructor / version exposure #1124 - * fixed; CastError race condition - * fixed; no longer swallowing misuse of subdoc#invalidate() - * fixed; utils.clone retains RegExp opts - * fixed; population of non-schema property - * fixed; allow updating versionKey #1265 - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; can now deselect populated doc _ids #1331 - * updated; muri to 0.3.1 - * updated; driver to 1.2.12 - * updated; mpromise to 0.2.1 - * deprecated; pluralization will die in 4.x - * docs; Buffer -> mongodb.Binary #1363 - * docs; auth options - * docs; improved - * website; add news section - * benchmark; make adjustable - -3.6.0rc0 / 2013-02-03 -====================== - - * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) - * changed; Buffer arrays can now contain nulls - * fixed; properly pass subtype to Binary in MongooseBuffer - * fixed; casting _id from document with non-ObjectId _id - * fixed; specifying schema type edge case { path: [{type: "String" }] } - * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) - * refactor; move expires index to SchemaDate #1328 - * refactor; internal document properties #1171 #1184 - * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) - * added; allow adding uncasted docs to populated arrays and properties #570 - * added; doc#populated(path) stores original populated _ids - * added; lean population #1260 - * added; query.populate() now accepts an options object - * added; document#populate(opts, callback) - * added; Model.populate(docs, opts, callback) - * added; support for rich nested path population - * added; doc.array.remove(value) subdoc with _id value support #1278 - * added; optionally allow non-strict sets and updates - * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) - * added; promise#then - * added; promise#end - * updated; mocha 1.8.1 - * updated; muri to 0.3.0 - * updated; mpath to 0.1.1 - * updated; docs - -3.5.16 / 2013-08-13 -=================== - - * updated; driver to 1.3.18 - -3.5.15 / 2013-07-26 -================== - - * updated; sliced to 0.0.5 - * updated; driver to 1.3.12 - * fixed; regression in Query#count() due to driver change - * tests; fixed timeouts - * tests; handle differing test uris - -3.5.14 / 2013-05-15 -=================== - - * updated; driver to 1.3.5 - * fixed; compat w/ Object.create(null) #1484 #1485 - * fixed; cloning objects missing constructors - * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) - -3.5.13 / 2013-05-09 -================== - - * update driver to 1.3.3 - * fixed; use of $options in array #1462 - -3.5.12 / 2013-04-25 -=================== - - * updated; driver to 1.3.0 - * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) - * fixed; read pref typos #1422 [kyano](https://github.com/kyano) - -3.5.11 / 2013-04-03 -================== - - * fixed; +field conflict with $slice #1370 - * fixed; RangeError in ValidationError.toString() #1296 - * fixed; nested deselection conflict #1333 - * remove time from Makefile - -3.5.10 / 2013-04-02 -================== - - * fixed; setting subdocuments deeply nested fields #1394 - * fixed; do not alter schema arguments #1364 - -3.5.9 / 2013-03-15 -================== - - * updated; driver to 1.2.14 - * added; support for authSource driver option (mongodb 2.4) - * added; QueryStream transform option (node 0.10 helper) - * fixed; backport for saving required populated buffers - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * test; added for saveable required populated buffers - * test; added for #1365 - * test; add authSource test - -3.5.8 / 2013-03-12 -================== - - * added; auth option in connection [geoah](https://github.com/geoah) - * fixed; CastError race condition - * docs; add note about stream compatibility with node 0.8 - -3.5.7 / 2013-02-22 -================== - - * updated; driver to 1.2.13 - * updated; muri to 0.3.1 #1347 - * fixed; utils.clone retains RegExp opts #1355 - * fixed; deepEquals RegExp support - * tests; fix a connection test - * website; clean up docs [afshinm](https://github.com/afshinm) - * website; update homepage - * website; migragtion: emphasize impact of strict docs #1264 - -3.5.6 / 2013-02-14 -================== - - * updated; driver to 1.2.12 - * fixed; properly pass Binary subtype - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; use correct node engine version - * fixed; display empty docs as {} in log output #953 follow up - * improved; "bad $within $box argument" error message - * populate; add unscientific benchmark - * website; add stack overflow to help section - * website; use better code font #1336 [risseraka](https://github.com/risseraka) - * website; clarify where help is available - * website; fix source code links #1272 [floatingLomas](https://github.com/floatingLomas) - * docs; be specific about _id schema option #1103 - * docs; add ensureIndex error handling example - * docs; README - * docs; CONTRIBUTING.md - -3.5.5 / 2013-01-29 -================== - - * updated; driver to 1.2.11 - * removed; old node < 0.6x shims - * fixed; documents with Buffer _ids equality - * fixed; MongooseBuffer properly casts numbers - * fixed; reopening closed connection on alt host/port #1287 - * docs; fixed typo in Readme #1298 [rened](https://github.com/rened) - * docs; fixed typo in migration docs [Prinzhorn](https://github.com/Prinzhorn) - * docs; fixed incorrect annotation in SchemaNumber#min [bilalq](https://github.com/bilalq) - * docs; updated - -3.5.4 / 2013-01-07 -================== - - * changed; "_pres" & "_posts" are now reserved pathnames #1261 - * updated; driver to 1.2.8 - * fixed; exception when reopening a replica set. #1263 [ethankan](https://github.com/ethankan) - * website; updated - -3.5.3 / 2012-12-26 -================== - - * added; support for geo object notation #1257 - * fixed; $within query casting with arrays - * fixed; unix domain socket support #1254 - * updated; driver to 1.2.7 - * updated; muri to 0.0.5 - -3.5.2 / 2012-12-17 -================== - - * fixed; using auth with replica sets #1253 - -3.5.1 / 2012-12-12 -================== - - * fixed; regression when using subdoc with `path` as pathname #1245 [daeq](https://github.com/daeq) - * fixed; safer db option checks - * updated; driver to 1.2.5 - * website; add more examples - * website; clean up old docs - * website; fix prev release urls - * docs; clarify streaming with HTTP responses - -3.5.0 / 2012-12-10 -================== - - * added; paths to CastErrors #1239 - * added; support for mongodb connection string spec #1187 - * added; post validate event - * added; Schema#get (to retrieve schema options) - * added; VersionError #1071 - * added; npmignore [hidekiy](https://github.com/hidekiy) - * update; driver to 1.2.3 - * fixed; stackoverflow in setter #1234 - * fixed; utils.isObject() - * fixed; do not clobber user specified driver writeConcern #1227 - * fixed; always pass current document to post hooks - * fixed; throw error when user attempts to overwrite a model - * fixed; connection.model only caches on connection #1209 - * fixed; respect conn.model() creation when matching global model exists #1209 - * fixed; passing model name + collection name now always honors collection name - * fixed; setting virtual field to an empty object #1154 - * fixed; subclassed MongooseErrors exposure, now available in mongoose.Error.xxxx - * fixed; model.remove() ignoring callback when executed twice [daeq](https://github.com/daeq) #1210 - * docs; add collection option to schema api docs #1222 - * docs; NOTE about db safe options - * docs; add post hooks docs - * docs; connection string options - * docs; middleware is not executed with Model.remove #1241 - * docs; {g,s}etter introspection #777 - * docs; update validation docs - * docs; add link to plugins page - * docs; clarify error returned by unique indexes #1225 - * docs; more detail about disabling autoIndex behavior - * docs; add homepage section to package (npm docs mongoose) - * docs; more detail around collection name pluralization #1193 - * website; add .important css - * website; update models page - * website; update getting started - * website; update quick start - -3.4.0 / 2012-11-10 -================== - - * added; support for generic toJSON/toObject transforms #1160 #1020 #1197 - * added; doc.set() merge support #1148 [NuORDER](https://github.com/NuORDER) - * added; query#add support #1188 [aleclofabbro](https://github.com/aleclofabbro) - * changed; adding invalid nested paths to non-objects throws 4216f14 - * changed; fixed; stop invalid function cloning (internal fix) - * fixed; add query $and casting support #1180 [anotheri](https://github.com/anotheri) - * fixed; overwriting of query arguments #1176 - * docs; fix expires examples - * docs; transforms - * docs; schema `collection` option docs [hermanjunge](https://github.com/hermanjunge) - * website; updated - * tests; added - -3.3.1 / 2012-10-11 -================== - - * fixed; allow goose.connect(uris, dbname, opts) #1144 - * docs; persist API private checked state across page loads - -3.3.0 / 2012-10-10 -================== - - * fixed; passing options as 2nd arg to connect() #1144 - * fixed; race condition after no-op save #1139 - * fixed; schema field selection application in findAndModify #1150 - * fixed; directly setting arrays #1126 - * updated; driver to 1.1.11 - * updated; collection pluralization rules [mrickard](https://github.com/mrickard) - * tests; added - * docs; updated - -3.2.2 / 2012-10-08 -================== - - * updated; driver to 1.1.10 #1143 - * updated; use sliced 0.0.3 - * fixed; do not recast embedded docs unnecessarily - * fixed; expires schema option helper #1132 - * fixed; built in string setters #1131 - * fixed; debug output for Dates/ObjectId properties #1129 - * docs; fixed Javascript syntax error in example [olalonde](https://github.com/olalonde) - * docs; fix toJSON example #1137 - * docs; add ensureIndex production notes - * docs; fix spelling - * docs; add blogposts about v3 - * website; updated - * removed; undocumented inGroupsOf util - * tests; added - -3.2.1 / 2012-09-28 -================== - - * fixed; remove query batchSize option default of 1000 https://github.com/learnboost/mongoose/commit/3edaa8651 - * docs; updated - * website; updated - -3.2.0 / 2012-09-27 -================== - - * added; direct array index assignment with casting support `doc.array.set(index, value)` - * fixed; QueryStream#resume within same tick as pause() #1116 - * fixed; default value validatation #1109 - * fixed; array splice() not casting #1123 - * fixed; default array construction edge case #1108 - * fixed; query casting for inequalities in arrays #1101 [dpatti](https://github.com/dpatti) - * tests; added - * website; more documentation - * website; fixed layout issue #1111 [SlashmanX](https://github.com/SlashmanX) - * website; refactored [guille](https://github.com/guille) - -3.1.2 / 2012-09-10 -================== - - * added; ReadPreferrence schema option #1097 - * updated; driver to 1.1.7 - * updated; default query batchSize to 1000 - * fixed; we now cast the mapReduce query option #1095 - * fixed; $elemMatch+$in with field selection #1091 - * fixed; properly cast $elemMatch+$in conditions #1100 - * fixed; default field application of subdocs #1027 - * fixed; querystream prematurely dying #1092 - * fixed; querystream never resumes when paused at getMore boundries #1092 - * fixed; querystream occasionally emits data events after destroy #1092 - * fixed; remove unnecessary ObjectId creation in querystream - * fixed; allow ne(boolean) again #1093 - * docs; add populate/field selection syntax notes - * docs; add toObject/toJSON options detail - * docs; `read` schema option - -3.1.1 / 2012-08-31 -================== - - * updated; driver to 1.1.6 - -3.1.0 / 2012-08-29 -================== - - * changed; fixed; directly setting nested objects now overwrites entire object (previously incorrectly merged them) - * added; read pref support (mongodb 2.2) 205a709c - * added; aggregate support (mongodb 2.2) f3a5bd3d - * added; virtual {g,s}etter introspection (#1070) - * updated; docs [brettz9](https://github.com/brettz9) - * updated; driver to 1.1.5 - * fixed; retain virtual setter return values (#1069) - -3.0.3 / 2012-08-23 -================== - - * fixed; use of nested paths beginning w/ numbers #1062 - * fixed; query population edge case #1053 #1055 [jfremy](https://github.com/jfremy) - * fixed; simultaneous top and sub level array modifications #1073 - * added; id and _id schema option aliases + tests - * improve debug formatting to allow copy/paste logged queries into mongo shell [eknkc](https://github.com/eknkc) - * docs - -3.0.2 / 2012-08-17 -================== - - * added; missing support for v3 sort/select syntax to findAndModify helpers (#1058) - * fixed; replset fullsetup event emission - * fixed; reconnected event for replsets - * fixed; server reconnection setting discovery - * fixed; compat with non-schema path props using positional notation (#1048) - * fixed; setter/casting order (#665) - * docs; updated - -3.0.1 / 2012-08-11 -================== - - * fixed; throw Error on bad validators (1044) - * fixed; typo in EmbeddedDocument#parentArray [lackac] - * fixed; repair mongoose.SchemaTypes alias - * updated; docs - -3.0.0 / 2012-08-07 -================== - - * removed; old subdocument#commit method - * fixed; setting arrays of matching docs [6924cbc2] - * fixed; doc!remove event now emits in save order as save for consistency - * fixed; pre-save hooks no longer fire on subdocuments when validation fails - * added; subdoc#parent() and subdoc#parentArray() to access subdocument parent objects - * added; query#lean() helper - -3.0.0rc0 / 2012-08-01 -===================== - - * fixed; allow subdoc literal declarations containing "type" pathname (#993) - * fixed; unsetting a default array (#758) - * fixed; boolean $in queries (#998) - * fixed; allow use of `options` as a pathname (#529) - * fixed; `model` is again a permitted schema path name - * fixed; field selection option on subdocs (#1022) - * fixed; handle another edge case with subdoc saving (#975) - * added; emit save err on model if listening - * added; MongoDB TTL collection support (#1006) - * added; $center options support - * added; $nearSphere and $polygon support - * updated; driver version to 1.1.2 - -3.0.0alpha2 / 2012-07-18 -========================= - - * changed; index errors are now emitted on their model and passed to an optional callback (#984) - * fixed; specifying index along with sparse/unique option no longer overwrites (#1004) - * fixed; never swallow connection errors (#618) - * fixed; creating object from model with emded object no longer overwrites defaults [achurkin] (#859) - * fixed; stop needless validation of unchanged/unselected fields (#891) - * fixed; document#equals behavior of objectids (#974) - * fixed; honor the minimize schema option (#978) - * fixed; provide helpful error msgs when reserved schema path is used (#928) - * fixed; callback to conn#disconnect is optional (#875) - * fixed; handle missing protocols in connection urls (#987) - * fixed; validate args to query#where (#969) - * fixed; saving modified/removed subdocs (#975) - * fixed; update with $pull from Mixed array (#735) - * fixed; error with null shard key value - * fixed; allow unsetting enums (#967) - * added; support for manual index creation (#984) - * added; support for disabled auto-indexing (#984) - * added; support for preserving MongooseArray#sort changes (#752) - * added; emit state change events on connection - * added; support for specifying BSON subtype in MongooseBuffer#toObject [jcrugzz] - * added; support for disabled versioning (#977) - * added; implicit "new" support for models and Schemas - -3.0.0alpha1 / 2012-06-15 -========================= - - * removed; doc#commit (use doc#markModified) - * removed; doc.modified getter (#950) - * removed; mongoose{connectSet,createSetConnection}. use connect,createConnection instead - * removed; query alias methods 1149804c - * removed; MongooseNumber - * changed; now creating indexes in background by default - * changed; strict mode now enabled by default (#952) - * changed; doc#modifiedPaths is now a method (#950) - * changed; getters no longer cast (#820); casting happens during set - * fixed; no need to pass updateArg to findOneAndUpdate (#931) - * fixed: utils.merge bug when merging nested non-objects. [treygriffith] - * fixed; strict:throw should produce errors in findAndModify (#963) - * fixed; findAndUpdate no longer overwrites document (#962) - * fixed; setting default DocumentArrays (#953) - * fixed; selection of _id with schema deselection (#954) - * fixed; ensure promise#error emits instanceof Error - * fixed; CursorStream: No stack overflow on any size result (#929) - * fixed; doc#remove now passes safe options - * fixed; invalid use of $set during $pop - * fixed; array#{$pop,$shift} mirror MongoDB behavior - * fixed; no longer test non-required vals in string match (#934) - * fixed; edge case with doc#inspect - * fixed; setter order (#665) - * fixed; setting invalid paths in strict mode (#916) - * fixed; handle docs without id in DocumentArray#id method (#897) - * fixed; do not save virtuals during model.update (#894) - * fixed; sub doc toObject virtuals application (#889) - * fixed; MongooseArray#pull of ObjectId (#881) - * fixed; handle passing db name with any repl set string - * fixed; default application of selected fields (#870) - * fixed; subdoc paths reported in validation errors (#725) - * fixed; incorrect reported num of affected docs in update ops (#862) - * fixed; connection assignment in Model#model (#853) - * fixed; stringifying arrays of docs (#852) - * fixed; modifying subdoc and parent array works (#842) - * fixed; passing undefined to next hook (#785) - * fixed; Query#{update,remove}() works without callbacks (#788) - * fixed; set/updating nested objects by parent pathname (#843) - * fixed; allow null in number arrays (#840) - * fixed; isNew on sub doc after insertion error (#837) - * fixed; if an insert fails, set isNew back to false [boutell] - * fixed; isSelected when only _id is selected (#730) - * fixed; setting an unset default value (#742) - * fixed; query#sort error messaging (#671) - * fixed; support for passing $options with $regex - * added; array of object literal notation in schema creates DocumentArrays - * added; gt,gte,lt,lte query support for arrays (#902) - * added; capped collection support (#938) - * added; document versioning support - * added; inclusion of deselected schema path (#786) - * added; non-atomic array#pop - * added; EmbeddedDocument constructor is now exposed in DocArray#create 7cf8beec - * added; mapReduce support (#678) - * added; support for a configurable minimize option #to{Object,JSON}(option) (#848) - * added; support for strict: `throws` [regality] - * added; support for named schema types (#795) - * added; to{Object,JSON} schema options (#805) - * added; findByIdAnd{Update,Remove}() - * added; findOneAnd{Update,Remove}() - * added; query.setOptions() - * added; instance.update() (#794) - * added; support specifying model in populate() [DanielBaulig] - * added; `lean` query option [gitfy] - * added; multi-atomic support to MongooseArray#nonAtomicPush - * added; support for $set + other $atomic ops on single array - * added; tests - * updated; driver to 1.0.2 - * updated; query.sort() syntax to mirror query.select() - * updated; clearer cast error msg for array numbers - * updated; docs - * updated; doc.clone 3x faster (#950) - * updated; only create _id if necessary (#950) - -2.7.3 / 2012-08-01 -================== - - * fixed; boolean $in queries (#998) - * fixed field selection option on subdocs (#1022) - -2.7.2 / 2012-07-18 -================== - - * fixed; callback to conn#disconnect is optional (#875) - * fixed; handle missing protocols in connection urls (#987) - * fixed; saving modified/removed subdocs (#975) - * updated; tests - -2.7.1 / 2012-06-26 -=================== - - * fixed; sharding: when a document holds a null as a value of the shard key - * fixed; update() using $pull on an array of Mixed (gh-735) - * deprecated; MongooseNumber#{inc, increment, decrement} methods - * tests; now using mocha - -2.7.0 / 2012-06-14 -=================== - - * added; deprecation warnings to methods being removed in 3.x - -2.6.8 / 2012-06-14 -=================== - - * fixed; edge case when using 'options' as a path name (#961) - -2.6.7 / 2012-06-08 -=================== - - * fixed; ensure promise#error always emits instanceof Error - * fixed; selection of _id w/ another excluded path (#954) - * fixed; setting default DocumentArrays (#953) - -2.6.6 / 2012-06-06 -=================== - - * fixed; stack overflow in query stream with large result sets (#929) - * added; $gt, $gte, $lt, $lte support to arrays (#902) - * fixed; pass option `safe` along to doc#remove() calls - -2.6.5 / 2012-05-24 -=================== - - * fixed; do not save virtuals in Model.update (#894) - * added; missing $ prefixed query aliases (going away in 3.x) (#884) [timoxley] - * fixed; setting invalid paths in strict mode (#916) - * fixed; resetting isNew after insert failure (#837) [boutell] - -2.6.4 / 2012-05-15 -=================== - - * updated; backport string regex $options to 2.x - * updated; use driver 1.0.2 (performance improvements) (#914) - * fixed; calling MongooseDocumentArray#id when the doc has no _id (#897) - -2.6.3 / 2012-05-03 -=================== - - * fixed; repl-set connectivity issues during failover on MongoDB 2.0.1 - * updated; driver to 1.0.0 - * fixed; virtuals application of subdocs when using toObject({ virtuals: true }) (#889) - * fixed; MongooseArray#pull of ObjectId correctly updates the array itself (#881) - -2.6.2 / 2012-04-30 -=================== - - * fixed; default field application of selected fields (#870) - -2.6.1 / 2012-04-30 -=================== - - * fixed; connection assignment in mongoose#model (#853, #877) - * fixed; incorrect reported num of affected docs in update ops (#862) - -2.6.0 / 2012-04-19 -=================== - - * updated; hooks.js to 0.2.1 - * fixed; issue with passing undefined to a hook callback. thanks to [chrisleishman] for reporting. - * fixed; updating/setting nested objects in strict schemas (#843) as reported by [kof] - * fixed; Query#{update,remove}() work without callbacks again (#788) - * fixed; modifying subdoc along with parent array $atomic op (#842) - -2.5.14 / 2012-04-13 -=================== - - * fixed; setting an unset default value (#742) - * fixed; doc.isSelected(otherpath) when only _id is selected (#730) - * updated; docs - -2.5.13 / 2012-03-22 -=================== - - * fixed; failing validation of unselected required paths (#730,#713) - * fixed; emitting connection error when only one listener (#759) - * fixed; MongooseArray#splice was not returning values (#784) [chrisleishman] - -2.5.12 / 2012-03-21 -=================== - - * fixed; honor the `safe` option in all ensureIndex calls - * updated; node-mongodb-native driver to 0.9.9-7 - -2.5.11 / 2012-03-15 -=================== - - * added; introspection for getters/setters (#745) - * updated; node-mongodb-driver to 0.9.9-5 - * added; tailable method to Query (#769) [holic] - * fixed; Number min/max validation of null (#764) [btamas] - * added; more flexible user/password connection options (#738) [KarneAsada] - -2.5.10 / 2012-03-06 -=================== - - * updated; node-mongodb-native driver to 0.9.9-4 - * added; Query#comment() - * fixed; allow unsetting arrays - * fixed; hooking the set method of subdocuments (#746) - * fixed; edge case in hooks - * fixed; allow $id and $ref in queries (fixes compatibility with mongoose-dbref) (#749) [richtera] - * added; default path selection to SchemaTypes - -2.5.9 / 2012-02-22 -=================== - - * fixed; properly cast nested atomic update operators for sub-documents - -2.5.8 / 2012-02-21 -=================== - - * added; post 'remove' middleware includes model that was removed (#729) [timoxley] - -2.5.7 / 2012-02-09 -=================== - - * fixed; RegExp validators on node >= v0.6.x - -2.5.6 / 2012-02-09 -=================== - - * fixed; emit errors returned from db.collection() on the connection (were being swallowed) - * added; can add multiple validators in your schema at once (#718) [diogogmt] - * fixed; strict embedded documents (#717) - * updated; docs [niemyjski] - * added; pass number of affected docs back in model.update/save - -2.5.5 / 2012-02-03 -=================== - - * fixed; RangeError: maximum call stack exceed error when removing docs with Number _id (#714) - -2.5.4 / 2012-02-03 -=================== - - * fixed; RangeError: maximum call stack exceed error (#714) - -2.5.3 / 2012-02-02 -=================== - - * added; doc#isSelected(path) - * added; query#equals() - * added; beta sharding support - * added; more descript error msgs (#700) [obeleh] - * added; document.modifiedPaths (#709) [ljharb] - * fixed; only functions can be added as getters/setters (#707,704) [ljharb] - -2.5.2 / 2012-01-30 -=================== - - * fixed; rollback -native driver to 0.9.7-3-5 (was causing timeouts and other replica set weirdness) - * deprecated; MongooseNumber (will be moved to a separate repo for 3.x) - * added; init event is emitted on schemas - -2.5.1 / 2012-01-27 -=================== - - * fixed; honor strict schemas in Model.update (#699) - -2.5.0 / 2012-01-26 -=================== - - * added; doc.toJSON calls toJSON on embedded docs when exists [jerem] - * added; populate support for refs of type Buffer (#686) [jerem] - * added; $all support for ObjectIds and Dates (#690) - * fixed; virtual setter calling on instantiation when strict: true (#682) [hunterloftis] - * fixed; doc construction triggering getters (#685) - * fixed; MongooseBuffer check in deepEquals (#688) - * fixed; range error when using Number _ids with `instance.save()` (#691) - * fixed; isNew on embedded docs edge case (#680) - * updated; driver to 0.9.8-3 - * updated; expose `model()` method within static methods - -2.4.10 / 2012-01-10 -=================== - - * added; optional getter application in .toObject()/.toJSON() (#412) - * fixed; nested $operators in $all queries (#670) - * added; $nor support (#674) - * fixed; bug when adding nested schema (#662) [paulwe] - -2.4.9 / 2012-01-04 -=================== - - * updated; driver to 0.9.7-3-5 to fix Linux performance degradation on some boxes - -2.4.8 / 2011-12-22 -=================== - - * updated; bump -native to 0.9.7.2-5 - * fixed; compatibility with date.js (#646) [chrisleishman] - * changed; undocumented schema "lax" option to "strict" - * fixed; default value population for strict schemas - * updated; the nextTick helper for small performance gain. 1bee2a2 - -2.4.7 / 2011-12-16 -=================== - - * fixed; bug in 2.4.6 with path setting - * updated; bump -native to 0.9.7.2-1 - * added; strict schema option [nw] - -2.4.6 / 2011-12-16 -=================== - - * fixed; conflicting mods on update bug [sirlantis] - * improved; doc.id getter performance - -2.4.5 / 2011-12-14 -=================== - - * fixed; bad MongooseArray behavior in 2.4.2 - 2.4.4 - -2.4.4 / 2011-12-14 -=================== - - * fixed; MongooseArray#doAtomics throwing after sliced - -2.4.3 / 2011-12-14 -=================== - - * updated; system.profile schema for MongoDB 2x - -2.4.2 / 2011-12-12 -=================== - - * fixed; partially populating multiple children of subdocs (#639) [kenpratt] - * fixed; allow Update of numbers to null (#640) [jerem] - -2.4.1 / 2011-12-02 -=================== - - * added; options support for populate() queries - * updated; -native driver to 0.9.7-1.4 - -2.4.0 / 2011-11-29 -=================== - - * added; QueryStreams (#614) - * added; debug print mode for development - * added; $within support to Array queries (#586) [ggoodale] - * added; $centerSphere query support - * fixed; $within support - * added; $unset is now used when setting a path to undefined (#519) - * added; query#batchSize support - * updated; docs - * updated; -native driver to 0.9.7-1.3 (provides Windows support) - -2.3.13 / 2011-11-15 -=================== - - * fixed; required validation for Refs (#612) [ded] - * added; $nearSphere support for Arrays (#610) - -2.3.12 / 2011-11-09 -=================== - - * fixed; regression, objects passed to Model.update should not be changed (#605) - * fixed; regression, empty Model.update should not be executed - -2.3.11 / 2011-11-08 -=================== - - * fixed; using $elemMatch on arrays of Mixed types (#591) - * fixed; allow using $regex when querying Arrays (#599) - * fixed; calling Model.update with no atomic keys (#602) - -2.3.10 / 2011-11-05 -=================== - - * fixed; model.update casting for nested paths works (#542) - -2.3.9 / 2011-11-04 -================== - - * fixed; deepEquals check for MongooseArray returned false - * fixed; reset modified flags of embedded docs after save [gitfy] - * fixed; setting embedded doc with identical values no longer marks modified [gitfy] - * updated; -native driver to 0.9.6.23 [mlazarov] - * fixed; Model.update casting (#542, #545, #479) - * fixed; populated refs no longer fail required validators (#577) - * fixed; populating refs of objects with custom ids works - * fixed; $pop & $unset work with Model.update (#574) - * added; more helpful debugging message for Schema#add (#578) - * fixed; accessing .id when no _id exists now returns null (#590) - -2.3.8 / 2011-10-26 -================== - - * added; callback to query#findOne is now optional (#581) - -2.3.7 / 2011-10-24 -================== - - * fixed; wrapped save/remove callbacks in nextTick to mitigate -native swallowing thrown errors - -2.3.6 / 2011-10-21 -================== - - * fixed; exclusion of embedded doc _id from query results (#541) - -2.3.5 / 2011-10-19 -================== - - * fixed; calling queries without passing a callback works (#569) - * fixed; populate() works with String and Number _ids too (#568) - -2.3.4 / 2011-10-18 -================== - - * added; Model.create now accepts an array as a first arg - * fixed; calling toObject on a DocumentArray with nulls no longer throws - * fixed; calling inspect on a DocumentArray with nulls no longer throws - * added; MongooseArray#unshift support - * fixed; save hooks now fire on embedded documents [gitfy] (#456) - * updated; -native driver to 0.9.6-22 - * fixed; correctly pass $addToSet op instead of $push - * fixed; $addToSet properly detects dates - * fixed; $addToSet with multiple items works - * updated; better node 0.6 Buffer support - -2.3.3 / 2011-10-12 -================== - - * fixed; population conditions in multi-query settings [vedmalex] (#563) - * fixed; now compatible with Node v0.5.x - -2.3.2 / 2011-10-11 -================== - - * fixed; population of null subdoc properties no longer hangs (#561) - -2.3.1 / 2011-10-10 -================== - - * added; support for Query filters to populate() [eneko] - * fixed; querying with number no longer crashes mongodb (#555) [jlbyrey] - * updated; version of -native driver to 0.9.6-21 - * fixed; prevent query callbacks that throw errors from corrupting -native connection state - -2.3.0 / 2011-10-04 -================== - - * fixed; nulls as default values for Boolean now works as expected - * updated; version of -native driver to 0.9.6-20 - -2.2.4 / 2011-10-03 -================== - - * fixed; populate() works when returned array contains undefined/nulls - -2.2.3 / 2011-09-29 -================== - - * updated; version of -native driver to 0.9.6-19 - -2.2.2 / 2011-09-28 -================== - - * added; $regex support to String [davidandrewcope] - * added; support for other contexts like repl etc (#535) - * fixed; clear modified state properly after saving - * added; $addToSet support to Array - -2.2.1 / 2011-09-22 -================== - - * more descript error when casting undefined to string - * updated; version of -native driver to 0.9.6-18 - -2.2.0 / 2011-09-22 -================== - - * fixed; maxListeners warning on schemas with many arrays (#530) - * changed; return / apply defaults based on fields selected in query (#423) - * fixed; correctly detect Mixed types within schema arrays (#532) - -2.1.4 / 2011-09-20 -================== - - * fixed; new private methods that stomped on users code - * changed; finished removing old "compat" support which did nothing - -2.1.3 / 2011-09-16 -================== - - * updated; version of -native driver to 0.9.6-15 - * added; emit `error` on connection when open fails [edwardhotchkiss] - * added; index support to Buffers (thanks justmoon for helping track this down) - * fixed; passing collection name via schema in conn.model() now works (thanks vedmalex for reporting) - -2.1.2 / 2011-09-07 -================== - - * fixed; Query#find with no args no longer throws - -2.1.1 / 2011-09-07 -================== - - * added; support Model.count(fn) - * fixed; compatibility with node >=0.4.0 < 0.4.3 - * added; pass model.options.safe through with .save() so w:2, wtimeout:5000 options work [andrewjstone] - * added; support for $type queries - * added; support for Query#or - * added; more tests - * optimized populate queries - -2.1.0 / 2011-09-01 -================== - - * changed; document#validate is a public method - * fixed; setting number to same value no longer marks modified (#476) [gitfy] - * fixed; Buffers shouldn't have default vals - * added; allow specifying collection name in schema (#470) [ixti] - * fixed; reset modified paths and atomics after saved (#459) - * fixed; set isNew on embedded docs to false after save - * fixed; use self to ensure proper scope of options in doOpenSet (#483) [andrewjstone] - -2.0.4 / 2011-08-29 -================== - - * Fixed; Only send the depopulated ObjectId instead of the entire doc on save (DBRefs) - * Fixed; Properly cast nested array values in Model.update (the data was stored in Mongo incorrectly but recast on document fetch was "fixing" it) - -2.0.3 / 2011-08-28 -================== - - * Fixed; manipulating a populated array no longer causes infinite loop in BSON serializer during save (#477) - * Fixed; populating an empty array no longer hangs foreeeeeeeever (#481) - -2.0.2 / 2011-08-25 -================== - - * Fixed; Maintain query option key order (fixes 'bad hint' error from compound query hints) - -2.0.1 / 2011-08-25 -================== - - * Fixed; do not over-write the doc when no valide props exist in Model.update (#473) - -2.0.0 / 2011-08-24 -=================== - - * Added; support for Buffers [justmoon] - * Changed; improved error handling [maelstrom] - * Removed: unused utils.erase - * Fixed; support for passing other context object into Schemas (#234) [Sija] - * Fixed; getters are no longer circular refs to themselves (#366) - * Removed; unused compat.js - * Fixed; getter/setter scopes are set properly - * Changed; made several private properties more obvious by prefixing _ - * Added; DBRef support [guille] - * Changed; removed support for multiple collection names per model - * Fixed; no longer applying setters when document returned from db - * Changed; default auto_reconnect to true - * Changed; Query#bind no longer clones the query - * Fixed; Model.update now accepts $pull, $inc and friends (#404) - * Added; virtual type option support [nw] - -1.8.4 / 2011-08-21 -=================== - - * Fixed; validation bug when instantiated with non-schema properties (#464) [jmreidy] - -1.8.3 / 2011-08-19 -=================== - - * Fixed; regression in connection#open [jshaw86] - -1.8.2 / 2011-08-17 -=================== - - * fixed; reset connection.readyState after failure [tomseago] - * fixed; can now query positionally for non-embedded docs (arrays of numbers/strings etc) - * fixed; embedded document query casting - * added; support for passing options to node-mongo-native db, server, and replsetserver [tomseago] - -1.8.1 / 2011-08-10 -=================== - - * fixed; ObjectIds were always marked modified - * fixed; can now query using document instances - * fixed; can now query/update using documents with subdocs - -1.8.0 / 2011-08-04 -=================== - - * fixed; can now use $all with String and Number - * fixed; can query subdoc array with $ne: null - * fixed; instance.subdocs#id now works with custom _ids - * fixed; do not apply setters when doc returned from db (change in bad behavior) - -1.7.4 / 2011-07-25 -=================== - - * fixed; sparse now a valid seperate schema option - * fixed; now catching cast errors in queries - * fixed; calling new Schema with object created in vm.runInNewContext now works (#384) [Sija] - * fixed; String enum was disallowing null - * fixed; Find by nested document _id now works (#389) - -1.7.3 / 2011-07-16 -=================== - - * fixed; MongooseArray#indexOf now works with ObjectIds - * fixed; validation scope now set properly (#418) - * fixed; added missing colors dependency (#398) - -1.7.2 / 2011-07-13 -=================== - - * changed; node-mongodb-native driver to v0.9.6.7 - -1.7.1 / 2011-07-12 -=================== - - * changed; roll back node-mongodb-native driver to v0.9.6.4 - -1.7.0 / 2011-07-12 -=================== - - * fixed; collection name misspelling [mathrawka] - * fixed; 2nd param is required for ReplSetServers [kevinmarvin] - * fixed; MongooseArray behaves properly with Object.keys - * changed; node-mongodb-native driver to v0.9.6.6 - * fixed/changed; Mongodb segfault when passed invalid ObjectId (#407) - - This means invalid data passed to the ObjectId constructor will now error - -1.6.0 / 2011-07-07 -=================== - - * changed; .save() errors are now emitted on the instances db instead of the instance 9782463fc - * fixed; errors occurring when creating indexes now properly emit on db - * added; $maxDistance support to MongooseArrays - * fixed; RegExps now work with $all - * changed; node-mongodb-native driver to v0.9.6.4 - * fixed; model names are now accessible via .modelName - * added; Query#slaveOk support - -1.5.0 / 2011-06-27 -=================== - - * changed; saving without a callback no longer ignores the error (@bnoguchi) - * changed; hook-js version bump to 0.1.9 - * changed; node-mongodb-native version bumped to 0.9.6.1 - When .remove() doesn't - return an error, null is no longer passed. - * fixed; two memory leaks (@justmoon) - * added; sparse index support - * added; more ObjectId conditionals (gt, lt, gte, lte) (@phillyqueso) - * added; options are now passed in model#remote (@JerryLuke) - -1.4.0 / 2011-06-10 -=================== - - * bumped hooks-js dependency (fixes issue passing null as first arg to next()) - * fixed; document#inspect now works properly with nested docs - * fixed; 'set' now works as a schema attribute (GH-365) - * fixed; _id is now set properly within pre-init hooks (GH-289) - * added; Query#distinct / Model#distinct support (GH-155) - * fixed; embedded docs now can use instance methods (GH-249) - * fixed; can now overwrite strings conflicting with schema type - -1.3.7 / 2011-06-03 -=================== - - * added MongooseArray#splice support - * fixed; 'path' is now a valid Schema pathname - * improved hooks (utilizing https://github.com/bnoguchi/hooks-js) - * fixed; MongooseArray#$shift now works (never did) - * fixed; Document.modified no longer throws - * fixed; modifying subdoc property sets modified paths for subdoc and parent doc - * fixed; marking subdoc path as modified properly persists the value to the db - * fixed; RexExps can again be saved ( #357 ) - -1.3.6 / 2011-05-18 -=================== - - * fixed; corrected casting for queries against array types - * added; Document#set now accepts Document instances - -1.3.5 / 2011-05-17 -=================== - - * fixed; $ne queries work properly with single vals - * added; #inspect() methods to improve console.log output - -1.3.4 / 2011-05-17 -=================== - - * fixed; find by Date works as expected (#336) - * added; geospatial 2d index support - * added; support for $near (#309) - * updated; node-mongodb-native driver - * fixed; updating numbers work (#342) - * added; better error msg when try to remove an embedded doc without an _id (#307) - * added; support for 'on-the-fly' schemas (#227) - * changed; virtual id getters can now be skipped - * fixed; .index() called on subdoc schema now works as expected - * fixed; db.setProfile() now buffers until the db is open (#340) - -1.3.3 / 2011-04-27 -=================== - - * fixed; corrected query casting on nested mixed types - -1.3.2 / 2011-04-27 -=================== - - * fixed; query hints now retain key order - -1.3.1 / 2011-04-27 -=================== - - * fixed; setting a property on an embedded array no longer overwrites entire array (GH-310) - * fixed; setting nested properties works when sibling prop is named "type" - * fixed; isModified is now much finer grained when .set() is used (GH-323) - * fixed; mongoose.model() and connection.model() now return the Model (GH-308, GH-305) - * fixed; can now use $gt, $lt, $gte, $lte with String schema types (GH-317) - * fixed; .lowercase() -> .toLowerCase() in pluralize() - * fixed; updating an embedded document by index works (GH-334) - * changed; .save() now passes the instance to the callback (GH-294, GH-264) - * added; can now query system.profile and system.indexes collections - * added; db.model('system.profile') is now included as a default Schema - * added; db.setProfiling(level, ms, callback) - * added; Query#hint() support - * added; more tests - * updated node-mongodb-native to 0.9.3 - -1.3.0 / 2011-04-19 -=================== - - * changed; save() callbacks now fire only once on failed validation - * changed; Errors returned from save() callbacks now instances of ValidationError - * fixed; MongooseArray#indexOf now works properly - -1.2.0 / 2011-04-11 -=================== - - * changed; MongooseNumber now casts empty string to null - -1.1.25 / 2011-04-08 -=================== - - * fixed; post init now fires at proper time - -1.1.24 / 2011-04-03 -=================== - - * fixed; pushing an array onto an Array works on existing docs - -1.1.23 / 2011-04-01 -=================== - - * Added Model#model - -1.1.22 / 2011-03-31 -=================== - - * Fixed; $in queries on mixed types now work - -1.1.21 / 2011-03-31 -=================== - - * Fixed; setting object root to null/undefined works - -1.1.20 / 2011-03-31 -=================== - - * Fixed; setting multiple props on null field works - -1.1.19 / 2011-03-31 -=================== - - * Fixed; no longer using $set on paths to an unexisting fields - -1.1.18 / 2011-03-30 -=================== - - * Fixed; non-mixed type object setters work after initd from null - -1.1.17 / 2011-03-30 -=================== - - * Fixed; nested object property access works when root initd with null value - -1.1.16 / 2011-03-28 -=================== - - * Fixed; empty arrays are now saved - -1.1.15 / 2011-03-28 -=================== - - * Fixed; `null` and `undefined` are set atomically. - -1.1.14 / 2011-03-28 -=================== - - * Changed; more forgiving date casting, accepting '' as null. - -1.1.13 / 2011-03-26 -=================== - - * Fixed setting values as `undefined`. - -1.1.12 / 2011-03-26 -=================== - - * Fixed; nested objects now convert to JSON properly - * Fixed; setting nested objects directly now works - * Update node-mongodb-native - -1.1.11 / 2011-03-25 -=================== - - * Fixed for use of `type` as a key. - -1.1.10 / 2011-03-23 -=================== - - * Changed; Make sure to only ensure indexes while connected - -1.1.9 / 2011-03-2 -================== - - * Fixed; Mixed can now default to empty arrays - * Fixed; keys by the name 'type' are now valid - * Fixed; null values retrieved from the database are hydrated as null values. - * Fixed repeated atomic operations when saving a same document twice. - -1.1.8 / 2011-03-23 -================== - - * Fixed 'id' overriding. [bnoguchi] - -1.1.7 / 2011-03-22 -================== - - * Fixed RegExp query casting when querying against an Array of Strings [bnoguchi] - * Fixed getters/setters for nested virtualsl. [bnoguchi] - -1.1.6 / 2011-03-22 -================== - - * Only doValidate when path exists in Schema [aheckmann] - * Allow function defaults for Array types [aheckmann] - * Fix validation hang [aheckmann] - * Fix setting of isRequired of SchemaType [aheckmann] - * Fix SchemaType#required(false) filter [aheckmann] - * More backwards compatibility [aheckmann] - * More tests [aheckmann] - -1.1.5 / 2011-03-14 -================== - - * Added support for `uri, db, fn` and `uri, fn` signatures for replica sets. - * Improved/extended replica set tests. - -1.1.4 / 2011-03-09 -================== - - * Fixed; running an empty Query doesn't throw. [aheckmann] - * Changed; Promise#addBack returns promise. [aheckmann] - * Added streaming cursor support. [aheckmann] - * Changed; Query#update defaults to use$SetOnSave now. [brian] - * Added more docs. - -1.1.3 / 2011-03-04 -================== - - * Added Promise#resolve [aheckmann] - * Fixed backward compatibility with nulls [aheckmann] - * Changed; Query#{run,exec} return promises [aheckmann] - -1.1.2 / 2011-03-03 -================== - - * Restored Query#exec and added notion of default operation [brian] - * Fixed ValidatorError messages [brian] - -1.1.1 / 2011-03-01 -================== - - * Added SchemaType String `lowercase`, `uppercase`, `trim`. - * Public exports (`Model`, `Document`) and tests. - * Added ObjectId casting support for `Document`s. - -1.1.0 / 2011-02-25 -================== - - * Added support for replica sets. - -1.0.16 / 2011-02-18 -=================== - - * Added $nin as another whitelisted $conditional for SchemaArray [brian] - * Changed #with to #where [brian] - * Added ability to use $in conditional with Array types [brian] - -1.0.15 / 2011-02-18 -=================== - - * Added `id` virtual getter for documents to easily access the hexString of - the `_id`. - -1.0.14 / 2011-02-17 -=================== - - * Fix for arrays within subdocuments [brian] - -1.0.13 / 2011-02-16 -=================== - - * Fixed embedded documents saving. - -1.0.12 / 2011-02-14 -=================== - - * Minor refactorings [brian] - -1.0.11 / 2011-02-14 -=================== - - * Query refactor and $ne, $slice, $or, $size, $elemMatch, $nin, $exists support [brian] - * Named scopes sugar [brian] - -1.0.10 / 2011-02-11 -=================== - - * Updated node-mongodb-native driver [thanks John Allen] - -1.0.9 / 2011-02-09 -================== - - * Fixed single member arrays as defaults [brian] - -1.0.8 / 2011-02-09 -================== - - * Fixed for collection-level buffering of commands [gitfy] - * Fixed `Document#toJSON` [dalejefferson] - * Fixed `Connection` authentication [robrighter] - * Fixed clash of accessors in getters/setters [eirikurn] - * Improved `Model#save` promise handling - -1.0.7 / 2011-02-05 -================== - - * Fixed memory leak warnings for test suite on 0.3 - * Fixed querying documents that have an array that contain at least one - specified member. [brian] - * Fixed default value for Array types (fixes GH-210). [brian] - * Fixed example code. - -1.0.6 / 2011-02-03 -================== - - * Fixed `post` middleware - * Fixed; it's now possible to instantiate a model even when one of the paths maps - to an undefined value [brian] - -1.0.5 / 2011-02-02 -================== - - * Fixed; combo $push and $pushAll auto-converts into a $pushAll [brian] - * Fixed; combo $pull and $pullAll auto-converts to a single $pullAll [brian] - * Fixed; $pullAll now removes said members from array before save (so it acts just - like pushAll) [brian] - * Fixed; multiple $pulls and $pushes become a single $pullAll and $pushAll. - Moreover, $pull now modifies the array before save to reflect the immediate - change [brian] - * Added tests for nested shortcut getters [brian] - * Added tests that show that Schemas with nested Arrays don't apply defaults - [brian] - -1.0.4 / 2011-02-02 -================== - - * Added MongooseNumber#toString - * Added MongooseNumber unit tests - -1.0.3 / 2011-02-02 -================== - - * Make sure safe mode works with Model#save - * Changed Schema options: safe mode is now the default - * Updated node-mongodb-native to HEAD - -1.0.2 / 2011-02-02 -================== - - * Added a Model.create shortcut for creating documents. [brian] - * Fixed; we can now instantiate models with hashes that map to at least one - null value. [brian] - * Fixed Schema with more than 2 nested levels. [brian] - -1.0.1 / 2011-02-02 -================== - - * Improved `MongooseNumber`, works almost like the native except for `typeof` - not being `'number'`. diff --git a/node_modules/mongoose/README.md b/node_modules/mongoose/README.md deleted file mode 100644 index 2f65bade8afe5c89f87910545a64e50a5999a450..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/README.md +++ /dev/null @@ -1,332 +0,0 @@ -# Mongoose - -Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. - -[](http://slack.mongoosejs.io) -[](https://travis-ci.org/Automattic/mongoose) -[](http://badge.fury.io/js/mongoose) - -[](https://www.npmjs.com/package/mongoose) - -## Documentation - -[mongoosejs.com](http://mongoosejs.com/) - -[Mongoose 5.0.0](https://github.com/Automattic/mongoose/blob/master/History.md#500--2018-01-17) was released on January 17, 2018. You can find more details on [backwards breaking changes in 5.0.0 on our docs site](https://mongoosejs.com/docs/migrating_to_5.html). - -## Support - - - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose) - - [Bug Reports](https://github.com/Automattic/mongoose/issues/) - - [Mongoose Slack Channel](http://slack.mongoosejs.io/) - - [Help Forum](http://groups.google.com/group/mongoose-orm) - - [MongoDB Support](https://docs.mongodb.org/manual/support/) - -## Importing - -```javascript -// Using Node.js `require()` -const mongoose = require('mongoose'); - -// Using ES6 imports -import mongoose from 'mongoose'; -``` - -## Plugins - -Check out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community. Next, learn how to write your own plugin from the [docs](http://mongoosejs.com/docs/plugins.html) or [this blog post](http://thecodebarbarian.com/2015/03/06/guide-to-mongoose-plugins). - -## Contributors - -Pull requests are always welcome! Please base pull requests against the `master` -branch and follow the [contributing guide](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md). - -If your pull requests makes documentation changes, please do **not** -modify any `.html` files. The `.html` files are compiled code, so please make -your changes in `docs/*.jade`, `lib/*.js`, or `test/docs/*.js`. - -View all 300+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors). - -## Installation - -First install [node.js](http://nodejs.org/) and [mongodb](https://www.mongodb.org/downloads). Then: - -```sh -$ npm install mongoose -``` - -## Overview - -### Connecting to MongoDB - -First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`. - -Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`. - -```js -const mongoose = require('mongoose'); - -mongoose.connect('mongodb://localhost/my_database'); -``` - -Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`. - -**Note:** _If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed._ - -**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc. - -### Defining a Model - -Models are defined through the `Schema` interface. - -```js -const Schema = mongoose.Schema; -const ObjectId = Schema.ObjectId; - -const BlogPost = new Schema({ - author: ObjectId, - title: String, - body: String, - date: Date -}); -``` - -Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of: - -* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync) -* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default) -* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get) -* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set) -* [Indexes](http://mongoosejs.com/docs/guide.html#indexes) -* [Middleware](http://mongoosejs.com/docs/middleware.html) -* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition -* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition -* [Plugins](http://mongoosejs.com/docs/plugins.html) -* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html) - -The following example shows some of these features: - -```js -const Comment = new Schema({ - name: { type: String, default: 'hahaha' }, - age: { type: Number, min: 18, index: true }, - bio: { type: String, match: /[a-z]/ }, - date: { type: Date, default: Date.now }, - buff: Buffer -}); - -// a setter -Comment.path('name').set(function (v) { - return capitalize(v); -}); - -// middleware -Comment.pre('save', function (next) { - notify(this.get('email')); - next(); -}); -``` - -Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup. - -### Accessing a Model - -Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function - -```js -const myModel = mongoose.model('ModelName'); -``` - -Or just do it all at once - -```js -const MyModel = mongoose.model('ModelName', mySchema); -``` - -The first argument is the _singular_ name of the collection your model is for. **Mongoose automatically looks for the _plural_ version of your model name.** For example, if you use - -```js -const MyModel = mongoose.model('Ticket', mySchema); -``` - -Then Mongoose will create the model for your __tickets__ collection, not your __ticket__ collection. - -Once we have our model, we can then instantiate it, and save it: - -```js -const instance = new MyModel(); -instance.my.key = 'hello'; -instance.save(function (err) { - // -}); -``` - -Or we can find documents from the same collection - -```js -MyModel.find({}, function (err, docs) { - // docs.forEach -}); -``` - -You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html). - -**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created: - -```js -const conn = mongoose.createConnection('your connection string'); -const MyModel = conn.model('ModelName', schema); -const m = new MyModel; -m.save(); // works -``` - -vs - -```js -const conn = mongoose.createConnection('your connection string'); -const MyModel = mongoose.model('ModelName', schema); -const m = new MyModel; -m.save(); // does not work b/c the default connection object was never connected -``` - -### Embedded Documents - -In the first example snippet, we defined a key in the Schema that looks like: - -``` -comments: [Comment] -``` - -Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as: - -```js -// retrieve my model -var BlogPost = mongoose.model('BlogPost'); - -// create a blog post -var post = new BlogPost(); - -// create a comment -post.comments.push({ title: 'My comment' }); - -post.save(function (err) { - if (!err) console.log('Success!'); -}); -``` - -The same goes for removing them: - -```js -BlogPost.findById(myId, function (err, post) { - if (!err) { - post.comments[0].remove(); - post.save(function (err) { - // do something - }); - } -}); -``` - -Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap! - - -### Middleware - -See the [docs](http://mongoosejs.com/docs/middleware.html) page. - -#### Intercepting and mutating method arguments - -You can intercept method arguments via middleware. - -For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value: - -```js -schema.pre('set', function (next, path, val, typel) { - // `this` is the current Document - this.emit('set', path, val); - - // Pass control to the next pre - next(); -}); -``` - -Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`: - -```js -.pre(method, function firstPre (next, methodArg1, methodArg2) { - // Mutate methodArg1 - next("altered-" + methodArg1.toString(), methodArg2); -}); - -// pre declaration is chainable -.pre(method, function secondPre (next, methodArg1, methodArg2) { - console.log(methodArg1); - // => 'altered-originalValOfMethodArg1' - - console.log(methodArg2); - // => 'originalValOfMethodArg2' - - // Passing no arguments to `next` automatically passes along the current argument values - // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)` - // and also equivalent to, with the example method arg - // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')` - next(); -}); -``` - -#### Schema gotcha - -`type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation: - -```js -new Schema({ - broken: { type: Boolean }, - asset: { - name: String, - type: String // uh oh, it broke. asset will be interpreted as String - } -}); - -new Schema({ - works: { type: Boolean }, - asset: { - name: String, - type: { type: String } // works. asset is an object with a type property - } -}); -``` - -### Driver Access - -Mongoose is built on top of the [official MongoDB Node.js driver](https://github.com/mongodb/node-mongodb-native). Each mongoose model keeps a reference to a [native MongoDB driver collection](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html). The collection object can be accessed using `YourModel.collection`. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one -notable exception that `YourModel.collection` still buffers -commands. As such, `YourModel.collection.find()` will **not** -return a cursor. - -## API Docs - -Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](https://github.com/tj/dox) -and [acquit](https://github.com/vkarpov15/acquit). - -## License - -Copyright (c) 2010 LearnBoost <dev@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/browser.js b/node_modules/mongoose/browser.js deleted file mode 100644 index 4cf822804e8801f0b615d29cd524ec71e75e80df..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/browser.js +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Export lib/mongoose - * - */ - -'use strict'; - -module.exports = require('./lib/browser'); diff --git a/node_modules/mongoose/index.js b/node_modules/mongoose/index.js deleted file mode 100644 index a938b443d43f0f9393d3bfd5064c71356b589679..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/index.js +++ /dev/null @@ -1,9 +0,0 @@ - -/** - * Export lib/mongoose - * - */ - -'use strict'; - -module.exports = require('./lib/'); diff --git a/node_modules/mongoose/lib/aggregate.js b/node_modules/mongoose/lib/aggregate.js deleted file mode 100644 index 28bea5c4ea6f15020e49c8226b96dd364454f855..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/aggregate.js +++ /dev/null @@ -1,1099 +0,0 @@ -'use strict'; - -/*! - * Module dependencies - */ - -const AggregationCursor = require('./cursor/AggregationCursor'); -const Query = require('./query'); -const util = require('util'); -const utils = require('./utils'); -const read = Query.prototype.read; -const readConcern = Query.prototype.readConcern; - -/** - * Aggregate constructor used for building aggregation pipelines. Do not - * instantiate this class directly, use [Model.aggregate()](/docs/api.html#model_Model.aggregate) instead. - * - * ####Example: - * - * const aggregate = Model.aggregate([ - * { $project: { a: 1, b: 1 } }, - * { $skip: 5 } - * ]); - * - * Model. - * aggregate([{ $match: { age: { $gte: 21 }}}]). - * unwind('tags'). - * exec(callback); - * - * ####Note: - * - * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). - * - Mongoose does **not** cast pipeline stages. The below will **not** work unless `_id` is a string in the database - * - * ```javascript - * new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]); - * // Do this instead to cast to an ObjectId - * new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]); - * ``` - * - * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ - * @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate - * @param {Array} [pipeline] aggregation pipeline as an array of objects - * @api public - */ - -function Aggregate(pipeline) { - this._pipeline = []; - this._model = undefined; - this.options = {}; - - if (arguments.length === 1 && util.isArray(pipeline)) { - this.append.apply(this, pipeline); - } -} - -/** - * Contains options passed down to the [aggregate command](https://docs.mongodb.com/manual/reference/command/aggregate/). - * Supported options are: - * - * - `readPreference` - * - [`cursor`](./api.html#aggregate_Aggregate-cursor) - * - [`explain`](./api.html#aggregate_Aggregate-explain) - * - [`allowDiskUse`](./api.html#aggregate_Aggregate-allowDiskUse) - * - `maxTimeMS` - * - `bypassDocumentValidation` - * - `raw` - * - `promoteLongs` - * - `promoteValues` - * - `promoteBuffers` - * - [`collation`](./api.html#aggregate_Aggregate-collation) - * - `comment` - * - [`session`](./api.html#aggregate_Aggregate-session) - * - * @property options - * @memberOf Aggregate - * @api public - */ - -Aggregate.prototype.options; - -/** - * Binds this aggregate to a model. - * - * @param {Model} model the model to which the aggregate is to be bound - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.model = function(model) { - this._model = model; - if (model.schema != null) { - if (this.options.readPreference == null && - model.schema.options.read != null) { - this.options.readPreference = model.schema.options.read; - } - if (this.options.collation == null && - model.schema.options.collation != null) { - this.options.collation = model.schema.options.collation; - } - } - return this; -}; - -/** - * Appends new operators to this aggregate pipeline - * - * ####Examples: - * - * aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); - * - * // or pass an array - * var pipeline = [{ $match: { daw: 'Logic Audio X' }} ]; - * aggregate.append(pipeline); - * - * @param {Object} ops operator(s) to append - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.append = function() { - const args = (arguments.length === 1 && util.isArray(arguments[0])) - ? arguments[0] - : utils.args(arguments); - - if (!args.every(isOperator)) { - throw new Error('Arguments must be aggregate pipeline operators'); - } - - this._pipeline = this._pipeline.concat(args); - - return this; -}; - -/** - * Appends a new $addFields operator to this aggregate pipeline. - * Requires MongoDB v3.4+ to work - * - * ####Examples: - * - * // adding new fields based on existing fields - * aggregate.addFields({ - * newField: '$b.nested' - * , plusTen: { $add: ['$val', 10]} - * , sub: { - * name: '$a' - * } - * }) - * - * // etc - * aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } }); - * - * @param {Object} arg field specification - * @see $addFields https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/ - * @return {Aggregate} - * @api public - */ -Aggregate.prototype.addFields = function(arg) { - const fields = {}; - if (typeof arg === 'object' && !util.isArray(arg)) { - Object.keys(arg).forEach(function(field) { - fields[field] = arg[field]; - }); - } else { - throw new Error('Invalid addFields() argument. Must be an object'); - } - return this.append({$addFields: fields}); -}; - -/** - * Appends a new $project operator to this aggregate pipeline. - * - * Mongoose query [selection syntax](#query_Query-select) is also supported. - * - * ####Examples: - * - * // include a, include b, exclude _id - * aggregate.project("a b -_id"); - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * aggregate.project({a: 1, b: 1, _id: 0}); - * - * // reshaping documents - * aggregate.project({ - * newField: '$b.nested' - * , plusTen: { $add: ['$val', 10]} - * , sub: { - * name: '$a' - * } - * }) - * - * // etc - * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); - * - * @param {Object|String} arg field specification - * @see projection http://docs.mongodb.org/manual/reference/aggregation/project/ - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.project = function(arg) { - const fields = {}; - - if (typeof arg === 'object' && !util.isArray(arg)) { - Object.keys(arg).forEach(function(field) { - fields[field] = arg[field]; - }); - } else if (arguments.length === 1 && typeof arg === 'string') { - arg.split(/\s+/).forEach(function(field) { - if (!field) { - return; - } - const include = field[0] === '-' ? 0 : 1; - if (include === 0) { - field = field.substring(1); - } - fields[field] = include; - }); - } else { - throw new Error('Invalid project() argument. Must be string or object'); - } - - return this.append({$project: fields}); -}; - -/** - * Appends a new custom $group operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.group({ _id: "$department" }); - * - * @see $group http://docs.mongodb.org/manual/reference/aggregation/group/ - * @method group - * @memberOf Aggregate - * @instance - * @param {Object} arg $group operator contents - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new custom $match operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.match({ department: { $in: [ "sales", "engineering" ] } }); - * - * @see $match http://docs.mongodb.org/manual/reference/aggregation/match/ - * @method match - * @memberOf Aggregate - * @instance - * @param {Object} arg $match operator contents - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new $skip operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.skip(10); - * - * @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/ - * @method skip - * @memberOf Aggregate - * @instance - * @param {Number} num number of records to skip before next stage - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new $limit operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.limit(10); - * - * @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/ - * @method limit - * @memberOf Aggregate - * @instance - * @param {Number} num maximum number of records to pass to the next stage - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new $geoNear operator to this aggregate pipeline. - * - * ####NOTE: - * - * **MUST** be used as the first operator in the pipeline. - * - * ####Examples: - * - * aggregate.near({ - * near: [40.724, -73.997], - * distanceField: "dist.calculated", // required - * maxDistance: 0.008, - * query: { type: "public" }, - * includeLocs: "dist.location", - * uniqueDocs: true, - * num: 5 - * }); - * - * @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/ - * @method near - * @memberOf Aggregate - * @instance - * @param {Object} arg - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.near = function(arg) { - const op = {}; - op.$geoNear = arg; - return this.append(op); -}; - -/*! - * define methods - */ - -'group match skip limit out'.split(' ').forEach(function($operator) { - Aggregate.prototype[$operator] = function(arg) { - const op = {}; - op['$' + $operator] = arg; - return this.append(op); - }; -}); - -/** - * Appends new custom $unwind operator(s) to this aggregate pipeline. - * - * Note that the `$unwind` operator requires the path name to start with '$'. - * Mongoose will prepend '$' if the specified field doesn't start '$'. - * - * ####Examples: - * - * aggregate.unwind("tags"); - * aggregate.unwind("a", "b", "c"); - * - * @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/ - * @param {String} fields the field(s) to unwind - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.unwind = function() { - const args = utils.args(arguments); - - const res = []; - for (let i = 0; i < args.length; ++i) { - const arg = args[i]; - if (arg && typeof arg === 'object') { - res.push({ $unwind: arg }); - } else if (typeof arg === 'string') { - res.push({ - $unwind: (arg && arg.charAt(0) === '$') ? arg : '$' + arg - }); - } else { - throw new Error('Invalid arg "' + arg + '" to unwind(), ' + - 'must be string or object'); - } - } - - return this.append.apply(this, res); -}; - -/** - * Appends a new $replaceRoot operator to this aggregate pipeline. - * - * Note that the `$replaceRoot` operator requires field strings to start with '$'. - * If you are passing in a string Mongoose will prepend '$' if the specified field doesn't start '$'. - * If you are passing in an object the strings in your expression will not be altered. - * - * ####Examples: - * - * aggregate.replaceRoot("user"); - * - * aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } }); - * - * @see $replaceRoot https://docs.mongodb.org/manual/reference/operator/aggregation/replaceRoot - * @param {String|Object} the field or document which will become the new root document - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.replaceRoot = function(newRoot) { - let ret; - - if (typeof newRoot === 'string') { - ret = newRoot.startsWith('$') ? newRoot : '$' + newRoot; - } else { - ret = newRoot; - } - - return this.append({ - $replaceRoot: { - newRoot: ret - } - }); -}; - -/** - * Appends a new $count operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.count("userCount"); - * - * @see $count https://docs.mongodb.org/manual/reference/operator/aggregation/count - * @param {String} the name of the count field - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.count = function(countName) { - return this.append({ $count: countName }); -}; - -/** - * Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name - * or a pipeline object. - * - * Note that the `$sortByCount` operator requires the new root to start with '$'. - * Mongoose will prepend '$' if the specified field name doesn't start with '$'. - * - * ####Examples: - * - * aggregate.sortByCount('users'); - * aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] }) - * - * @see $sortByCount https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/ - * @param {Object|String} arg - * @return {Aggregate} this - * @api public - */ - -Aggregate.prototype.sortByCount = function(arg) { - if (arg && typeof arg === 'object') { - return this.append({ $sortByCount: arg }); - } else if (typeof arg === 'string') { - return this.append({ - $sortByCount: (arg && arg.charAt(0) === '$') ? arg : '$' + arg - }); - } else { - throw new TypeError('Invalid arg "' + arg + '" to sortByCount(), ' + - 'must be string or object'); - } -}; - -/** - * Appends new custom $lookup operator(s) to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' }); - * - * @see $lookup https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/#pipe._S_lookup - * @param {Object} options to $lookup as described in the above link - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.lookup = function(options) { - return this.append({$lookup: options}); -}; - -/** - * Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection. - * - * Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if `{ allowDiskUse: true }` is specified. - * - * #### Examples: - * // Suppose we have a collection of courses, where a document might look like `{ _id: 0, name: 'Calculus', prerequisite: 'Trigonometry'}` and `{ _id: 0, name: 'Trigonometry', prerequisite: 'Algebra' }` - * aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites - * - * @see $graphLookup https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/#pipe._S_graphLookup - * @param {Object} options to $graphLookup as described in the above link - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.graphLookup = function(options) { - const cloneOptions = {}; - if (options) { - if (!utils.isObject(options)) { - throw new TypeError('Invalid graphLookup() argument. Must be an object.'); - } - - utils.mergeClone(cloneOptions, options); - const startWith = cloneOptions.startWith; - - if (startWith && typeof startWith === 'string') { - cloneOptions.startWith = cloneOptions.startWith.charAt(0) === '$' ? - cloneOptions.startWith : - '$' + cloneOptions.startWith; - } - - } - return this.append({ $graphLookup: cloneOptions }); -}; - -/** - * Appends new custom $sample operator(s) to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.sample(3); // Add a pipeline that picks 3 random documents - * - * @see $sample https://docs.mongodb.org/manual/reference/operator/aggregation/sample/#pipe._S_sample - * @param {Number} size number of random documents to pick - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.sample = function(size) { - return this.append({$sample: {size: size}}); -}; - -/** - * Appends a new $sort operator to this aggregate pipeline. - * - * 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. - * - * ####Examples: - * - * // these are equivalent - * aggregate.sort({ field: 'asc', test: -1 }); - * aggregate.sort('field -test'); - * - * @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/ - * @param {Object|String} arg - * @return {Aggregate} this - * @api public - */ - -Aggregate.prototype.sort = function(arg) { - // TODO refactor to reuse the query builder logic - - const sort = {}; - - if (arg.constructor.name === 'Object') { - const desc = ['desc', 'descending', -1]; - Object.keys(arg).forEach(function(field) { - // If sorting by text score, skip coercing into 1/-1 - if (arg[field] instanceof Object && arg[field].$meta) { - sort[field] = arg[field]; - return; - } - sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1; - }); - } else if (arguments.length === 1 && typeof arg === 'string') { - arg.split(/\s+/).forEach(function(field) { - if (!field) { - return; - } - const ascend = field[0] === '-' ? -1 : 1; - if (ascend === -1) { - field = field.substring(1); - } - sort[field] = ascend; - }); - } else { - throw new TypeError('Invalid sort() argument. Must be a string or object.'); - } - - return this.append({$sort: sort}); -}; - -/** - * Sets the readPreference option for the aggregation query. - * - * ####Example: - * - * Model.aggregate(..).read('primaryPreferred').exec(callback) - * - * @param {String} pref one of the listed preference options or their aliases - * @param {Array} [tags] optional tags for this query - * @return {Aggregate} this - * @api public - * @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 - */ - -Aggregate.prototype.read = function(pref, tags) { - if (!this.options) { - this.options = {}; - } - read.call(this, pref, tags); - return this; -}; - -/** - * Sets the readConcern level for the aggregation query. - * - * ####Example: - * - * Model.aggregate(..).readConcern('majority').exec(callback) - * - * @param {String} level one of the listed read concern level or their aliases - * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ - * @return {Aggregate} this - * @api public - */ - -Aggregate.prototype.readConcern = function(level) { - if (!this.options) { - this.options = {}; - } - readConcern.call(this, level); - return this; -}; - -/** - * Appends a new $redact operator to this aggregate pipeline. - * - * If 3 arguments are supplied, Mongoose will wrap them with if-then-else of $cond operator respectively - * If `thenExpr` or `elseExpr` is string, make sure it starts with $$, like `$$DESCEND`, `$$PRUNE` or `$$KEEP`. - * - * ####Example: - * - * Model.aggregate(...) - * .redact({ - * $cond: { - * if: { $eq: [ '$level', 5 ] }, - * then: '$$PRUNE', - * else: '$$DESCEND' - * } - * }) - * .exec(); - * - * // $redact often comes with $cond operator, you can also use the following syntax provided by mongoose - * Model.aggregate(...) - * .redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND') - * .exec(); - * - * @param {Object} expression redact options or conditional expression - * @param {String|Object} [thenExpr] true case for the condition - * @param {String|Object} [elseExpr] false case for the condition - * @return {Aggregate} this - * @see $redact https://docs.mongodb.com/manual/reference/operator/aggregation/redact/ - * @api public - */ - -Aggregate.prototype.redact = function(expression, thenExpr, elseExpr) { - if (arguments.length === 3) { - if ((typeof thenExpr === 'string' && !thenExpr.startsWith('$$')) || - (typeof elseExpr === 'string' && !elseExpr.startsWith('$$'))) { - throw new Error('If thenExpr or elseExpr is string, it must start with $$. e.g. $$DESCEND, $$PRUNE, $$KEEP'); - } - - expression = { - $cond: { - if: expression, - then: thenExpr, - else: elseExpr - } - }; - } else if (arguments.length !== 1) { - throw new TypeError('Invalid arguments'); - } - - return this.append({$redact: expression}); -}; - -/** - * Execute the aggregation with explain - * - * ####Example: - * - * Model.aggregate(..).explain(callback) - * - * @param {Function} callback - * @return {Promise} - */ - -Aggregate.prototype.explain = function(callback) { - return utils.promiseOrCallback(callback, cb => { - if (!this._pipeline.length) { - const err = new Error('Aggregate has empty pipeline'); - return cb(err); - } - - prepareDiscriminatorPipeline(this); - - this._model.collection. - aggregate(this._pipeline, this.options || {}). - explain(function(error, result) { - if (error) { - return cb(error); - } - cb(null, result); - }); - }, this._model.events); -}; - -/** - * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) - * - * ####Example: - * - * await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true); - * - * @param {Boolean} value Should tell server it can use hard drive to store data during aggregation. - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - */ - -Aggregate.prototype.allowDiskUse = function(value) { - this.options.allowDiskUse = value; - return this; -}; - -/** - * Sets the hint option for the aggregation query (ignored for < 3.6.0) - * - * ####Example: - * - * Model.aggregate(..).hint({ qty: 1, category: 1 } }).exec(callback) - * - * @param {Object|String} value a hint object or the index name - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - */ - -Aggregate.prototype.hint = function(value) { - this.options.hint = value; - return this; -}; - -/** - * Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html). - * - * ####Example: - * - * const session = await Model.startSession(); - * await Model.aggregate(..).session(session); - * - * @param {ClientSession} session - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - */ - -Aggregate.prototype.session = function(session) { - if (session == null) { - delete this.options.session; - } else { - this.options.session = session; - } - return this; -}; - -/** - * Lets you set arbitrary options, for middleware or plugins. - * - * ####Example: - * - * var agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option - * agg.options; // `{ allowDiskUse: true }` - * - * @param {Object} options keys to merge into current options - * @param [options.maxTimeMS] number limits the time this aggregation will run, see [MongoDB docs on `maxTimeMS`](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) - * @param [options.allowDiskUse] boolean if true, the MongoDB server will use the hard drive to store data during this aggregation - * @param [options.collation] object see [`Aggregate.prototype.collation()`](./docs/api.html#aggregate_Aggregate-collation) - * @param [options.session] ClientSession see [`Aggregate.prototype.session()`](./docs/api.html#aggregate_Aggregate-session) - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - * @return {Aggregate} this - * @api public - */ - -Aggregate.prototype.option = function(value) { - for (const key in value) { - this.options[key] = value[key]; - } - return this; -}; - -/** - * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). - * Note the different syntax below: .exec() returns a cursor object, and no callback - * is necessary. - * - * ####Example: - * - * var cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec(); - * cursor.each(function(error, doc) { - * // use doc - * }); - * - * @param {Object} options - * @param {Number} options.batchSize set the cursor batch size - * @param {Boolean} [options.useMongooseAggCursor] use experimental mongoose-specific aggregation cursor (for `eachAsync()` and other query cursor semantics) - * @return {Aggregate} this - * @api public - * @see mongodb http://mongodb.github.io/node-mongodb-native/2.0/api/AggregationCursor.html - */ - -Aggregate.prototype.cursor = function(options) { - if (!this.options) { - this.options = {}; - } - this.options.cursor = options || {}; - return this; -}; - -/** - * Sets an option on this aggregation. This function will be deprecated in a - * future release. Use the [`cursor()`](./api.html#aggregate_Aggregate-cursor), - * [`collation()`](./api.html#aggregate_Aggregate-collation), etc. helpers to - * set individual options, or access `agg.options` directly. - * - * Note that MongoDB aggregations [do **not** support the `noCursorTimeout` flag](https://jira.mongodb.org/browse/SERVER-6036), - * if you try setting that flag with this function you will get a "unrecognized field 'noCursorTimeout'" error. - * - * @param {String} flag - * @param {Boolean} value - * @return {Aggregate} this - * @api public - * @deprecated Use [`.option()`](api.html#aggregate_Aggregate-option) instead. Note that MongoDB aggregations do **not** support a `noCursorTimeout` option. - */ - -Aggregate.prototype.addCursorFlag = util.deprecate(function(flag, value) { - if (!this.options) { - this.options = {}; - } - this.options[flag] = value; - return this; -}, 'Mongoose: `Aggregate#addCursorFlag()` is deprecated, use `option()` instead'); - -/** - * Adds a collation - * - * ####Example: - * - * Model.aggregate(..).collation({ locale: 'en_US', strength: 1 }).exec(); - * - * @param {Object} collation options - * @return {Aggregate} this - * @api public - * @see mongodb http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#aggregate - */ - -Aggregate.prototype.collation = function(collation) { - if (!this.options) { - this.options = {}; - } - this.options.collation = collation; - return this; -}; - -/** - * Combines multiple aggregation pipelines. - * - * ####Example: - * - * Model.aggregate(...) - * .facet({ - * books: [{ groupBy: '$author' }], - * price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }] - * }) - * .exec(); - * - * // Output: { books: [...], price: [{...}, {...}] } - * - * @param {Object} facet options - * @return {Aggregate} this - * @see $facet https://docs.mongodb.com/v3.4/reference/operator/aggregation/facet/ - * @api public - */ - -Aggregate.prototype.facet = function(options) { - return this.append({$facet: options}); -}; - -/** - * Returns the current pipeline - * - * ####Example: - * - * MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }] - * - * @return {Array} - * @api public - */ - - -Aggregate.prototype.pipeline = function() { - return this._pipeline; -}; - -/** - * Executes the aggregate pipeline on the currently bound Model. - * - * ####Example: - * - * aggregate.exec(callback); - * - * // Because a promise is returned, the `callback` is optional. - * var promise = aggregate.exec(); - * promise.then(..); - * - * @see Promise #promise_Promise - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Aggregate.prototype.exec = function(callback) { - if (!this._model) { - throw new Error('Aggregate not bound to any Model'); - } - const model = this._model; - const options = utils.clone(this.options || {}); - const pipeline = this._pipeline; - const collection = this._model.collection; - - if (options && options.cursor) { - return new AggregationCursor(this); - } - - return utils.promiseOrCallback(callback, cb => { - if (!pipeline.length) { - const err = new Error('Aggregate has empty pipeline'); - return cb(err); - } - - prepareDiscriminatorPipeline(this); - - model.hooks.execPre('aggregate', this, error => { - if (error) { - const _opts = { error: error }; - return model.hooks.execPost('aggregate', this, [null], _opts, error => { - cb(error); - }); - } - - collection.aggregate(pipeline, options, (error, cursor) => { - if (error) { - const _opts = { error: error }; - return model.hooks.execPost('aggregate', this, [null], _opts, error => { - if (error) { - return cb(error); - } - return cb(null); - }); - } - cursor.toArray((error, result) => { - const _opts = { error: error }; - model.hooks.execPost('aggregate', this, [result], _opts, (error, result) => { - if (error) { - return cb(error); - } - - cb(null, result); - }); - }); - }); - }); - }, model.events); -}; - -/** - * Provides promise for aggregate. - * - * ####Example: - * - * Model.aggregate(..).then(successCallback, errorCallback); - * - * @see Promise #promise_Promise - * @param {Function} [resolve] successCallback - * @param {Function} [reject] errorCallback - * @return {Promise} - */ -Aggregate.prototype.then = function(resolve, reject) { - return this.exec().then(resolve, reject); -}; - -/** - * Executes the query returning a `Promise` which will be - * resolved with either the doc(s) or rejected with the error. - * Like [`.then()`](#query_Query-then), but only takes a rejection handler. - * - * @param {Function} [reject] - * @return {Promise} - * @api public - */ - -Aggregate.prototype.catch = function(reject) { - return this.exec().then(null, reject); -}; - -/** - * Returns an asyncIterator for use with [`for/await/of` loops](http://bit.ly/async-iterators) - * This function *only* works for `find()` queries. - * You do not need to call this function explicitly, the JavaScript runtime - * will call it for you. - * - * ####Example - * - * for await (const doc of Model.find().sort({ name: 1 })) { - * console.log(doc.name); - * } - * - * Node.js 10.x supports async iterators natively without any flags. You can - * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). - * - * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If - * `Symbol.asyncIterator` is undefined, that means your Node.js version does not - * support async iterators. - * - * @method Symbol.asyncIterator - * @memberOf Aggregate - * @instance - * @api public - */ - -if (Symbol.asyncIterator != null) { - Aggregate.prototype[Symbol.asyncIterator] = function() { - return this.cursor({ useMongooseAggCursor: true }). - exec(). - transformNull(). - map(doc => { - return doc == null ? { done: true } : { value: doc, done: false }; - }); - }; -} - -/*! - * Helpers - */ - -/** - * Checks whether an object is likely a pipeline operator - * - * @param {Object} obj object to check - * @return {Boolean} - * @api private - */ - -function isOperator(obj) { - if (typeof obj !== 'object') { - return false; - } - - const k = Object.keys(obj); - - return k.length === 1 && k.some(key => { return key[0] === '$'; }); -} - -/*! - * Adds the appropriate `$match` pipeline step to the top of an aggregate's - * pipeline, should it's model is a non-root discriminator type. This is - * analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`. - * - * @param {Aggregate} aggregate Aggregate to prepare - */ - -Aggregate._prepareDiscriminatorPipeline = prepareDiscriminatorPipeline; - -function prepareDiscriminatorPipeline(aggregate) { - const schema = aggregate._model.schema; - const discriminatorMapping = schema && schema.discriminatorMapping; - - if (discriminatorMapping && !discriminatorMapping.isRoot) { - const originalPipeline = aggregate._pipeline; - const discriminatorKey = discriminatorMapping.key; - const discriminatorValue = discriminatorMapping.value; - - // If the first pipeline stage is a match and it doesn't specify a `__t` - // key, add the discriminator key to it. This allows for potential - // aggregation query optimizations not to be disturbed by this feature. - if (originalPipeline[0] && originalPipeline[0].$match && !originalPipeline[0].$match[discriminatorKey]) { - originalPipeline[0].$match[discriminatorKey] = discriminatorValue; - // `originalPipeline` is a ref, so there's no need for - // aggregate._pipeline = originalPipeline - } else if (originalPipeline[0] && originalPipeline[0].$geoNear) { - originalPipeline[0].$geoNear.query = - originalPipeline[0].$geoNear.query || {}; - originalPipeline[0].$geoNear.query[discriminatorKey] = discriminatorValue; - } else { - const match = {}; - match[discriminatorKey] = discriminatorValue; - aggregate._pipeline.unshift({ $match: match }); - } - } -} - -/*! - * Exports - */ - -module.exports = Aggregate; diff --git a/node_modules/mongoose/lib/browser.js b/node_modules/mongoose/lib/browser.js deleted file mode 100644 index 8b9b4b7bd2f19e973b74981bceff99d9ac54c99c..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/browser.js +++ /dev/null @@ -1,133 +0,0 @@ -/* eslint-env browser */ - -'use strict'; - -require('./driver').set(require('./drivers/browser')); - -const DocumentProvider = require('./document_provider.js'); -const PromiseProvider = require('./promise_provider'); - -DocumentProvider.setBrowser(true); - -/** - * The Mongoose [Promise](#promise_Promise) constructor. - * - * @method Promise - * @api public - */ - -Object.defineProperty(exports, 'Promise', { - get: function() { - return PromiseProvider.get(); - }, - set: function(lib) { - PromiseProvider.set(lib); - } -}); - -/** - * Storage layer for mongoose promises - * - * @method PromiseProvider - * @api public - */ - -exports.PromiseProvider = PromiseProvider; - -/** - * The [MongooseError](#error_MongooseError) constructor. - * - * @method Error - * @api public - */ - -exports.Error = require('./error'); - -/** - * The Mongoose [Schema](#schema_Schema) constructor - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var Schema = mongoose.Schema; - * var CatSchema = new Schema(..); - * - * @method Schema - * @api public - */ - -exports.Schema = require('./schema'); - -/** - * The various Mongoose Types. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var array = mongoose.Types.Array; - * - * ####Types: - * - * - [ObjectId](#types-objectid-js) - * - [Buffer](#types-buffer-js) - * - [SubDocument](#types-embedded-js) - * - [Array](#types-array-js) - * - [DocumentArray](#types-documentarray-js) - * - * Using this exposed access to the `ObjectId` type, we can construct ids on demand. - * - * var ObjectId = mongoose.Types.ObjectId; - * var id1 = new ObjectId; - * - * @property Types - * @api public - */ -exports.Types = require('./types'); - -/** - * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor - * - * @method VirtualType - * @api public - */ -exports.VirtualType = require('./virtualtype'); - -/** - * The various Mongoose SchemaTypes. - * - * ####Note: - * - * _Alias of mongoose.Schema.Types for backwards compatibility._ - * - * @property SchemaTypes - * @see Schema.SchemaTypes #schema_Schema.Types - * @api public - */ - -exports.SchemaType = require('./schematype.js'); - -/** - * Internal utils - * - * @property utils - * @api private - */ - -exports.utils = require('./utils.js'); - -/** - * The Mongoose browser [Document](#document-js) constructor. - * - * @method Document - * @api public - */ -exports.Document = DocumentProvider(); - -/*! - * Module exports. - */ - -if (typeof window !== 'undefined') { - window.mongoose = module.exports; - window.Buffer = Buffer; -} diff --git a/node_modules/mongoose/lib/browserDocument.js b/node_modules/mongoose/lib/browserDocument.js deleted file mode 100644 index b1c803d7243b9d265d130d3e703761163b733f35..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/browserDocument.js +++ /dev/null @@ -1,102 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const NodeJSDocument = require('./document'); -const EventEmitter = require('events').EventEmitter; -const MongooseError = require('./error'); -const Schema = require('./schema'); -const ObjectId = require('./types/objectid'); -const ValidationError = MongooseError.ValidationError; -const applyHooks = require('./helpers/model/applyHooks'); -const utils = require('./utils'); - -/** - * Document constructor. - * - * @param {Object} obj the values to set - * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data - * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose. - * @event `save`: Emitted when the document is successfully saved - * @api private - */ - -function Document(obj, schema, fields, skipId, skipInit) { - if (!(this instanceof Document)) { - return new Document(obj, schema, fields, skipId, skipInit); - } - - if (utils.isObject(schema) && !schema.instanceOfSchema) { - schema = new Schema(schema); - } - - // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id - schema = this.schema || schema; - - // Generate ObjectId if it is missing, but it requires a scheme - if (!this.schema && schema.options._id) { - obj = obj || {}; - - if (obj._id === undefined) { - obj._id = new ObjectId(); - } - } - - if (!schema) { - throw new MongooseError.MissingSchemaError(); - } - - this.$__setSchema(schema); - - NodeJSDocument.call(this, obj, fields, skipId, skipInit); - - applyHooks(this, schema, { decorateDoc: true }); - - // apply methods - for (const m in schema.methods) { - this[m] = schema.methods[m]; - } - // apply statics - for (const s in schema.statics) { - this[s] = schema.statics[s]; - } -} - -/*! - * Inherit from the NodeJS document - */ - -Document.prototype = Object.create(NodeJSDocument.prototype); -Document.prototype.constructor = Document; - -/*! - * ignore - */ - -Document.events = new EventEmitter(); - -/*! - * Browser doc exposes the event emitter API - */ - -Document.$emitter = new EventEmitter(); - -utils.each( - ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', - 'removeAllListeners', 'addListener'], - function(emitterFn) { - Document[emitterFn] = function() { - return Document.$emitter[emitterFn].apply(Document.$emitter, arguments); - }; - }); - -/*! - * Module exports. - */ - -Document.ValidationError = ValidationError; -module.exports = exports = Document; diff --git a/node_modules/mongoose/lib/cast.js b/node_modules/mongoose/lib/cast.js deleted file mode 100644 index 987912e764c1f70ef05ae66226280eccf876c4e4..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/cast.js +++ /dev/null @@ -1,340 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const StrictModeError = require('./error/strict'); -const Types = require('./schema/index'); -const castTextSearch = require('./schema/operators/text'); -const get = require('./helpers/get'); -const util = require('util'); -const utils = require('./utils'); - -const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon']; - -/** - * Handles internal casting for query filters. - * - * @param {Schema} schema - * @param {Object} obj Object to cast - * @param {Object} options the query options - * @param {Query} context passed to setters - * @api private - */ -module.exports = function cast(schema, obj, options, context) { - if (Array.isArray(obj)) { - throw new Error('Query filter must be an object, got an array ', util.inspect(obj)); - } - - const paths = Object.keys(obj); - let i = paths.length; - let _keys; - let any$conditionals; - let schematype; - let nested; - let path; - let type; - let val; - - options = options || {}; - - while (i--) { - path = paths[i]; - val = obj[path]; - - if (path === '$or' || path === '$nor' || path === '$and') { - let k = val.length; - - while (k--) { - val[k] = cast(schema, val[k], options, context); - } - } else if (path === '$where') { - type = typeof val; - - if (type !== 'string' && type !== 'function') { - throw new Error('Must have a string or function for $where'); - } - - if (type === 'function') { - obj[path] = val.toString(); - } - - continue; - } else if (path === '$elemMatch') { - val = cast(schema, val, options, context); - } else if (path === '$text') { - val = castTextSearch(val, path); - } else { - if (!schema) { - // no casting for Mixed types - continue; - } - - schematype = schema.path(path); - - // Check for embedded discriminator paths - if (!schematype) { - const split = path.split('.'); - let j = split.length; - while (j--) { - const pathFirstHalf = split.slice(0, j).join('.'); - const pathLastHalf = split.slice(j).join('.'); - const _schematype = schema.path(pathFirstHalf); - const discriminatorKey = get(_schematype, 'schema.options.discriminatorKey'); - - // gh-6027: if we haven't found the schematype but this path is - // underneath an embedded discriminator and the embedded discriminator - // key is in the query, use the embedded discriminator schema - if (_schematype != null && - get(_schematype, 'schema.discriminators') != null && - discriminatorKey != null && - pathLastHalf !== discriminatorKey) { - const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey); - if (discriminatorVal != null) { - schematype = _schematype.schema.discriminators[discriminatorVal]. - path(pathLastHalf); - } - } - } - } - - if (!schematype) { - // Handle potential embedded array queries - const split = path.split('.'); - let j = split.length; - let pathFirstHalf; - let pathLastHalf; - let remainingConds; - - // Find the part of the var path that is a path of the Schema - while (j--) { - pathFirstHalf = split.slice(0, j).join('.'); - schematype = schema.path(pathFirstHalf); - if (schematype) { - break; - } - } - - // If a substring of the input path resolves to an actual real path... - if (schematype) { - // Apply the casting; similar code for $elemMatch in schema/array.js - if (schematype.caster && schematype.caster.schema) { - remainingConds = {}; - pathLastHalf = split.slice(j).join('.'); - remainingConds[pathLastHalf] = val; - obj[path] = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf]; - } else { - obj[path] = val; - } - continue; - } - - if (utils.isObject(val)) { - // handle geo schemas that use object notation - // { loc: { long: Number, lat: Number } - - let geo = ''; - if (val.$near) { - geo = '$near'; - } else if (val.$nearSphere) { - geo = '$nearSphere'; - } else if (val.$within) { - geo = '$within'; - } else if (val.$geoIntersects) { - geo = '$geoIntersects'; - } else if (val.$geoWithin) { - geo = '$geoWithin'; - } - - if (geo) { - const numbertype = new Types.Number('__QueryCasting__'); - let value = val[geo]; - - if (val.$maxDistance != null) { - val.$maxDistance = numbertype.castForQueryWrapper({ - val: val.$maxDistance, - context: context - }); - } - if (val.$minDistance != null) { - val.$minDistance = numbertype.castForQueryWrapper({ - val: val.$minDistance, - context: context - }); - } - - if (geo === '$within') { - const withinType = value.$center - || value.$centerSphere - || value.$box - || value.$polygon; - - if (!withinType) { - throw new Error('Bad $within parameter: ' + JSON.stringify(val)); - } - - value = withinType; - } else if (geo === '$near' && - typeof value.type === 'string' && Array.isArray(value.coordinates)) { - // geojson; cast the coordinates - value = value.coordinates; - } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') && - value.$geometry && typeof value.$geometry.type === 'string' && - Array.isArray(value.$geometry.coordinates)) { - if (value.$maxDistance != null) { - value.$maxDistance = numbertype.castForQueryWrapper({ - val: value.$maxDistance, - context: context - }); - } - if (value.$minDistance != null) { - value.$minDistance = numbertype.castForQueryWrapper({ - val: value.$minDistance, - context: context - }); - } - if (utils.isMongooseObject(value.$geometry)) { - value.$geometry = value.$geometry.toObject({ - transform: false, - virtuals: false - }); - } - value = value.$geometry.coordinates; - } else if (geo === '$geoWithin') { - if (value.$geometry) { - if (utils.isMongooseObject(value.$geometry)) { - value.$geometry = value.$geometry.toObject({ virtuals: false }); - } - const geoWithinType = value.$geometry.type; - if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) { - throw new Error('Invalid geoJSON type for $geoWithin "' + - geoWithinType + '", must be "Polygon" or "MultiPolygon"'); - } - value = value.$geometry.coordinates; - } else { - value = value.$box || value.$polygon || value.$center || - value.$centerSphere; - if (utils.isMongooseObject(value)) { - value = value.toObject({ virtuals: false }); - } - } - } - - _cast(value, numbertype, context); - continue; - } - } - - if (schema.nested[path]) { - continue; - } - if (options.upsert && options.strict) { - if (options.strict === 'throw') { - throw new StrictModeError(path); - } - throw new StrictModeError(path, 'Path "' + path + '" is not in ' + - 'schema, strict mode is `true`, and upsert is `true`.'); - } else if (options.strictQuery === 'throw') { - throw new StrictModeError(path, 'Path "' + path + '" is not in ' + - 'schema and strictQuery is true.'); - } else if (options.strictQuery) { - delete obj[path]; - } - } else if (val == null) { - continue; - } else if (val.constructor.name === 'Object') { - any$conditionals = Object.keys(val).some(function(k) { - return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; - }); - - if (!any$conditionals) { - obj[path] = schematype.castForQueryWrapper({ - val: val, - context: context - }); - } else { - const ks = Object.keys(val); - let $cond; - - let k = ks.length; - - while (k--) { - $cond = ks[k]; - nested = val[$cond]; - - if ($cond === '$not') { - if (nested && schematype && !schematype.caster) { - _keys = Object.keys(nested); - if (_keys.length && _keys[0].charAt(0) === '$') { - for (const key in nested) { - nested[key] = schematype.castForQueryWrapper({ - $conditional: key, - val: nested[key], - context: context - }); - } - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: context - }); - } - continue; - } - cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context); - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: context - }); - } - } - } - } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) { - const casted = []; - for (let valIndex = 0; valIndex < val.length; valIndex++) { - casted.push(schematype.castForQueryWrapper({ - val: val[valIndex], - context: context - })); - } - - obj[path] = { $in: casted }; - } else { - obj[path] = schematype.castForQueryWrapper({ - val: val, - context: context - }); - } - } - } - - return obj; -}; - -function _cast(val, numbertype, context) { - if (Array.isArray(val)) { - val.forEach(function(item, i) { - if (Array.isArray(item) || utils.isObject(item)) { - return _cast(item, numbertype, context); - } - val[i] = numbertype.castForQueryWrapper({ val: item, context: context }); - }); - } else { - const nearKeys = Object.keys(val); - let nearLen = nearKeys.length; - while (nearLen--) { - const nkey = nearKeys[nearLen]; - const item = val[nkey]; - if (Array.isArray(item) || utils.isObject(item)) { - _cast(item, numbertype, context); - val[nkey] = item; - } else { - val[nkey] = numbertype.castForQuery({ val: item, context: context }); - } - } - } -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/boolean.js b/node_modules/mongoose/lib/cast/boolean.js deleted file mode 100644 index 4843e1f70b519fb087491c0cebf8cecb86c4833d..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/cast/boolean.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -const CastError = require('../error/cast'); - -/*! - * Given a value, cast it to a boolean, or throw a `CastError` if the value - * cannot be casted. `null` and `undefined` are considered valid. - * - * @param {Any} value - * @param {String} [path] optional the path to set on the CastError - * @return {Boolean|null|undefined} - * @throws {CastError} if `value` is not one of the allowed values - * @api private - */ - -module.exports = function castBoolean(value, path) { - if (value == null) { - return value; - } - - if (module.exports.convertToTrue.has(value)) { - return true; - } - if (module.exports.convertToFalse.has(value)) { - return false; - } - throw new CastError('boolean', value, path); -}; - -module.exports.convertToTrue = new Set([true, 'true', 1, '1', 'yes']); -module.exports.convertToFalse = new Set([false, 'false', 0, '0', 'no']); diff --git a/node_modules/mongoose/lib/cast/date.js b/node_modules/mongoose/lib/cast/date.js deleted file mode 100644 index ac17006df70bc6e7a60e4088ef6dad9ea1886d5f..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/cast/date.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -const assert = require('assert'); - -module.exports = function castDate(value) { - // Support empty string because of empty form values. Originally introduced - // in https://github.com/Automattic/mongoose/commit/efc72a1898fc3c33a319d915b8c5463a22938dfe - if (value == null || value === '') { - return null; - } - - if (value instanceof Date) { - assert.ok(!isNaN(value.valueOf())); - - return value; - } - - let date; - - assert.ok(typeof value !== 'boolean'); - - if (value instanceof Number || typeof value === 'number') { - date = new Date(value); - } else if (typeof value === 'string' && !isNaN(Number(value)) && (Number(value) >= 275761 || Number(value) < -271820)) { - // string representation of milliseconds take this path - date = new Date(Number(value)); - } else if (typeof value.valueOf === 'function') { - // support for moment.js. This is also the path strings will take because - // strings have a `valueOf()` - date = new Date(value.valueOf()); - } else { - // fallback - date = new Date(value); - } - - if (!isNaN(date.valueOf())) { - return date; - } - - assert.ok(false); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/decimal128.js b/node_modules/mongoose/lib/cast/decimal128.js deleted file mode 100644 index bfb1578c406cef3813b4c975c7823cf6770cd486..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/cast/decimal128.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -const Decimal128Type = require('../types/decimal128'); -const assert = require('assert'); - -module.exports = function castDecimal128(value) { - if (value == null) { - return value; - } - - if (typeof value === 'object' && typeof value.$numberDecimal === 'string') { - return Decimal128Type.fromString(value.$numberDecimal); - } - - if (value instanceof Decimal128Type) { - return value; - } - - if (typeof value === 'string') { - return Decimal128Type.fromString(value); - } - - if (Buffer.isBuffer(value)) { - return new Decimal128Type(value); - } - - if (typeof value === 'number') { - return Decimal128Type.fromString(String(value)); - } - - if (typeof value.valueOf === 'function' && typeof value.valueOf() === 'string') { - return Decimal128Type.fromString(value.valueOf()); - } - - assert.ok(false); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/number.js b/node_modules/mongoose/lib/cast/number.js deleted file mode 100644 index abc22f65cb9ec107399b24c2ca7007efcba96b2a..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/cast/number.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const assert = require('assert'); - -/*! - * Given a value, cast it to a number, or throw a `CastError` if the value - * cannot be casted. `null` and `undefined` are considered valid. - * - * @param {Any} value - * @param {String} [path] optional the path to set on the CastError - * @return {Boolean|null|undefined} - * @throws {Error} if `value` is not one of the allowed values - * @api private - */ - -module.exports = function castNumber(val) { - assert.ok(!isNaN(val)); - - if (val == null) { - return val; - } - if (val === '') { - return null; - } - - if (typeof val === 'string' || typeof val === 'boolean') { - val = Number(val); - } - - assert.ok(!isNaN(val)); - if (val instanceof Number) { - return val; - } - if (typeof val === 'number') { - return val; - } - if (!Array.isArray(val) && typeof val.valueOf === 'function') { - return Number(val.valueOf()); - } - if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) { - return new Number(val); - } - - assert.ok(false); -}; diff --git a/node_modules/mongoose/lib/cast/objectid.js b/node_modules/mongoose/lib/cast/objectid.js deleted file mode 100644 index 67cffb543042373e9a964941f2cf67079db858c0..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/cast/objectid.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const ObjectId = require('../driver').get().ObjectId; -const assert = require('assert'); - -module.exports = function castObjectId(value) { - if (value == null) { - return value; - } - - if (value instanceof ObjectId) { - return value; - } - - if (value._id) { - if (value._id instanceof ObjectId) { - return value._id; - } - if (value._id.toString instanceof Function) { - return new ObjectId(value._id.toString()); - } - } - - if (value.toString instanceof Function) { - return new ObjectId(value.toString()); - } - - assert.ok(false); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/string.js b/node_modules/mongoose/lib/cast/string.js deleted file mode 100644 index c9080138d10f89236fba533dff059cdb06c7989e..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/cast/string.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const CastError = require('../error/cast'); - -/*! - * Given a value, cast it to a string, or throw a `CastError` if the value - * cannot be casted. `null` and `undefined` are considered valid. - * - * @param {Any} value - * @param {String} [path] optional the path to set on the CastError - * @return {string|null|undefined} - * @throws {CastError} - * @api private - */ - -module.exports = function castString(value, path) { - // If null or undefined - if (value == null) { - return value; - } - - // handle documents being passed - if (value._id && typeof value._id === 'string') { - return value._id; - } - - // Re: gh-647 and gh-3030, we're ok with casting using `toString()` - // **unless** its the default Object.toString, because "[object Object]" - // doesn't really qualify as useful data - if (value.toString && value.toString !== Object.prototype.toString) { - return value.toString(); - } - - throw new CastError('string', value, path); -}; diff --git a/node_modules/mongoose/lib/collection.js b/node_modules/mongoose/lib/collection.js deleted file mode 100644 index 1f797058b445b78c9696cd1009cfe6de0d00fa95..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/collection.js +++ /dev/null @@ -1,269 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const EventEmitter = require('events').EventEmitter; -const STATES = require('./connectionstate'); -const immediate = require('./helpers/immediate'); - -/** - * Abstract Collection constructor - * - * This is the base class that drivers inherit from and implement. - * - * @param {String} name name of the collection - * @param {Connection} conn A MongooseConnection instance - * @param {Object} opts optional collection options - * @api public - */ - -function Collection(name, conn, opts) { - if (opts === void 0) { - opts = {}; - } - if (opts.capped === void 0) { - opts.capped = {}; - } - - opts.bufferCommands = undefined === opts.bufferCommands - ? true - : opts.bufferCommands; - - if (typeof opts.capped === 'number') { - opts.capped = {size: opts.capped}; - } - - this.opts = opts; - this.name = name; - this.collectionName = name; - this.conn = conn; - this.queue = []; - this.buffer = this.opts.bufferCommands; - this.emitter = new EventEmitter(); - - if (STATES.connected === this.conn.readyState) { - this.onOpen(); - } -} - -/** - * The collection name - * - * @api public - * @property name - */ - -Collection.prototype.name; - -/** - * The collection name - * - * @api public - * @property collectionName - */ - -Collection.prototype.collectionName; - -/** - * The Connection instance - * - * @api public - * @property conn - */ - -Collection.prototype.conn; - -/** - * Called when the database connects - * - * @api private - */ - -Collection.prototype.onOpen = function() { - this.buffer = false; - immediate(() => this.doQueue()); -}; - -/** - * Called when the database disconnects - * - * @api private - */ - -Collection.prototype.onClose = function(force) { - if (this.opts.bufferCommands && !force) { - this.buffer = true; - } -}; - -/** - * Queues a method for later execution when its - * database connection opens. - * - * @param {String} name name of the method to queue - * @param {Array} args arguments to pass to the method when executed - * @api private - */ - -Collection.prototype.addQueue = function(name, args) { - this.queue.push([name, args]); - return this; -}; - -/** - * Executes all queued methods and clears the queue. - * - * @api private - */ - -Collection.prototype.doQueue = function() { - for (let i = 0, l = this.queue.length; i < l; i++) { - if (typeof this.queue[i][0] === 'function') { - this.queue[i][0].apply(this, this.queue[i][1]); - } else { - this[this.queue[i][0]].apply(this, this.queue[i][1]); - } - } - this.queue = []; - const _this = this; - process.nextTick(function() { - _this.emitter.emit('queue'); - }); - return this; -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.ensureIndex = function() { - throw new Error('Collection#ensureIndex unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.createIndex = function() { - throw new Error('Collection#ensureIndex unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findAndModify = function() { - throw new Error('Collection#findAndModify unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findOneAndUpdate = function() { - throw new Error('Collection#findOneAndUpdate unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findOneAndDelete = function() { - throw new Error('Collection#findOneAndDelete unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findOneAndReplace = function() { - throw new Error('Collection#findOneAndReplace unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findOne = function() { - throw new Error('Collection#findOne unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.find = function() { - throw new Error('Collection#find unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.insert = function() { - throw new Error('Collection#insert unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.insertOne = function() { - throw new Error('Collection#insertOne unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.insertMany = function() { - throw new Error('Collection#insertMany unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.save = function() { - throw new Error('Collection#save unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.update = function() { - throw new Error('Collection#update unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.getIndexes = function() { - throw new Error('Collection#getIndexes unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.mapReduce = function() { - throw new Error('Collection#mapReduce unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.watch = function() { - throw new Error('Collection#watch unimplemented by driver'); -}; - -/*! - * Module exports. - */ - -module.exports = Collection; diff --git a/node_modules/mongoose/lib/connection.js b/node_modules/mongoose/lib/connection.js deleted file mode 100644 index ff382938c2eea3412900e9b1ad007b1fbb5e7458..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/connection.js +++ /dev/null @@ -1,960 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const EventEmitter = require('events').EventEmitter; -const Schema = require('./schema'); -const Collection = require('./driver').get().Collection; -const STATES = require('./connectionstate'); -const MongooseError = require('./error'); -const PromiseProvider = require('./promise_provider'); -const get = require('./helpers/get'); -const mongodb = require('mongodb'); -const utils = require('./utils'); - -const parseConnectionString = require('mongodb-core').parseConnectionString; - -/*! - * A list of authentication mechanisms that don't require a password for authentication. - * This is used by the authMechanismDoesNotRequirePassword method. - * - * @api private - */ -const noPasswordAuthMechanisms = [ - 'MONGODB-X509' -]; - -/** - * Connection constructor - * - * For practical reasons, a Connection equals a Db. - * - * @param {Mongoose} base a mongoose instance - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `connecting`: Emitted when `connection.openUri()` is executed on this connection. - * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios. - * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models. - * @event `disconnecting`: Emitted when `connection.close()` was executed. - * @event `disconnected`: Emitted after getting disconnected from the db. - * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models. - * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection. - * @event `error`: Emitted when an error occurs on this connection. - * @event `fullsetup`: Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected. - * @event `all`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. - * @api public - */ - -function Connection(base) { - this.base = base; - this.collections = {}; - this.models = {}; - this.config = {autoIndex: true}; - this.replica = false; - this.options = null; - this.otherDbs = []; // FIXME: To be replaced with relatedDbs - this.relatedDbs = {}; // Hashmap of other dbs that share underlying connection - this.states = STATES; - this._readyState = STATES.disconnected; - this._closeCalled = false; - this._hasOpened = false; - - this.$internalEmitter = new EventEmitter(); - this.$internalEmitter.setMaxListeners(0); -} - -/*! - * Inherit from EventEmitter - */ - -Connection.prototype.__proto__ = EventEmitter.prototype; - -/** - * Connection ready state - * - * - 0 = disconnected - * - 1 = connected - * - 2 = connecting - * - 3 = disconnecting - * - * Each state change emits its associated event name. - * - * ####Example - * - * conn.on('connected', callback); - * conn.on('disconnected', callback); - * - * @property readyState - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'readyState', { - get: function() { - return this._readyState; - }, - set: function(val) { - if (!(val in STATES)) { - throw new Error('Invalid connection state: ' + val); - } - - if (this._readyState !== val) { - this._readyState = val; - // [legacy] loop over the otherDbs on this connection and change their state - for (let i = 0; i < this.otherDbs.length; i++) { - this.otherDbs[i].readyState = val; - } - - // loop over relatedDbs on this connection and change their state - for (const k in this.relatedDbs) { - this.relatedDbs[k].readyState = val; - } - - if (STATES.connected === val) { - this._hasOpened = true; - } - - this.emit(STATES[val]); - } - } -}); - -/** - * A hash of the collections associated with this connection - * - * @property collections - * @memberOf Connection - * @instance - * @api public - */ - -Connection.prototype.collections; - -/** - * The name of the database this connection points to. - * - * ####Example - * - * mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb" - * - * @property name - * @memberOf Connection - * @instance - * @api public - */ - -Connection.prototype.name; - -/** - * The host name portion of the URI. If multiple hosts, such as a replica set, - * this will contain the first host name in the URI - * - * ####Example - * - * mongoose.createConnection('mongodb://localhost:27017/mydb').host; // "localhost" - * - * @property host - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'host', { - configurable: true, - enumerable: true, - writable: true -}); - -/** - * The port portion of the URI. If multiple hosts, such as a replica set, - * this will contain the port from the first host name in the URI. - * - * ####Example - * - * mongoose.createConnection('mongodb://localhost:27017/mydb').port; // 27017 - * - * @property port - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'port', { - configurable: true, - enumerable: true, - writable: true -}); - -/** - * The username specified in the URI - * - * ####Example - * - * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').user; // "val" - * - * @property user - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'user', { - configurable: true, - enumerable: true, - writable: true -}); - -/** - * The password specified in the URI - * - * ####Example - * - * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').pass; // "psw" - * - * @property pass - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'pass', { - configurable: true, - enumerable: true, - writable: true -}); - -/** - * The mongodb.Db instance, set when the connection is opened - * - * @property db - * @memberOf Connection - * @instance - * @api public - */ - -Connection.prototype.db; - -/** - * A hash of the global options that are associated with this connection - * - * @property config - * @memberOf Connection - * @instance - * @api public - */ - -Connection.prototype.config; - -/** - * Helper for `createCollection()`. Will explicitly create the given collection - * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/) - * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose. - * - * Options are passed down without modification to the [MongoDB driver's `createCollection()` function](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) - * - * @method createCollection - * @param {string} collection The collection to create - * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Connection.prototype.createCollection = _wrapConnHelper(function createCollection(collection, options, cb) { - if (typeof options === 'function') { - cb = options; - options = {}; - } - this.db.createCollection(collection, options, cb); -}); - -/** - * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) - * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), - * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). - * - * ####Example: - * - * const session = await conn.startSession(); - * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); - * await doc.remove(); - * // `doc` will always be null, even if reading from a replica set - * // secondary. Without causal consistency, it is possible to - * // get a doc back from the below query if the query reads from a - * // secondary that is experiencing replication lag. - * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); - * - * - * @method startSession - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) - * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency - * @param {Function} [callback] - * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession` - * @api public - */ - -Connection.prototype.startSession = _wrapConnHelper(function startSession(options, cb) { - if (typeof options === 'function') { - cb = options; - options = null; - } - const session = this.client.startSession(options); - cb(null, session); -}); - -/** - * Helper for `dropCollection()`. Will delete the given collection, including - * all documents and indexes. - * - * @method dropCollection - * @param {string} collection The collection to delete - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(collection, cb) { - this.db.dropCollection(collection, cb); -}); - -/** - * Helper for `dropDatabase()`. Deletes the given database, including all - * collections, documents, and indexes. - * - * @method dropDatabase - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) { - this.$internalEmitter.emit('dropDatabase'); - this.db.dropDatabase(cb); -}); - -/*! - * ignore - */ - -function _wrapConnHelper(fn) { - return function() { - const cb = arguments.length > 0 ? arguments[arguments.length - 1] : null; - const argsWithoutCb = typeof cb === 'function' ? - Array.prototype.slice.call(arguments, 0, arguments.length - 1) : - Array.prototype.slice.call(arguments); - return utils.promiseOrCallback(cb, cb => { - if (this.readyState !== STATES.connected) { - this.once('open', function() { - fn.apply(this, argsWithoutCb.concat([cb])); - }); - } else { - fn.apply(this, argsWithoutCb.concat([cb])); - } - }); - }; -} - -/** - * error - * - * Graceful error handling, passes error to callback - * if available, else emits error on the connection. - * - * @param {Error} err - * @param {Function} callback optional - * @api private - */ - -Connection.prototype.error = function(err, callback) { - if (callback) { - callback(err); - return null; - } - if (this.listeners('error').length > 0) { - this.emit('error', err); - } - return Promise.reject(err); -}; - -/** - * Called when the connection is opened - * - * @api private - */ - -Connection.prototype.onOpen = function() { - this.readyState = STATES.connected; - - // avoid having the collection subscribe to our event emitter - // to prevent 0.3 warning - for (const i in this.collections) { - if (utils.object.hasOwnProperty(this.collections, i)) { - this.collections[i].onOpen(); - } - } - - this.emit('open'); -}; - -/** - * Opens the connection with a URI using `MongoClient.connect()`. - * - * @param {String} uri The URI to connect with. - * @param {Object} [options] Passed on to http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect - * @param {Function} [callback] - * @returns {Connection} this - * @api private - */ - -Connection.prototype.openUri = function(uri, options, callback) { - this.readyState = STATES.connecting; - this._closeCalled = false; - - if (typeof options === 'function') { - callback = options; - options = null; - } - - if (['string', 'number'].indexOf(typeof options) !== -1) { - throw new MongooseError('Mongoose 5.x no longer supports ' + - '`mongoose.connect(host, dbname, port)` or ' + - '`mongoose.createConnection(host, dbname, port)`. See ' + - 'http://mongoosejs.com/docs/connections.html for supported connection syntax'); - } - - if (typeof uri !== 'string') { - throw new MongooseError('The `uri` parameter to `openUri()` must be a ' + - `string, got "${typeof uri}". Make sure the first parameter to ` + - '`mongoose.connect()` or `mongoose.createConnection()` is a string.'); - } - - const Promise = PromiseProvider.get(); - const _this = this; - - if (options) { - options = utils.clone(options); - const autoIndex = options.config && options.config.autoIndex != null ? - options.config.autoIndex : - options.autoIndex; - if (autoIndex != null) { - this.config.autoIndex = autoIndex !== false; - delete options.config; - delete options.autoIndex; - } - - if ('autoCreate' in options) { - this.config.autoCreate = !!options.autoCreate; - delete options.autoCreate; - } - if ('useCreateIndex' in options) { - this.config.useCreateIndex = !!options.useCreateIndex; - delete options.useCreateIndex; - } - - if ('useFindAndModify' in options) { - this.config.useFindAndModify = !!options.useFindAndModify; - delete options.useFindAndModify; - } - - // Backwards compat - if (options.user || options.pass) { - options.auth = options.auth || {}; - options.auth.user = options.user; - options.auth.password = options.pass; - - this.user = options.user; - this.pass = options.pass; - } - delete options.user; - delete options.pass; - - if (options.bufferCommands != null) { - options.bufferMaxEntries = 0; - this.config.bufferCommands = options.bufferCommands; - delete options.bufferCommands; - } - - if (options.useMongoClient != null) { - handleUseMongoClient(options); - } - } else { - options = {}; - } - - this._connectionOptions = options; - const dbName = options.dbName; - if (dbName != null) { - this.$dbName = dbName; - } - delete options.dbName; - - if (!('promiseLibrary' in options)) { - options.promiseLibrary = PromiseProvider.get(); - } - if (!('useNewUrlParser' in options)) { - if ('useNewUrlParser' in this.base.options) { - options.useNewUrlParser = this.base.options.useNewUrlParser; - } else { - options.useNewUrlParser = false; - } - } - - const parsePromise = new Promise((resolve, reject) => { - parseConnectionString(uri, options, (err, parsed) => { - if (err) { - return reject(err); - } - this.name = dbName != null ? dbName : get(parsed, 'auth.db', null); - this.host = get(parsed, 'hosts.0.host', 'localhost'); - this.port = get(parsed, 'hosts.0.port', 27017); - this.user = this.user || get(parsed, 'auth.username'); - this.pass = this.pass || get(parsed, 'auth.password'); - resolve(); - }); - }); - - const promise = new Promise((resolve, reject) => { - const client = new mongodb.MongoClient(uri, options); - _this.client = client; - client.connect(function(error) { - if (error) { - _this.readyState = STATES.disconnected; - return reject(error); - } - - const db = dbName != null ? client.db(dbName) : client.db(); - _this.db = db; - - // Backwards compat for mongoose 4.x - db.on('reconnect', function() { - // If we aren't disconnected, we assume this reconnect is due to a - // socket timeout. If there's no activity on a socket for - // `socketTimeoutMS`, the driver will attempt to reconnect and emit - // this event. - if (_this.readyState !== STATES.connected) { - _this.readyState = STATES.connected; - _this.emit('reconnect'); - _this.emit('reconnected'); - } - }); - db.s.topology.on('reconnectFailed', function() { - _this.emit('reconnectFailed'); - }); - db.s.topology.on('left', function(data) { - _this.emit('left', data); - }); - db.s.topology.on('joined', function(data) { - _this.emit('joined', data); - }); - db.s.topology.on('fullsetup', function(data) { - _this.emit('fullsetup', data); - }); - db.on('close', function() { - // Implicitly emits 'disconnected' - _this.readyState = STATES.disconnected; - }); - client.on('left', function() { - if (_this.readyState === STATES.connected && - get(db, 's.topology.s.coreTopology.s.replicaSetState.topologyType') === 'ReplicaSetNoPrimary') { - _this.readyState = STATES.disconnected; - } - }); - db.on('timeout', function() { - _this.emit('timeout'); - }); - - delete _this.then; - delete _this.catch; - _this.readyState = STATES.connected; - - for (const i in _this.collections) { - if (utils.object.hasOwnProperty(_this.collections, i)) { - _this.collections[i].onOpen(); - } - } - - resolve(_this); - _this.emit('open'); - }); - }); - - this.$initialConnection = Promise.all([promise, parsePromise]). - then(res => res[0]). - catch(err => { - if (this.listeners('error').length > 0) { - process.nextTick(() => this.emit('error', err)); - return; - } - throw err; - }); - this.then = function(resolve, reject) { - return this.$initialConnection.then(resolve, reject); - }; - this.catch = function(reject) { - return this.$initialConnection.catch(reject); - }; - - if (callback != null) { - this.$initialConnection = this.$initialConnection.then( - () => callback(null, this), - err => callback(err) - ); - } - - return this; -}; - -/*! - * ignore - */ - -const handleUseMongoClient = function handleUseMongoClient(options) { - console.warn('WARNING: The `useMongoClient` option is no longer ' + - 'necessary in mongoose 5.x, please remove it.'); - const stack = new Error().stack; - console.warn(stack.substr(stack.indexOf('\n') + 1)); - delete options.useMongoClient; -}; - -/** - * Closes the connection - * - * @param {Boolean} [force] optional - * @param {Function} [callback] optional - * @return {Connection} self - * @api public - */ - -Connection.prototype.close = function(force, callback) { - if (typeof force === 'function') { - callback = force; - force = false; - } - - this.$wasForceClosed = !!force; - - return utils.promiseOrCallback(callback, cb => { - this._close(force, cb); - }); -}; - -/** - * Handles closing the connection - * - * @param {Boolean} force - * @param {Function} callback - * @api private - */ -Connection.prototype._close = function(force, callback) { - const _this = this; - this._closeCalled = true; - - switch (this.readyState) { - case 0: // disconnected - callback(); - break; - - case 1: // connected - this.readyState = STATES.disconnecting; - this.doClose(force, function(err) { - if (err) { - return callback(err); - } - _this.onClose(force); - callback(null); - }); - - break; - case 2: // connecting - this.once('open', function() { - _this.close(callback); - }); - break; - - case 3: // disconnecting - this.once('close', function() { - callback(); - }); - break; - } - - return this; -}; - -/** - * Called when the connection closes - * - * @api private - */ - -Connection.prototype.onClose = function(force) { - this.readyState = STATES.disconnected; - - // avoid having the collection subscribe to our event emitter - // to prevent 0.3 warning - for (const i in this.collections) { - if (utils.object.hasOwnProperty(this.collections, i)) { - this.collections[i].onClose(force); - } - } - - this.emit('close', force); -}; - -/** - * Retrieves a collection, creating it if not cached. - * - * Not typically needed by applications. Just talk to your collection through your model. - * - * @param {String} name of the collection - * @param {Object} [options] optional collection options - * @return {Collection} collection instance - * @api public - */ - -Connection.prototype.collection = function(name, options) { - options = options ? utils.clone(options) : {}; - options.$wasForceClosed = this.$wasForceClosed; - if (!(name in this.collections)) { - this.collections[name] = new Collection(name, this, options); - } - return this.collections[name]; -}; - -/** - * Defines or retrieves a model. - * - * var mongoose = require('mongoose'); - * var db = mongoose.createConnection(..); - * db.model('Venue', new Schema(..)); - * var Ticket = db.model('Ticket', new Schema(..)); - * var Venue = db.model('Venue'); - * - * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ - * - * ####Example: - * - * var schema = new Schema({ name: String }, { collection: 'actor' }); - * - * // or - * - * schema.set('collection', 'actor'); - * - * // or - * - * var collectionName = 'actor' - * var M = conn.model('Actor', schema, collectionName) - * - * @param {String|Function} name the model name or class extending Model - * @param {Schema} [schema] a schema. necessary when defining a model - * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name - * @see Mongoose#model #index_Mongoose-model - * @return {Model} The compiled model - * @api public - */ - -Connection.prototype.model = function(name, schema, collection) { - if (!(this instanceof Connection)) { - throw new MongooseError('`connection.model()` should not be run with ' + - '`new`. If you are doing `new db.model(foo)(bar)`, use ' + - '`db.model(foo)(bar)` instead'); - } - - let fn; - if (typeof name === 'function') { - fn = name; - name = fn.name; - } - - // collection name discovery - if (typeof schema === 'string') { - collection = schema; - schema = false; - } - - if (utils.isObject(schema) && !schema.instanceOfSchema) { - schema = new Schema(schema); - } - if (schema && !schema.instanceOfSchema) { - throw new Error('The 2nd parameter to `mongoose.model()` should be a ' + - 'schema or a POJO'); - } - - if (this.models[name] && !collection) { - // model exists but we are not subclassing with custom collection - if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { - throw new MongooseError.OverwriteModelError(name); - } - return this.models[name]; - } - - const opts = {cache: false, connection: this}; - let model; - - if (schema && schema.instanceOfSchema) { - // compile a model - model = this.base.model(fn || name, schema, collection, opts); - - // only the first model with this name is cached to allow - // for one-offs with custom collection names etc. - if (!this.models[name]) { - this.models[name] = model; - } - - // Errors handled internally, so safe to ignore error - model.init(function $modelInitNoop() {}); - - return model; - } - - if (this.models[name] && collection) { - // subclassing current model with alternate collection - model = this.models[name]; - schema = model.prototype.schema; - const sub = model.__subclass(this, schema, collection); - // do not cache the sub model - return sub; - } - - // lookup model in mongoose module - model = this.base.models[name]; - - if (!model) { - throw new MongooseError.MissingSchemaError(name); - } - - if (this === model.prototype.db - && (!collection || collection === model.collection.name)) { - // model already uses this connection. - - // only the first model with this name is cached to allow - // for one-offs with custom collection names etc. - if (!this.models[name]) { - this.models[name] = model; - } - - return model; - } - this.models[name] = model.__subclass(this, schema, collection); - return this.models[name]; -}; - -/** - * Removes the model named `name` from this connection, if it exists. You can - * use this function to clean up any models you created in your tests to - * prevent OverwriteModelErrors. - * - * ####Example: - * - * conn.model('User', new Schema({ name: String })); - * console.log(conn.model('User')); // Model object - * conn.deleteModel('User'); - * console.log(conn.model('User')); // undefined - * - * // Usually useful in a Mocha `afterEach()` hook - * afterEach(function() { - * conn.deleteModel(/.+/); // Delete every model - * }); - * - * @api public - * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. - * @return {Connection} this - */ - -Connection.prototype.deleteModel = function(name) { - if (typeof name === 'string') { - const model = this.model(name); - if (model == null) { - return this; - } - delete this.models[name]; - delete this.collections[model.collection.name]; - delete this.base.modelSchemas[name]; - } else if (name instanceof RegExp) { - const pattern = name; - const names = this.modelNames(); - for (const name of names) { - if (pattern.test(name)) { - this.deleteModel(name); - } - } - } else { - throw new Error('First parameter to `deleteModel()` must be a string ' + - 'or regexp, got "' + name + '"'); - } - - return this; -}; - -/** - * Returns an array of model names created on this connection. - * @api public - * @return {Array} - */ - -Connection.prototype.modelNames = function() { - return Object.keys(this.models); -}; - -/** - * @brief Returns if the connection requires authentication after it is opened. Generally if a - * username and password are both provided than authentication is needed, but in some cases a - * password is not required. - * @api private - * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false. - */ -Connection.prototype.shouldAuthenticate = function() { - return this.user != null && - (this.pass != null || this.authMechanismDoesNotRequirePassword()); -}; - -/** - * @brief Returns a boolean value that specifies if the current authentication mechanism needs a - * password to authenticate according to the auth objects passed into the openUri methods. - * @api private - * @return {Boolean} true if the authentication mechanism specified in the options object requires - * a password, otherwise false. - */ -Connection.prototype.authMechanismDoesNotRequirePassword = function() { - if (this.options && this.options.auth) { - return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0; - } - return true; -}; - -/** - * @brief Returns a boolean value that specifies if the provided objects object provides enough - * data to authenticate with. Generally this is true if the username and password are both specified - * but in some authentication methods, a password is not required for authentication so only a username - * is required. - * @param {Object} [options] the options object passed into the openUri methods. - * @api private - * @return {Boolean} true if the provided options object provides enough data to authenticate with, - * otherwise false. - */ -Connection.prototype.optionsProvideAuthenticationData = function(options) { - return (options) && - (options.user) && - ((options.pass) || this.authMechanismDoesNotRequirePassword()); -}; - -/** - * Switches to a different database using the same connection pool. - * - * Returns a new connection object, with the new db. - * - * @method useDb - * @memberOf Connection - * @param {String} name The database name - * @return {Connection} New Connection Object - * @api public - */ - -/*! - * Module exports. - */ - -Connection.STATES = STATES; -module.exports = Connection; diff --git a/node_modules/mongoose/lib/connectionstate.js b/node_modules/mongoose/lib/connectionstate.js deleted file mode 100644 index 920f45bee98b496a6c36a4b07027cc520616d7e2..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/connectionstate.js +++ /dev/null @@ -1,26 +0,0 @@ - -/*! - * Connection states - */ - -'use strict'; - -const STATES = module.exports = exports = Object.create(null); - -const disconnected = 'disconnected'; -const connected = 'connected'; -const connecting = 'connecting'; -const disconnecting = 'disconnecting'; -const uninitialized = 'uninitialized'; - -STATES[0] = disconnected; -STATES[1] = connected; -STATES[2] = connecting; -STATES[3] = disconnecting; -STATES[99] = uninitialized; - -STATES[disconnected] = 0; -STATES[connected] = 1; -STATES[connecting] = 2; -STATES[disconnecting] = 3; -STATES[uninitialized] = 99; diff --git a/node_modules/mongoose/lib/cursor/AggregationCursor.js b/node_modules/mongoose/lib/cursor/AggregationCursor.js deleted file mode 100644 index 45acc94d4a8dfc72cc6d4428fbb5d638746dc530..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/cursor/AggregationCursor.js +++ /dev/null @@ -1,296 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const Readable = require('stream').Readable; -const eachAsync = require('../helpers/cursor/eachAsync'); -const util = require('util'); -const utils = require('../utils'); - -/** - * An AggregationCursor is a concurrency primitive for processing aggregation - * results one document at a time. It is analogous to QueryCursor. - * - * An AggregationCursor fulfills the Node.js streams3 API, - * in addition to several other mechanisms for loading documents from MongoDB - * one at a time. - * - * Creating an AggregationCursor executes the model's pre aggregate hooks, - * but **not** the model's post aggregate hooks. - * - * Unless you're an advanced user, do **not** instantiate this class directly. - * Use [`Aggregate#cursor()`](/docs/api.html#aggregate_Aggregate-cursor) instead. - * - * @param {Aggregate} agg - * @param {Object} options - * @inherits Readable - * @event `cursor`: Emitted when the cursor is created - * @event `error`: Emitted when an error occurred - * @event `data`: Emitted when the stream is flowing and the next doc is ready - * @event `end`: Emitted when the stream is exhausted - * @api public - */ - -function AggregationCursor(agg) { - Readable.call(this, { objectMode: true }); - - this.cursor = null; - this.agg = agg; - this._transforms = []; - const model = agg._model; - delete agg.options.cursor.useMongooseAggCursor; - this._mongooseOptions = {}; - - _init(model, this, agg); -} - -util.inherits(AggregationCursor, Readable); - -/*! - * ignore - */ - -function _init(model, c, agg) { - if (!model.collection.buffer) { - model.hooks.execPre('aggregate', agg, function() { - c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {}); - c.emit('cursor', c.cursor); - }); - } else { - model.collection.emitter.once('queue', function() { - model.hooks.execPre('aggregate', agg, function() { - c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {}); - c.emit('cursor', c.cursor); - }); - }); - } -} - -/*! - * Necessary to satisfy the Readable API - */ - -AggregationCursor.prototype._read = function() { - const _this = this; - _next(this, function(error, doc) { - if (error) { - return _this.emit('error', error); - } - if (!doc) { - _this.push(null); - _this.cursor.close(function(error) { - if (error) { - return _this.emit('error', error); - } - setTimeout(function() { - _this.emit('close'); - }, 0); - }); - return; - } - _this.push(doc); - }); -}; - -/** - * Registers a transform function which subsequently maps documents retrieved - * via the streams interface or `.next()` - * - * ####Example - * - * // Map documents returned by `data` events - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }) - * on('data', function(doc) { console.log(doc.foo); }); - * - * // Or map documents returned by `.next()` - * var cursor = Thing.find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }); - * cursor.next(function(error, doc) { - * console.log(doc.foo); - * }); - * - * @param {Function} fn - * @return {AggregationCursor} - * @api public - * @method map - */ - -AggregationCursor.prototype.map = function(fn) { - this._transforms.push(fn); - return this; -}; - -/*! - * Marks this cursor as errored - */ - -AggregationCursor.prototype._markError = function(error) { - this._error = error; - return this; -}; - -/** - * Marks this cursor as closed. Will stop streaming and subsequent calls to - * `next()` will error. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method close - * @emits close - * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close - */ - -AggregationCursor.prototype.close = function(callback) { - return utils.promiseOrCallback(callback, cb => { - this.cursor.close(error => { - if (error) { - cb(error); - return this.listeners('error').length > 0 && this.emit('error', error); - } - this.emit('close'); - cb(null); - }); - }); -}; - -/** - * Get the next document from this cursor. Will return `null` when there are - * no documents left. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method next - */ - -AggregationCursor.prototype.next = function(callback) { - return utils.promiseOrCallback(callback, cb => { - _next(this, cb); - }); -}; - -/** - * Execute `fn` for every document in the cursor. If `fn` returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * - * @param {Function} fn - * @param {Object} [options] - * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1. - * @param {Function} [callback] executed when all docs have been processed - * @return {Promise} - * @api public - * @method eachAsync - */ - -AggregationCursor.prototype.eachAsync = function(fn, opts, callback) { - const _this = this; - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - opts = opts || {}; - - return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback); -}; - -/*! - * ignore - */ - -AggregationCursor.prototype.transformNull = function(val) { - if (arguments.length === 0) { - val = true; - } - this._mongooseOptions.transformNull = val; - return this; -}; - -/** - * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). - * Useful for setting the `noCursorTimeout` and `tailable` flags. - * - * @param {String} flag - * @param {Boolean} value - * @return {AggregationCursor} this - * @api public - * @method addCursorFlag - */ - -AggregationCursor.prototype.addCursorFlag = function(flag, value) { - const _this = this; - _waitForCursor(this, function() { - _this.cursor.addCursorFlag(flag, value); - }); - return this; -}; - -/*! - * ignore - */ - -function _waitForCursor(ctx, cb) { - if (ctx.cursor) { - return cb(); - } - ctx.once('cursor', function() { - cb(); - }); -} - -/*! - * Get the next doc from the underlying cursor and mongooseify it - * (populate, etc.) - */ - -function _next(ctx, cb) { - let callback = cb; - if (ctx._transforms.length) { - callback = function(err, doc) { - if (err || (doc === null && !ctx._mongooseOptions.transformNull)) { - return cb(err, doc); - } - cb(err, ctx._transforms.reduce(function(doc, fn) { - return fn(doc); - }, doc)); - }; - } - - if (ctx._error) { - return process.nextTick(function() { - callback(ctx._error); - }); - } - - if (ctx.cursor) { - return ctx.cursor.next(function(error, doc) { - if (error) { - return callback(error); - } - if (!doc) { - return callback(null, null); - } - - callback(null, doc); - }); - } else { - ctx.once('cursor', function() { - _next(ctx, cb); - }); - } -} - -module.exports = AggregationCursor; diff --git a/node_modules/mongoose/lib/cursor/ChangeStream.js b/node_modules/mongoose/lib/cursor/ChangeStream.js deleted file mode 100644 index e43521614d3c6b462e65a7a28b4ef5c1f229393b..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/cursor/ChangeStream.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const EventEmitter = require('events').EventEmitter; - -/*! - * ignore - */ - -class ChangeStream extends EventEmitter { - constructor(model, pipeline, options) { - super(); - - this.driverChangeStream = null; - this.closed = false; - // This wrapper is necessary because of buffering. - if (model.collection.buffer) { - model.collection.addQueue(() => { - if (this.closed) { - return; - } - this.driverChangeStream = model.collection.watch(pipeline, options); - this._bindEvents(); - this.emit('ready'); - }); - } else { - this.driverChangeStream = model.collection.watch(pipeline, options); - this._bindEvents(); - this.emit('ready'); - } - } - - _bindEvents() { - ['close', 'change', 'end', 'error'].forEach(ev => { - this.driverChangeStream.on(ev, data => this.emit(ev, data)); - }); - } - - _queue(cb) { - this.once('ready', () => cb()); - } - - close() { - this.closed = true; - if (this.driverChangeStream) { - this.driverChangeStream.close(); - } - } -} - -/*! - * ignore - */ - -module.exports = ChangeStream; diff --git a/node_modules/mongoose/lib/cursor/QueryCursor.js b/node_modules/mongoose/lib/cursor/QueryCursor.js deleted file mode 100644 index d0f2f2c55301066f298f4ff92c15528600992ab5..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/cursor/QueryCursor.js +++ /dev/null @@ -1,331 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const Readable = require('stream').Readable; -const eachAsync = require('../helpers/cursor/eachAsync'); -const helpers = require('../queryhelpers'); -const util = require('util'); -const utils = require('../utils'); - -/** - * A QueryCursor is a concurrency primitive for processing query results - * one document at a time. A QueryCursor fulfills the Node.js streams3 API, - * in addition to several other mechanisms for loading documents from MongoDB - * one at a time. - * - * QueryCursors execute the model's pre find hooks, but **not** the model's - * post find hooks. - * - * Unless you're an advanced user, do **not** instantiate this class directly. - * Use [`Query#cursor()`](/docs/api.html#query_Query-cursor) instead. - * - * @param {Query} query - * @param {Object} options query options passed to `.find()` - * @inherits Readable - * @event `cursor`: Emitted when the cursor is created - * @event `error`: Emitted when an error occurred - * @event `data`: Emitted when the stream is flowing and the next doc is ready - * @event `end`: Emitted when the stream is exhausted - * @api public - */ - -function QueryCursor(query, options) { - Readable.call(this, { objectMode: true }); - - this.cursor = null; - this.query = query; - const _this = this; - const model = query.model; - this._mongooseOptions = {}; - this._transforms = []; - this.model = model; - model.hooks.execPre('find', query, () => { - this._transforms = this._transforms.concat(query._transforms.slice()); - if (options.transform) { - this._transforms.push(options.transform); - } - model.collection.find(query._conditions, options, function(err, cursor) { - if (_this._error) { - cursor.close(function() {}); - _this.listeners('error').length > 0 && _this.emit('error', _this._error); - } - if (err) { - return _this.emit('error', err); - } - _this.cursor = cursor; - _this.emit('cursor', cursor); - }); - }); -} - -util.inherits(QueryCursor, Readable); - -/*! - * Necessary to satisfy the Readable API - */ - -QueryCursor.prototype._read = function() { - const _this = this; - _next(this, function(error, doc) { - if (error) { - return _this.emit('error', error); - } - if (!doc) { - _this.push(null); - _this.cursor.close(function(error) { - if (error) { - return _this.emit('error', error); - } - setTimeout(function() { - _this.emit('close'); - }, 0); - }); - return; - } - _this.push(doc); - }); -}; - -/** - * Registers a transform function which subsequently maps documents retrieved - * via the streams interface or `.next()` - * - * ####Example - * - * // Map documents returned by `data` events - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }) - * on('data', function(doc) { console.log(doc.foo); }); - * - * // Or map documents returned by `.next()` - * var cursor = Thing.find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }); - * cursor.next(function(error, doc) { - * console.log(doc.foo); - * }); - * - * @param {Function} fn - * @return {QueryCursor} - * @api public - * @method map - */ - -QueryCursor.prototype.map = function(fn) { - this._transforms.push(fn); - return this; -}; - -/*! - * Marks this cursor as errored - */ - -QueryCursor.prototype._markError = function(error) { - this._error = error; - return this; -}; - -/** - * Marks this cursor as closed. Will stop streaming and subsequent calls to - * `next()` will error. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method close - * @emits close - * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close - */ - -QueryCursor.prototype.close = function(callback) { - return utils.promiseOrCallback(callback, cb => { - this.cursor.close(error => { - if (error) { - cb(error); - return this.listeners('error').length > 0 && this.emit('error', error); - } - this.emit('close'); - cb(null); - }); - }, this.model.events); -}; - -/** - * Get the next document from this cursor. Will return `null` when there are - * no documents left. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method next - */ - -QueryCursor.prototype.next = function(callback) { - return utils.promiseOrCallback(callback, cb => { - _next(this, function(error, doc) { - if (error) { - return cb(error); - } - cb(null, doc); - }); - }, this.model.events); -}; - -/** - * Execute `fn` for every document in the cursor. If `fn` returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * - * @param {Function} fn - * @param {Object} [options] - * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1. - * @param {Function} [callback] executed when all docs have been processed - * @return {Promise} - * @api public - * @method eachAsync - */ - -QueryCursor.prototype.eachAsync = function(fn, opts, callback) { - const _this = this; - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - opts = opts || {}; - - return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback); -}; - -/** - * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). - * Useful for setting the `noCursorTimeout` and `tailable` flags. - * - * @param {String} flag - * @param {Boolean} value - * @return {AggregationCursor} this - * @api public - * @method addCursorFlag - */ - -QueryCursor.prototype.addCursorFlag = function(flag, value) { - const _this = this; - _waitForCursor(this, function() { - _this.cursor.addCursorFlag(flag, value); - }); - return this; -}; - -/*! - * ignore - */ - -QueryCursor.prototype.transformNull = function(val) { - if (arguments.length === 0) { - val = true; - } - this._mongooseOptions.transformNull = val; - return this; -}; - -/*! - * Get the next doc from the underlying cursor and mongooseify it - * (populate, etc.) - */ - -function _next(ctx, cb) { - let callback = cb; - if (ctx._transforms.length) { - callback = function(err, doc) { - if (err || (doc === null && !ctx._mongooseOptions.transformNull)) { - return cb(err, doc); - } - cb(err, ctx._transforms.reduce(function(doc, fn) { - return fn.call(ctx, doc); - }, doc)); - }; - } - - if (ctx._error) { - return process.nextTick(function() { - callback(ctx._error); - }); - } - - if (ctx.cursor) { - return ctx.cursor.next(function(error, doc) { - if (error) { - return callback(error); - } - if (!doc) { - return callback(null, null); - } - - const opts = ctx.query._mongooseOptions; - if (!opts.populate) { - return opts.lean ? - callback(null, doc) : - _create(ctx, doc, null, callback); - } - - const pop = helpers.preparePopulationOptionsMQ(ctx.query, - ctx.query._mongooseOptions); - pop.__noPromise = true; - ctx.query.model.populate(doc, pop, function(err, doc) { - if (err) { - return callback(err); - } - return opts.lean ? - callback(null, doc) : - _create(ctx, doc, pop, callback); - }); - }); - } else { - ctx.once('cursor', function() { - _next(ctx, cb); - }); - } -} - -/*! - * ignore - */ - -function _waitForCursor(ctx, cb) { - if (ctx.cursor) { - return cb(); - } - ctx.once('cursor', function() { - cb(); - }); -} - -/*! - * Convert a raw doc into a full mongoose doc. - */ - -function _create(ctx, doc, populatedIds, cb) { - const instance = helpers.createModel(ctx.query.model, doc, ctx.query._fields); - const opts = populatedIds ? - { populated: populatedIds } : - undefined; - - instance.init(doc, opts, function(err) { - if (err) { - return cb(err); - } - cb(null, instance); - }); -} - -module.exports = QueryCursor; diff --git a/node_modules/mongoose/lib/document.js b/node_modules/mongoose/lib/document.js deleted file mode 100644 index 56f7c55360613ad8f2c97535613ad7b8a215e137..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/document.js +++ /dev/null @@ -1,3180 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const EventEmitter = require('events').EventEmitter; -const InternalCache = require('./internal'); -const MongooseError = require('./error'); -const MixedSchema = require('./schema/mixed'); -const ObjectExpectedError = require('./error/objectExpected'); -const ObjectParameterError = require('./error/objectParameter'); -const StrictModeError = require('./error/strict'); -const ValidatorError = require('./schematype').ValidatorError; -const VirtualType = require('./virtualtype'); -const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths'); -const compile = require('./helpers/document/compile').compile; -const defineKey = require('./helpers/document/compile').defineKey; -const flatten = require('./helpers/common').flatten; -const get = require('./helpers/get'); -const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath'); -const idGetter = require('./plugins/idGetter'); -const isDefiningProjection = require('./helpers/projection/isDefiningProjection'); -const isExclusive = require('./helpers/projection/isExclusive'); -const inspect = require('util').inspect; -const internalToObjectOptions = require('./options').internalToObjectOptions; -const mpath = require('mpath'); -const utils = require('./utils'); - -const ValidationError = MongooseError.ValidationError; -const clone = utils.clone; -const deepEqual = utils.deepEqual; -const isMongooseObject = utils.isMongooseObject; - -const documentArrayParent = require('./helpers/symbols').documentArrayParent; -const getSymbol = require('./helpers/symbols').getSymbol; - -let DocumentArray; -let MongooseArray; -let Embedded; - -const specialProperties = utils.specialProperties; - -/** - * The core Mongoose document constructor. You should not call this directly, - * the Mongoose [Model constructor](./api.html#Model) calls this for you. - * - * @param {Object} obj the values to set - * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data - * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose. - * @event `save`: Emitted when the document is successfully saved - * @api private - */ - -function Document(obj, fields, skipId, options) { - if (typeof skipId === 'object' && skipId != null) { - options = skipId; - skipId = options.skipId; - } - options = options || {}; - - this.$__ = new InternalCache; - this.$__.emitter = new EventEmitter(); - this.isNew = 'isNew' in options ? options.isNew : true; - this.errors = undefined; - this.$__.$options = options || {}; - - if (obj != null && typeof obj !== 'object') { - throw new ObjectParameterError(obj, 'obj', 'Document'); - } - - const schema = this.schema; - - if (typeof fields === 'boolean') { - this.$__.strictMode = fields; - fields = undefined; - } else { - this.$__.strictMode = schema.options.strict; - this.$__.selected = fields; - } - - const required = schema.requiredPaths(true); - for (let i = 0; i < required.length; ++i) { - this.$__.activePaths.require(required[i]); - } - - this.$__.emitter.setMaxListeners(0); - - let exclude = null; - - // determine if this doc is a result of a query with - // excluded fields - if (utils.isPOJO(fields)) { - exclude = isExclusive(fields); - } - - const hasIncludedChildren = exclude === false && fields ? - $__hasIncludedChildren(fields) : - {}; - - this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false); - - // By default, defaults get applied **before** setting initial values - // Re: gh-6155 - $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, true, { - isNew: this.isNew - }); - - if (obj) { - if (obj instanceof Document) { - this.isNew = obj.isNew; - } - // Skip set hooks - if (this.$__original_set) { - this.$__original_set(obj, undefined, true); - } else { - this.$set(obj, undefined, true); - } - } - - // Function defaults get applied **after** setting initial values so they - // see the full doc rather than an empty one, unless they opt out. - // Re: gh-3781, gh-6155 - if (options.willInit) { - this.once('init', () => { - $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { - isNew: this.isNew - }); - }); - } else { - $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { - isNew: this.isNew - }); - } - - this.$__._id = this._id; - - if (!schema.options.strict && obj) { - const _this = this; - const keys = Object.keys(this._doc); - - keys.forEach(function(key) { - if (!(key in schema.tree)) { - defineKey(key, null, _this); - } - }); - } - - applyQueue(this); -} - -/*! - * Document exposes the NodeJS event emitter API, so you can use - * `on`, `once`, etc. - */ -utils.each( - ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', - 'removeAllListeners', 'addListener'], - function(emitterFn) { - Document.prototype[emitterFn] = function() { - return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); - }; - }); - -Document.prototype.constructor = Document; - -/** - * The documents schema. - * - * @api public - * @property schema - * @memberOf Document - * @instance - */ - -Document.prototype.schema; - -/** - * Boolean flag specifying if the document is new. - * - * @api public - * @property isNew - * @memberOf Document - * @instance - */ - -Document.prototype.isNew; - -/** - * The string version of this documents _id. - * - * ####Note: - * - * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. - * - * new Schema({ name: String }, { id: false }); - * - * @api public - * @see Schema options /docs/guide.html#options - * @property id - * @memberOf Document - * @instance - */ - -Document.prototype.id; - -/** - * Hash containing current validation errors. - * - * @api public - * @property errors - * @memberOf Document - * @instance - */ - -Document.prototype.errors; - -/*! - * ignore - */ - -function $__hasIncludedChildren(fields) { - const hasIncludedChildren = {}; - const keys = Object.keys(fields); - for (let j = 0; j < keys.length; ++j) { - const parts = keys[j].split('.'); - const c = []; - for (let k = 0; k < parts.length; ++k) { - c.push(parts[k]); - hasIncludedChildren[c.join('.')] = 1; - } - } - - return hasIncludedChildren; -} - -/*! - * ignore - */ - -function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) { - const paths = Object.keys(doc.schema.paths); - const plen = paths.length; - - for (let i = 0; i < plen; ++i) { - let def; - let curPath = ''; - const p = paths[i]; - - if (p === '_id' && skipId) { - continue; - } - - const type = doc.schema.paths[p]; - const path = p.split('.'); - const len = path.length; - let included = false; - let doc_ = doc._doc; - - for (let j = 0; j < len; ++j) { - if (doc_ == null) { - break; - } - - const piece = path[j]; - curPath += (!curPath.length ? '' : '.') + piece; - - if (exclude === true) { - if (curPath in fields) { - break; - } - } else if (exclude === false && fields && !included) { - if (curPath in fields) { - included = true; - } else if (!hasIncludedChildren[curPath]) { - break; - } - } - - if (j === len - 1) { - if (doc_[piece] !== void 0) { - break; - } - - if (typeof type.defaultValue === 'function') { - if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) { - break; - } - if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) { - break; - } - } else if (!isBeforeSetters) { - // Non-function defaults should always run **before** setters - continue; - } - - if (pathsToSkip && pathsToSkip[curPath]) { - break; - } - - if (fields && exclude !== null) { - if (exclude === true) { - // apply defaults to all non-excluded fields - if (p in fields) { - continue; - } - - def = type.getDefault(doc, false); - if (typeof def !== 'undefined') { - doc_[piece] = def; - doc.$__.activePaths.default(p); - } - } else if (included) { - // selected field - def = type.getDefault(doc, false); - if (typeof def !== 'undefined') { - doc_[piece] = def; - doc.$__.activePaths.default(p); - } - } - } else { - def = type.getDefault(doc, false); - if (typeof def !== 'undefined') { - doc_[piece] = def; - doc.$__.activePaths.default(p); - } - } - } else { - doc_ = doc_[piece]; - } - } - } -} - -/** - * Builds the default doc structure - * - * @param {Object} obj - * @param {Object} [fields] - * @param {Boolean} [skipId] - * @api private - * @method $__buildDoc - * @memberOf Document - * @instance - */ - -Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) { - const doc = {}; - - const paths = Object.keys(this.schema.paths). - // Don't build up any paths that are underneath a map, we don't know - // what the keys will be - filter(p => !p.includes('$*')); - const plen = paths.length; - let ii = 0; - - for (; ii < plen; ++ii) { - const p = paths[ii]; - - if (p === '_id') { - if (skipId) { - continue; - } - if (obj && '_id' in obj) { - continue; - } - } - - const path = p.split('.'); - const len = path.length; - const last = len - 1; - let curPath = ''; - let doc_ = doc; - let included = false; - - for (let i = 0; i < len; ++i) { - const piece = path[i]; - - curPath += (!curPath.length ? '' : '.') + piece; - - // support excluding intermediary levels - if (exclude === true) { - if (curPath in fields) { - break; - } - } else if (exclude === false && fields && !included) { - if (curPath in fields) { - included = true; - } else if (!hasIncludedChildren[curPath]) { - break; - } - } - - if (i < last) { - doc_ = doc_[piece] || (doc_[piece] = {}); - } - } - } - - this._doc = doc; -}; - -/*! - * Converts to POJO when you use the document for querying - */ - -Document.prototype.toBSON = function() { - return this.toObject(internalToObjectOptions); -}; - -/** - * Initializes the document without setters or marking anything modified. - * - * Called internally after a document is returned from mongodb. Normally, - * you do **not** need to call this function on your own. - * - * This function triggers `init` [middleware](/docs/middleware.html). - * Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous). - * - * @param {Object} doc document returned by mongo - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.init = function(doc, opts, fn) { - if (typeof opts === 'function') { - fn = opts; - opts = null; - } - - this.$__init(doc, opts); - - if (fn) { - fn(null, this); - } - - return this; -}; - -/*! - * ignore - */ - -Document.prototype.$__init = function(doc, opts) { - this.isNew = false; - this.$init = true; - - // handle docs with populated paths - // If doc._id is not null or undefined - if (doc._id !== null && doc._id !== undefined && - opts && opts.populated && opts.populated.length) { - const id = String(doc._id); - for (let i = 0; i < opts.populated.length; ++i) { - const item = opts.populated[i]; - if (item.isVirtual) { - this.populated(item.path, utils.getValue(item.path, doc), item); - } else { - this.populated(item.path, item._docs[id], item); - } - } - } - - init(this, doc, this._doc); - - this.emit('init', this); - this.constructor.emit('init', this); - - this.$__._id = this._id; - - return this; -}; - -/*! - * Init helper. - * - * @param {Object} self document instance - * @param {Object} obj raw mongodb doc - * @param {Object} doc object we are initializing - * @api private - */ - -function init(self, obj, doc, prefix) { - prefix = prefix || ''; - - const keys = Object.keys(obj); - const len = keys.length; - let schema; - let path; - let i; - let index = 0; - - while (index < len) { - _init(index++); - } - - function _init(index) { - i = keys[index]; - path = prefix + i; - schema = self.schema.path(path); - - // Should still work if not a model-level discriminator, but should not be - // necessary. This is *only* to catch the case where we queried using the - // base model and the discriminated model has a projection - if (self.schema.$isRootDiscriminator && !self.isSelected(path)) { - return; - } - - if (!schema && utils.isPOJO(obj[i])) { - // assume nested object - if (!doc[i]) { - doc[i] = {}; - } - init(self, obj[i], doc[i], path + '.'); - } else if (!schema) { - doc[i] = obj[i]; - } else { - if (obj[i] === null) { - doc[i] = null; - } else if (obj[i] !== undefined) { - const intCache = obj[i].$__ || {}; - const wasPopulated = intCache.wasPopulated || null; - if (schema && !wasPopulated) { - try { - doc[i] = schema.cast(obj[i], self, true); - } catch (e) { - self.invalidate(e.path, new ValidatorError({ - path: e.path, - message: e.message, - type: 'cast', - value: e.value - })); - } - } else { - doc[i] = obj[i]; - } - } - // mark as hydrated - if (!self.isModified(path)) { - self.$__.activePaths.init(path); - } - } - } -} - -/** - * Sends an update command with this document `_id` as the query selector. - * - * ####Example: - * - * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); - * - * ####Valid options: - * - * - same as in [Model.update](#model_Model.update) - * - * @see Model.update #model_Model.update - * @param {Object} doc - * @param {Object} options - * @param {Function} callback - * @return {Query} - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.update = function update() { - const args = utils.args(arguments); - args.unshift({_id: this._id}); - const query = this.constructor.update.apply(this.constructor, args); - - if (this.$session() != null) { - if (!('session' in query.options)) { - query.options.session = this.$session(); - } - } - - return query; -}; - -/** - * Sends an updateOne command with this document `_id` as the query selector. - * - * ####Example: - * - * weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback); - * - * ####Valid options: - * - * - same as in [Model.updateOne](#model_Model.updateOne) - * - * @see Model.updateOne #model_Model.updateOne - * @param {Object} doc - * @param {Object} options - * @param {Function} callback - * @return {Query} - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.updateOne = function updateOne(doc, options, callback) { - const query = this.constructor.updateOne({_id: this._id}, doc, options); - query._pre(cb => { - this.constructor._middleware.execPre('updateOne', this, [], cb); - }); - query._post(cb => { - this.constructor._middleware.execPost('updateOne', this, [], {}, cb); - }); - - if (this.$session() != null) { - if (!('session' in query.options)) { - query.options.session = this.$session(); - } - } - - if (callback != null) { - return query.exec(callback); - } - - return query; -}; - -/** - * Sends a replaceOne command with this document `_id` as the query selector. - * - * ####Valid options: - * - * - same as in [Model.replaceOne](#model_Model.replaceOne) - * - * @see Model.replaceOne #model_Model.replaceOne - * @param {Object} doc - * @param {Object} options - * @param {Function} callback - * @return {Query} - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.replaceOne = function replaceOne() { - const args = utils.args(arguments); - args.unshift({ _id: this._id }); - return this.constructor.replaceOne.apply(this.constructor, args); -}; - -/** - * Getter/setter around the session associated with this document. Used to - * automatically set `session` if you `save()` a doc that you got from a - * query with an associated session. - * - * ####Example: - * - * const session = MyModel.startSession(); - * const doc = await MyModel.findOne().session(session); - * doc.$session() === session; // true - * doc.$session(null); - * doc.$session() === null; // true - * - * If this is a top-level document, setting the session propagates to all child - * docs. - * - * @param {ClientSession} [session] overwrite the current session - * @return {ClientSession} - * @method $session - * @api public - * @memberOf Document - */ - -Document.prototype.$session = function $session(session) { - if (arguments.length === 0) { - return this.$__.session; - } - this.$__.session = session; - - if (!this.ownerDocument) { - const subdocs = this.$__getAllSubdocs(); - for (const child of subdocs) { - child.$session(session); - } - } - - return session; -}; - -/** - * Alias for `set()`, used internally to avoid conflicts - * - * @param {String|Object} path path or object of key/vals to set - * @param {Any} val the value to set - * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes - * @param {Object} [options] optionally specify options that modify the behavior of the set - * @method $set - * @name $set - * @memberOf Document - * @instance - * @api public - */ - -Document.prototype.$set = function $set(path, val, type, options) { - if (utils.isPOJO(type)) { - options = type; - type = undefined; - } - - options = options || {}; - const merge = options.merge; - const adhoc = type && type !== true; - const constructing = type === true; - let adhocs; - let keys; - let i = 0; - let pathtype; - let key; - let prefix; - - const strict = 'strict' in options - ? options.strict - : this.$__.strictMode; - - if (adhoc) { - adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); - adhocs[path] = this.schema.interpretAsType(path, type, this.schema.options); - } - - if (typeof path !== 'string') { - // new Document({ key: val }) - if (path === null || path === void 0) { - const _ = path; - path = val; - val = _; - } else { - prefix = val ? val + '.' : ''; - - if (path instanceof Document) { - if (path.$__isNested) { - path = path.toObject(); - } else { - path = path._doc; - } - } - - keys = Object.keys(path); - const len = keys.length; - - if (len === 0 && !this.schema.options.minimize) { - if (val) { - this.$set(val, {}); - } - return this; - } - - while (i < len) { - _handleIndex.call(this, i++); - } - - return this; - } - } - - function _handleIndex(i) { - key = keys[i]; - const pathName = prefix + key; - pathtype = this.schema.pathType(pathName); - - // On initial set, delete any nested keys if we're going to overwrite - // them to ensure we keep the user's key order. - if (type === true && - !prefix && - path[key] != null && - pathtype === 'nested' && - this._doc[key] != null && - Object.keys(this._doc[key]).length === 0) { - delete this._doc[key]; - } - - if (utils.isPOJO(path[key]) && - pathtype !== 'virtual' && - pathtype !== 'real' && - !(this.$__path(pathName) instanceof MixedSchema) && - !(this.schema.paths[pathName] && - this.schema.paths[pathName].options && - this.schema.paths[pathName].options.ref)) { - this.$set(path[key], prefix + key, constructing); - } else if (strict) { - // Don't overwrite defaults with undefined keys (gh-3981) - if (constructing && path[key] === void 0 && - this.get(key) !== void 0) { - return; - } - - if (pathtype === 'adhocOrUndefined') { - pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true }); - } - - if (pathtype === 'real' || pathtype === 'virtual') { - // Check for setting single embedded schema to document (gh-3535) - let p = path[key]; - if (this.schema.paths[pathName] && - this.schema.paths[pathName].$isSingleNested && - path[key] instanceof Document) { - p = p.toObject({ virtuals: false, transform: false }); - } - this.$set(prefix + key, p, constructing); - } else if (pathtype === 'nested' && path[key] instanceof Document) { - this.$set(prefix + key, - path[key].toObject({transform: false}), constructing); - } else if (strict === 'throw') { - if (pathtype === 'nested') { - throw new ObjectExpectedError(key, path[key]); - } else { - throw new StrictModeError(key); - } - } - } else if (path[key] !== void 0) { - this.$set(prefix + key, path[key], constructing); - } - } - - const pathType = this.schema.pathType(path); - if (pathType === 'nested' && val) { - if (utils.isPOJO(val)) { - if (!merge) { - this.setValue(path, null); - cleanModifiedSubpaths(this, path); - } else { - return this.$set(val, path, constructing); - } - - const keys = Object.keys(val); - this.setValue(path, {}); - for (const key of keys) { - this.$set(path + '.' + key, val[key], constructing); - } - this.markModified(path); - cleanModifiedSubpaths(this, path, { skipDocArrays: true }); - return this; - } - this.invalidate(path, new MongooseError.CastError('Object', val, path)); - return this; - } - - let schema; - const parts = path.split('.'); - - if (pathType === 'adhocOrUndefined' && strict) { - // check for roots that are Mixed types - let mixed; - - for (i = 0; i < parts.length; ++i) { - const subpath = parts.slice(0, i + 1).join('.'); - - // If path is underneath a virtual, bypass everything and just set it. - if (i + 1 < parts.length && this.schema.pathType(subpath) === 'virtual') { - mpath.set(path, val, this); - return this; - } - - schema = this.schema.path(subpath); - if (schema == null) { - continue; - } - - if (schema instanceof MixedSchema) { - // allow changes to sub paths of mixed types - mixed = true; - break; - } - } - - if (schema == null) { - // Check for embedded discriminators - schema = getEmbeddedDiscriminatorPath(this, path); - } - - if (!mixed && !schema) { - if (strict === 'throw') { - throw new StrictModeError(path); - } - return this; - } - } else if (pathType === 'virtual') { - schema = this.schema.virtualpath(path); - schema.applySetters(val, this); - return this; - } else { - schema = this.$__path(path); - } - - // gh-4578, if setting a deeply nested path that doesn't exist yet, create it - let cur = this._doc; - let curPath = ''; - for (i = 0; i < parts.length - 1; ++i) { - cur = cur[parts[i]]; - curPath += (curPath.length > 0 ? '.' : '') + parts[i]; - if (!cur) { - this.$set(curPath, {}); - // Hack re: gh-5800. If nested field is not selected, it probably exists - // so `MongoError: cannot use the part (nested of nested.num) to - // traverse the element ({nested: null})` is not likely. If user gets - // that error, its their fault for now. We should reconsider disallowing - // modifying not selected paths for 6.x - if (!this.isSelected(curPath)) { - this.unmarkModified(curPath); - } - cur = this.getValue(curPath); - } - } - - let pathToMark; - - // When using the $set operator the path to the field must already exist. - // Else mongodb throws: "LEFT_SUBFIELD only supports Object" - - if (parts.length <= 1) { - pathToMark = path; - } else { - for (i = 0; i < parts.length; ++i) { - const subpath = parts.slice(0, i + 1).join('.'); - if (this.get(subpath) === null) { - pathToMark = subpath; - break; - } - } - - if (!pathToMark) { - pathToMark = path; - } - } - - // if this doc is being constructed we should not trigger getters - const priorVal = (() => { - if (this.$__.$options.priorDoc != null) { - return this.$__.$options.priorDoc.getValue(path); - } - if (constructing) { - return void 0; - } - return this.getValue(path); - })(); - - if (!schema) { - this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); - return this; - } - - let shouldSet = true; - try { - // If the user is trying to set a ref path to a document with - // the correct model name, treat it as populated - const refMatches = (() => { - if (schema.options == null) { - return false; - } - if (!(val instanceof Document)) { - return false; - } - const model = val.constructor; - - // Check ref - const ref = schema.options.ref; - if (ref != null && (ref === model.modelName || ref === model.baseModelName)) { - return true; - } - - // Check refPath - const refPath = schema.options.refPath; - if (refPath == null) { - return false; - } - const modelName = val.get(refPath); - if (modelName === model.modelName || modelName === model.baseModelName) { - return true; - } - return false; - })(); - - let didPopulate = false; - if (refMatches && val instanceof Document) { - if (this.ownerDocument) { - this.ownerDocument().populated(this.$__fullPath(path), - val._id, {model: val.constructor}); - } else { - this.populated(path, val._id, {model: val.constructor}); - } - didPopulate = true; - } - - let popOpts; - if (schema.options && - Array.isArray(schema.options[this.schema.options.typeKey]) && - schema.options[this.schema.options.typeKey].length && - schema.options[this.schema.options.typeKey][0].ref && - Array.isArray(val) && - val.length > 0 && - val[0] instanceof Document && - val[0].constructor.modelName && - (schema.options[this.schema.options.typeKey][0].ref === val[0].constructor.baseModelName || schema.options[this.schema.options.typeKey][0].ref === val[0].constructor.modelName)) { - if (this.ownerDocument) { - popOpts = { model: val[0].constructor }; - this.ownerDocument().populated(this.$__fullPath(path), - val.map(function(v) { return v._id; }), popOpts); - } else { - popOpts = { model: val[0].constructor }; - this.populated(path, val.map(function(v) { return v._id; }), popOpts); - } - didPopulate = true; - } - - // If this path is underneath a single nested schema, we'll call the setter - // later in `$__set()` because we don't take `_doc` when we iterate through - // a single nested doc. That's to make sure we get the correct context. - // Otherwise we would double-call the setter, see gh-7196. - if (this.schema.singleNestedPaths[path] == null) { - const setterContext = constructing && this.$__.$options.priorDoc ? - this.$__.$options.priorDoc : - this; - val = schema.applySetters(val, setterContext, false, priorVal); - } - - if (!didPopulate && this.$__.populated) { - delete this.$__.populated[path]; - } - - this.$markValid(path); - } catch (e) { - this.invalidate(path, - new MongooseError.CastError(schema.instance, val, path, e)); - shouldSet = false; - } - - if (shouldSet) { - this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); - } - - if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) { - cleanModifiedSubpaths(this, path); - } - - return this; -}; - -/** - * Sets the value of a path, or many paths. - * - * ####Example: - * - * // path, value - * doc.set(path, value) - * - * // object - * doc.set({ - * path : value - * , path2 : { - * path : value - * } - * }) - * - * // on-the-fly cast to number - * doc.set(path, value, Number) - * - * // on-the-fly cast to string - * doc.set(path, value, String) - * - * // changing strict mode behavior - * doc.set(path, value, { strict: false }); - * - * @param {String|Object} path path or object of key/vals to set - * @param {Any} val the value to set - * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes - * @param {Object} [options] optionally specify options that modify the behavior of the set - * @api public - * @method set - * @memberOf Document - * @instance - */ - -Document.prototype.set = Document.prototype.$set; - -/** - * Determine if we should mark this change as modified. - * - * @return {Boolean} - * @api private - * @method $__shouldModify - * @memberOf Document - * @instance - */ - -Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) { - if (this.isNew) { - return true; - } - - // Re: the note about gh-7196, `val` is the raw value without casting or - // setters if the full path is under a single nested subdoc because we don't - // want to double run setters. So don't set it as modified. See gh-7264. - if (this.schema.singleNestedPaths[path] != null) { - return false; - } - - if (val === void 0 && !this.isSelected(path)) { - // when a path is not selected in a query, its initial - // value will be undefined. - return true; - } - - if (val === void 0 && path in this.$__.activePaths.states.default) { - // we're just unsetting the default value which was never saved - return false; - } - - // gh-3992: if setting a populated field to a doc, don't mark modified - // if they have the same _id - if (this.populated(path) && - val instanceof Document && - deepEqual(val._id, priorVal)) { - return false; - } - - if (!deepEqual(val, priorVal || this.get(path))) { - return true; - } - - if (!constructing && - val !== null && - val !== undefined && - path in this.$__.activePaths.states.default && - deepEqual(val, schema.getDefault(this, constructing))) { - // a path with a default was $unset on the server - // and the user is setting it to the same value again - return true; - } - return false; -}; - -/** - * Handles the actual setting of the value and marking the path modified if appropriate. - * - * @api private - * @method $__set - * @memberOf Document - * @instance - */ - -Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) { - Embedded = Embedded || require('./types/embedded'); - - const shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts, - schema, val, priorVal); - const _this = this; - - if (shouldModify) { - this.markModified(pathToMark); - - // handle directly setting arrays (gh-1126) - MongooseArray || (MongooseArray = require('./types/array')); - if (val && val.isMongooseArray) { - val._registerAtomic('$set', val); - - // Update embedded document parent references (gh-5189) - if (val.isMongooseDocumentArray) { - val.forEach(function(item) { - item && item.__parentArray && (item.__parentArray = val); - }); - } - - // Small hack for gh-1638: if we're overwriting the entire array, ignore - // paths that were modified before the array overwrite - this.$__.activePaths.forEach(function(modifiedPath) { - if (modifiedPath.indexOf(path + '.') === 0) { - _this.$__.activePaths.ignore(modifiedPath); - } - }); - } - } - - let obj = this._doc; - let i = 0; - const l = parts.length; - let cur = ''; - - for (; i < l; i++) { - const next = i + 1; - const last = next === l; - cur += (cur ? '.' + parts[i] : parts[i]); - if (specialProperties.has(parts[i])) { - return; - } - - if (last) { - if (obj instanceof Map) { - obj.set(parts[i], val); - } else { - obj[parts[i]] = val; - } - } else { - if (utils.isPOJO(obj[parts[i]])) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { - obj = obj[parts[i]]; - } else { - obj[parts[i]] = obj[parts[i]] || {}; - obj = obj[parts[i]]; - } - } - } -}; - -/** - * Gets a raw value from a path (no getters) - * - * @param {String} path - * @api private - */ - -Document.prototype.getValue = function(path) { - return utils.getValue(path, this._doc); -}; - -/** - * Sets a raw value for a path (no casting, setters, transformations) - * - * @param {String} path - * @param {Object} value - * @api private - */ - -Document.prototype.setValue = function(path, val) { - utils.setValue(path, val, this._doc); - return this; -}; - -/** - * Returns the value of a path. - * - * ####Example - * - * // path - * doc.get('age') // 47 - * - * // dynamic casting to a string - * doc.get('age', String) // "47" - * - * @param {String} path - * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes - * @api public - */ - -Document.prototype.get = function(path, type, options) { - let adhoc; - options = options || {}; - if (type) { - adhoc = this.schema.interpretAsType(path, type, this.schema.options); - } - - const schema = this.$__path(path) || this.schema.virtualpath(path); - const pieces = path.split('.'); - let obj = this._doc; - - if (schema instanceof VirtualType) { - if (schema.getters.length === 0) { - return void 0; - } - return schema.applyGetters(null, this); - } - - for (let i = 0, l = pieces.length; i < l; i++) { - if (obj && obj._doc) { - obj = obj._doc; - } - - if (obj == null) { - obj = void 0; - } else if (obj instanceof Map) { - obj = obj.get(pieces[i]); - } else if (i === l - 1) { - obj = utils.getValue(pieces[i], obj); - } else { - obj = obj[pieces[i]]; - } - } - - if (adhoc) { - obj = adhoc.cast(obj); - } - - if (schema != null) { - obj = schema.applyGetters(obj, this); - } else if (this.schema.nested[path] && options.virtuals) { - // Might need to apply virtuals if this is a nested path - return applyGetters(this, utils.clone(obj), 'virtuals', { path: path }); - } - - return obj; -}; - -/*! - * ignore - */ - -Document.prototype[getSymbol] = Document.prototype.get; - -/** - * Returns the schematype for the given `path`. - * - * @param {String} path - * @api private - * @method $__path - * @memberOf Document - * @instance - */ - -Document.prototype.$__path = function(path) { - const adhocs = this.$__.adhocPaths; - const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null; - - if (adhocType) { - return adhocType; - } - return this.schema.path(path); -}; - -/** - * Marks the path as having pending changes to write to the db. - * - * _Very helpful when using [Mixed](./schematypes.html#mixed) types._ - * - * ####Example: - * - * doc.mixed.type = 'changed'; - * doc.markModified('mixed.type'); - * doc.save() // changes to mixed.type are now persisted - * - * @param {String} path the path to mark modified - * @param {Document} [scope] the scope to run validators with - * @api public - */ - -Document.prototype.markModified = function(path, scope) { - this.$__.activePaths.modify(path); - if (scope != null && !this.ownerDocument) { - this.$__.pathsToScopes[path] = scope; - } -}; - -/** - * Clears the modified state on the specified path. - * - * ####Example: - * - * doc.foo = 'bar'; - * doc.unmarkModified('foo'); - * doc.save(); // changes to foo will not be persisted - * - * @param {String} path the path to unmark modified - * @api public - */ - -Document.prototype.unmarkModified = function(path) { - this.$__.activePaths.init(path); - delete this.$__.pathsToScopes[path]; -}; - -/** - * Don't run validation on this path or persist changes to this path. - * - * ####Example: - * - * doc.foo = null; - * doc.$ignore('foo'); - * doc.save(); // changes to foo will not be persisted and validators won't be run - * - * @memberOf Document - * @instance - * @method $ignore - * @param {String} path the path to ignore - * @api public - */ - -Document.prototype.$ignore = function(path) { - this.$__.activePaths.ignore(path); -}; - -/** - * Returns the list of paths that have been modified. - * - * @param {Object} [options] - * @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`. - * @return {Array} - * @api public - */ - -Document.prototype.modifiedPaths = function(options) { - options = options || {}; - const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); - const _this = this; - return directModifiedPaths.reduce(function(list, path) { - const parts = path.split('.'); - list = list.concat(parts.reduce(function(chains, part, i) { - return chains.concat(parts.slice(0, i).concat(part).join('.')); - }, []).filter(function(chain) { - return (list.indexOf(chain) === -1); - })); - - if (!options.includeChildren) { - return list; - } - - let cur = _this.get(path); - if (cur != null && typeof cur === 'object') { - if (cur._doc) { - cur = cur._doc; - } - if (Array.isArray(cur)) { - const len = cur.length; - for (let i = 0; i < len; ++i) { - if (list.indexOf(path + '.' + i) === -1) { - list.push(path + '.' + i); - if (cur[i] != null && cur[i].$__) { - const modified = cur[i].modifiedPaths(); - for (const childPath of modified) { - list.push(path + '.' + i + '.' + childPath); - } - } - } - } - } else { - Object.keys(cur). - filter(function(key) { - return list.indexOf(path + '.' + key) === -1; - }). - forEach(function(key) { - list.push(path + '.' + key); - }); - } - } - - return list; - }, []); -}; - -/** - * Returns true if this document was modified, else false. - * - * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. - * - * ####Example - * - * doc.set('documents.0.title', 'changed'); - * doc.isModified() // true - * doc.isModified('documents') // true - * doc.isModified('documents.0.title') // true - * doc.isModified('documents otherProp') // true - * doc.isDirectModified('documents') // false - * - * @param {String} [path] optional - * @return {Boolean} - * @api public - */ - -Document.prototype.isModified = function(paths, modifiedPaths) { - if (paths) { - if (!Array.isArray(paths)) { - paths = paths.split(' '); - } - const modified = modifiedPaths || this.modifiedPaths(); - const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); - const isModifiedChild = paths.some(function(path) { - return !!~modified.indexOf(path); - }); - return isModifiedChild || paths.some(function(path) { - return directModifiedPaths.some(function(mod) { - return mod === path || path.indexOf(mod + '.') === 0; - }); - }); - } - return this.$__.activePaths.some('modify'); -}; - -/** - * Checks if a path is set to its default. - * - * ####Example - * - * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} }); - * var m = new MyModel(); - * m.$isDefault('name'); // true - * - * @memberOf Document - * @instance - * @method $isDefault - * @param {String} [path] - * @return {Boolean} - * @api public - */ - -Document.prototype.$isDefault = function(path) { - return (path in this.$__.activePaths.states.default); -}; - -/** - * Getter/setter, determines whether the document was removed or not. - * - * ####Example: - * product.remove(function (err, product) { - * product.$isDeleted(); // true - * product.remove(); // no-op, doesn't send anything to the db - * - * product.$isDeleted(false); - * product.$isDeleted(); // false - * product.remove(); // will execute a remove against the db - * }) - * - * @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted - * @return {Boolean} whether mongoose thinks this doc is deleted. - * @method $isDeleted - * @memberOf Document - * @instance - * @api public - */ - -Document.prototype.$isDeleted = function(val) { - if (arguments.length === 0) { - return !!this.$__.isDeleted; - } - - this.$__.isDeleted = !!val; - return this; -}; - -/** - * Returns true if `path` was directly set and modified, else false. - * - * ####Example - * - * doc.set('documents.0.title', 'changed'); - * doc.isDirectModified('documents.0.title') // true - * doc.isDirectModified('documents') // false - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isDirectModified = function(path) { - return (path in this.$__.activePaths.states.modify); -}; - -/** - * Checks if `path` was initialized. - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isInit = function(path) { - return (path in this.$__.activePaths.states.init); -}; - -/** - * Checks if `path` was selected in the source query which initialized this document. - * - * ####Example - * - * Thing.findOne().select('name').exec(function (err, doc) { - * doc.isSelected('name') // true - * doc.isSelected('age') // false - * }) - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isSelected = function isSelected(path) { - if (this.$__.selected) { - if (path === '_id') { - return this.$__.selected._id !== 0; - } - - const paths = Object.keys(this.$__.selected); - let i = paths.length; - let inclusive = null; - let cur; - - if (i === 1 && paths[0] === '_id') { - // only _id was selected. - return this.$__.selected._id === 0; - } - - while (i--) { - cur = paths[i]; - if (cur === '_id') { - continue; - } - if (!isDefiningProjection(this.$__.selected[cur])) { - continue; - } - inclusive = !!this.$__.selected[cur]; - break; - } - - if (inclusive === null) { - return true; - } - - if (path in this.$__.selected) { - return inclusive; - } - - i = paths.length; - const pathDot = path + '.'; - - while (i--) { - cur = paths[i]; - if (cur === '_id') { - continue; - } - - if (cur.indexOf(pathDot) === 0) { - return inclusive || cur !== pathDot; - } - - if (pathDot.indexOf(cur + '.') === 0) { - return inclusive; - } - } - - return !inclusive; - } - - return true; -}; - -/** - * Checks if `path` was explicitly selected. If no projection, always returns - * true. - * - * ####Example - * - * Thing.findOne().select('nested.name').exec(function (err, doc) { - * doc.isDirectSelected('nested.name') // true - * doc.isDirectSelected('nested.otherName') // false - * doc.isDirectSelected('nested') // false - * }) - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isDirectSelected = function isDirectSelected(path) { - if (this.$__.selected) { - if (path === '_id') { - return this.$__.selected._id !== 0; - } - - const paths = Object.keys(this.$__.selected); - let i = paths.length; - let inclusive = null; - let cur; - - if (i === 1 && paths[0] === '_id') { - // only _id was selected. - return this.$__.selected._id === 0; - } - - while (i--) { - cur = paths[i]; - if (cur === '_id') { - continue; - } - if (!isDefiningProjection(this.$__.selected[cur])) { - continue; - } - inclusive = !!this.$__.selected[cur]; - break; - } - - if (inclusive === null) { - return true; - } - - if (path in this.$__.selected) { - return inclusive; - } - - return !inclusive; - } - - return true; -}; - -/** - * Executes registered validation rules for this document. - * - * ####Note: - * - * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. - * - * ####Example: - * - * doc.validate(function (err) { - * if (err) handleError(err); - * else // validation passed - * }); - * - * @param {Object} optional options internal options - * @param {Function} callback optional callback called after validation completes, passing an error if one occurred - * @return {Promise} Promise - * @api public - */ - -Document.prototype.validate = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = null; - } - - return utils.promiseOrCallback(callback, cb => this.$__validate(function(error) { - cb(error); - }), this.constructor.events); -}; - -/*! - * ignore - */ - -function _evaluateRequiredFunctions(doc) { - Object.keys(doc.$__.activePaths.states.require).forEach(path => { - const p = doc.schema.path(path); - - if (p != null && typeof p.originalRequiredValue === 'function') { - doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc); - } - }); -} - -/*! - * ignore - */ - -function _getPathsToValidate(doc) { - let i; - let len; - const skipSchemaValidators = {}; - - _evaluateRequiredFunctions(doc); - - // only validate required fields when necessary - let paths = Object.keys(doc.$__.activePaths.states.require).filter(function(path) { - if (!doc.isSelected(path) && !doc.isModified(path)) { - return false; - } - if (path in doc.$__.cachedRequired) { - return doc.$__.cachedRequired[path]; - } - return true; - }); - - paths = paths.concat(Object.keys(doc.$__.activePaths.states.init)); - paths = paths.concat(Object.keys(doc.$__.activePaths.states.modify)); - paths = paths.concat(Object.keys(doc.$__.activePaths.states.default)); - - if (!doc.ownerDocument) { - const subdocs = doc.$__getAllSubdocs(); - let subdoc; - len = subdocs.length; - const modifiedPaths = doc.modifiedPaths(); - for (i = 0; i < len; ++i) { - subdoc = subdocs[i]; - if (doc.isModified(subdoc.$basePath, modifiedPaths) && - !doc.isDirectModified(subdoc.$basePath) && - !doc.$isDefault(subdoc.$basePath)) { - // Remove child paths for now, because we'll be validating the whole - // subdoc - paths = paths.filter(function(p) { - return p != null && p.indexOf(subdoc.$basePath + '.') !== 0; - }); - paths.push(subdoc.$basePath); - skipSchemaValidators[subdoc.$basePath] = true; - } - } - } - - // gh-661: if a whole array is modified, make sure to run validation on all - // the children as well - len = paths.length; - for (i = 0; i < len; ++i) { - const path = paths[i]; - - const _pathType = doc.schema.path(path); - if (!_pathType || - !_pathType.$isMongooseArray || - // To avoid potential performance issues, skip doc arrays whose children - // are not required. `getPositionalPathType()` may be slow, so avoid - // it unless we have a case of #6364 - (_pathType.$isMongooseDocumentArray && !get(_pathType, 'schemaOptions.required'))) { - continue; - } - - const val = doc.getValue(path); - if (val) { - const numElements = val.length; - for (let j = 0; j < numElements; ++j) { - paths.push(path + '.' + j); - } - } - } - - const flattenOptions = { skipArrays: true }; - len = paths.length; - for (i = 0; i < len; ++i) { - const pathToCheck = paths[i]; - if (doc.schema.nested[pathToCheck]) { - let _v = doc.getValue(pathToCheck); - if (isMongooseObject(_v)) { - _v = _v.toObject({ transform: false }); - } - const flat = flatten(_v, '', flattenOptions); - const _subpaths = Object.keys(flat).map(function(p) { - return pathToCheck + '.' + p; - }); - paths = paths.concat(_subpaths); - } - } - - len = paths.length; - for (i = 0; i < len; ++i) { - const path = paths[i]; - const _pathType = doc.schema.path(path); - if (!_pathType || !_pathType.$isSchemaMap) { - continue; - } - - const val = doc.getValue(path); - if (val == null) { - continue; - } - for (const key of val.keys()) { - paths.push(path + '.' + key); - } - } - - return [paths, skipSchemaValidators]; -} - -/*! - * ignore - */ - -Document.prototype.$__validate = function(callback) { - const _this = this; - const _complete = () => { - const err = this.$__.validationError; - this.$__.validationError = undefined; - this.$__.cachedRequired = {}; - this.emit('validate', _this); - this.constructor.emit('validate', _this); - if (err) { - for (const key in err.errors) { - // Make sure cast errors persist - if (!this[documentArrayParent] && err.errors[key] instanceof MongooseError.CastError) { - this.invalidate(key, err.errors[key]); - } - } - - return err; - } - }; - - // only validate required fields when necessary - const pathDetails = _getPathsToValidate(this); - const paths = pathDetails[0]; - const skipSchemaValidators = pathDetails[1]; - - if (paths.length === 0) { - return process.nextTick(function() { - const error = _complete(); - if (error) { - return _this.schema.s.hooks.execPost('validate:error', _this, [ _this], { error: error }, function(error) { - callback(error); - }); - } - callback(null, _this); - }); - } - - const validated = {}; - let total = 0; - - const complete = function() { - const error = _complete(); - if (error) { - return _this.schema.s.hooks.execPost('validate:error', _this, [ _this], { error: error }, function(error) { - callback(error); - }); - } - callback(null, _this); - }; - - const validatePath = function(path) { - if (path == null || validated[path]) { - return; - } - - validated[path] = true; - total++; - - process.nextTick(function() { - const p = _this.schema.path(path); - - if (!p) { - return --total || complete(); - } - - // If user marked as invalid or there was a cast error, don't validate - if (!_this.$isValid(path)) { - --total || complete(); - return; - } - - const val = _this.getValue(path); - const scope = path in _this.$__.pathsToScopes ? - _this.$__.pathsToScopes[path] : - _this; - - p.doValidate(val, function(err) { - if (err && (!p.$isMongooseDocumentArray || err.$isArrayValidatorError)) { - if (p.$isSingleNested && - err.name === 'ValidationError' && - p.schema.options.storeSubdocValidationError === false) { - return --total || complete(); - } - _this.invalidate(path, err, undefined, true); - } - --total || complete(); - }, scope, { skipSchemaValidators: skipSchemaValidators[path] }); - }); - }; - - const numPaths = paths.length; - for (let i = 0; i < numPaths; ++i) { - validatePath(paths[i]); - } -}; - -/** - * Executes registered validation rules (skipping asynchronous validators) for this document. - * - * ####Note: - * - * This method is useful if you need synchronous validation. - * - * ####Example: - * - * var err = doc.validateSync(); - * if ( err ){ - * handleError( err ); - * } else { - * // validation passed - * } - * - * @param {Array|string} pathsToValidate only validate the given paths - * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error. - * @api public - */ - -Document.prototype.validateSync = function(pathsToValidate) { - const _this = this; - - if (typeof pathsToValidate === 'string') { - pathsToValidate = pathsToValidate.split(' '); - } - - // only validate required fields when necessary - const pathDetails = _getPathsToValidate(this); - let paths = pathDetails[0]; - const skipSchemaValidators = pathDetails[1]; - - if (pathsToValidate && pathsToValidate.length) { - const tmp = []; - for (let i = 0; i < paths.length; ++i) { - if (pathsToValidate.indexOf(paths[i]) !== -1) { - tmp.push(paths[i]); - } - } - paths = tmp; - } - - const validating = {}; - - paths.forEach(function(path) { - if (validating[path]) { - return; - } - - validating[path] = true; - - const p = _this.schema.path(path); - if (!p) { - return; - } - if (!_this.$isValid(path)) { - return; - } - - const val = _this.getValue(path); - const err = p.doValidateSync(val, _this, { - skipSchemaValidators: skipSchemaValidators[path] - }); - if (err && (!p.$isMongooseDocumentArray || err.$isArrayValidatorError)) { - if (p.$isSingleNested && - err.name === 'ValidationError' && - p.schema.options.storeSubdocValidationError === false) { - return; - } - _this.invalidate(path, err, undefined, true); - } - }); - - const err = _this.$__.validationError; - _this.$__.validationError = undefined; - _this.emit('validate', _this); - _this.constructor.emit('validate', _this); - - if (err) { - for (const key in err.errors) { - // Make sure cast errors persist - if (err.errors[key] instanceof MongooseError.CastError) { - _this.invalidate(key, err.errors[key]); - } - } - } - - return err; -}; - -/** - * Marks a path as invalid, causing validation to fail. - * - * The `errorMsg` argument will become the message of the `ValidationError`. - * - * The `value` argument (if passed) will be available through the `ValidationError.value` property. - * - * doc.invalidate('size', 'must be less than 20', 14); - - * doc.validate(function (err) { - * console.log(err) - * // prints - * { message: 'Validation failed', - * name: 'ValidationError', - * errors: - * { size: - * { message: 'must be less than 20', - * name: 'ValidatorError', - * path: 'size', - * type: 'user defined', - * value: 14 } } } - * }) - * - * @param {String} path the field to invalidate - * @param {String|Error} errorMsg the error which states the reason `path` was invalid - * @param {Object|String|Number|any} value optional invalid value - * @param {String} [kind] optional `kind` property for the error - * @return {ValidationError} the current ValidationError, with all currently invalidated paths - * @api public - */ - -Document.prototype.invalidate = function(path, err, val, kind) { - if (!this.$__.validationError) { - this.$__.validationError = new ValidationError(this); - } - - if (this.$__.validationError.errors[path]) { - return; - } - - if (!err || typeof err === 'string') { - err = new ValidatorError({ - path: path, - message: err, - type: kind || 'user defined', - value: val - }); - } - - if (this.$__.validationError === err) { - return this.$__.validationError; - } - - this.$__.validationError.addError(path, err); - return this.$__.validationError; -}; - -/** - * Marks a path as valid, removing existing validation errors. - * - * @param {String} path the field to mark as valid - * @api public - * @memberOf Document - * @instance - * @method $markValid - */ - -Document.prototype.$markValid = function(path) { - if (!this.$__.validationError || !this.$__.validationError.errors[path]) { - return; - } - - delete this.$__.validationError.errors[path]; - if (Object.keys(this.$__.validationError.errors).length === 0) { - this.$__.validationError = null; - } -}; - -/** - * Saves this document. - * - * ####Example: - * - * product.sold = Date.now(); - * product.save(function (err, product) { - * if (err) .. - * }) - * - * The callback will receive two parameters - * - * 1. `err` if an error occurred - * 2. `product` which is the saved `product` - * - * As an extra measure of flow control, save will return a Promise. - * ####Example: - * product.save().then(function(product) { - * ... - * }); - * - * @param {Object} [options] options optional options - * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe) - * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. - * @param {Function} [fn] optional callback - * @method save - * @memberOf Document - * @instance - * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. - * @api public - * @see middleware http://mongoosejs.com/docs/middleware.html - */ - -/** - * Checks if a path is invalid - * - * @param {String} path the field to check - * @method $isValid - * @memberOf Document - * @instance - * @api private - */ - -Document.prototype.$isValid = function(path) { - return !this.$__.validationError || !this.$__.validationError.errors[path]; -}; - -/** - * Resets the internal modified state of this document. - * - * @api private - * @return {Document} - * @method $__reset - * @memberOf Document - * @instance - */ - -Document.prototype.$__reset = function reset() { - let _this = this; - DocumentArray || (DocumentArray = require('./types/documentarray')); - - this.$__.activePaths - .map('init', 'modify', function(i) { - return _this.getValue(i); - }) - .filter(function(val) { - return val && val instanceof Array && val.isMongooseDocumentArray && val.length; - }) - .forEach(function(array) { - let i = array.length; - while (i--) { - const doc = array[i]; - if (!doc) { - continue; - } - doc.$__reset(); - } - - _this.$__.activePaths.init(array._path); - - array._atomics = {}; - }); - - this.$__.activePaths. - map('init', 'modify', function(i) { - return _this.getValue(i); - }). - filter(function(val) { - return val && val.$isSingleNested; - }). - forEach(function(doc) { - doc.$__reset(); - _this.$__.activePaths.init(doc.$basePath); - }); - - // clear atomics - this.$__dirty().forEach(function(dirt) { - const type = dirt.value; - - if (type && type._atomics) { - type._atomics = {}; - } - }); - - // Clear 'dirty' cache - this.$__.activePaths.clear('modify'); - this.$__.activePaths.clear('default'); - this.$__.validationError = undefined; - this.errors = undefined; - _this = this; - this.schema.requiredPaths().forEach(function(path) { - _this.$__.activePaths.require(path); - }); - - return this; -}; - -/** - * Returns this documents dirty paths / vals. - * - * @api private - * @method $__dirty - * @memberOf Document - * @instance - */ - -Document.prototype.$__dirty = function() { - const _this = this; - - let all = this.$__.activePaths.map('modify', function(path) { - return { - path: path, - value: _this.getValue(path), - schema: _this.$__path(path) - }; - }); - - // gh-2558: if we had to set a default and the value is not undefined, - // we have to save as well - all = all.concat(this.$__.activePaths.map('default', function(path) { - if (path === '_id' || _this.getValue(path) == null) { - return; - } - return { - path: path, - value: _this.getValue(path), - schema: _this.$__path(path) - }; - })); - - // Sort dirty paths in a flat hierarchy. - all.sort(function(a, b) { - return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0)); - }); - - // Ignore "foo.a" if "foo" is dirty already. - const minimal = []; - let lastPath; - let top; - - all.forEach(function(item) { - if (!item) { - return; - } - if (item.path.indexOf(lastPath) !== 0) { - lastPath = item.path + '.'; - minimal.push(item); - top = item; - } else { - // special case for top level MongooseArrays - if (top.value && top.value._atomics && top.value.hasAtomics()) { - // the `top` array itself and a sub path of `top` are being modified. - // the only way to honor all of both modifications is through a $set - // of entire array. - top.value._atomics = {}; - top.value._atomics.$set = top.value; - } - } - }); - - top = lastPath = null; - return minimal; -}; - -/** - * Assigns/compiles `schema` into this documents prototype. - * - * @param {Schema} schema - * @api private - * @method $__setSchema - * @memberOf Document - * @instance - */ - -Document.prototype.$__setSchema = function(schema) { - schema.plugin(idGetter, { deduplicate: true }); - compile(schema.tree, this, undefined, schema.options); - - // Apply default getters if virtual doesn't have any (gh-6262) - for (const key of Object.keys(schema.virtuals)) { - schema.virtuals[key]._applyDefaultGetters(); - } - - this.schema = schema; -}; - - -/** - * Get active path that were changed and are arrays - * - * @api private - * @method $__getArrayPathsToValidate - * @memberOf Document - * @instance - */ - -Document.prototype.$__getArrayPathsToValidate = function() { - DocumentArray || (DocumentArray = require('./types/documentarray')); - - // validate all document arrays. - return this.$__.activePaths - .map('init', 'modify', function(i) { - return this.getValue(i); - }.bind(this)) - .filter(function(val) { - return val && val instanceof Array && val.isMongooseDocumentArray && val.length; - }).reduce(function(seed, array) { - return seed.concat(array); - }, []) - .filter(function(doc) { - return doc; - }); -}; - - -/** - * Get all subdocs (by bfs) - * - * @api private - * @method $__getAllSubdocs - * @memberOf Document - * @instance - */ - -Document.prototype.$__getAllSubdocs = function() { - DocumentArray || (DocumentArray = require('./types/documentarray')); - Embedded = Embedded || require('./types/embedded'); - - function docReducer(doc, seed, path) { - const val = path ? doc[path] : doc; - if (val instanceof Embedded) { - seed.push(val); - } - else if (val instanceof Map) { - seed = Array.from(val.keys()).reduce(function(seed, path) { - return docReducer(val.get(path), seed, null); - }, seed); - } - else if (val && val.$isSingleNested) { - seed = Object.keys(val._doc).reduce(function(seed, path) { - return docReducer(val._doc, seed, path); - }, seed); - seed.push(val); - } - else if (val && val.isMongooseDocumentArray) { - val.forEach(function _docReduce(doc) { - if (!doc || !doc._doc) { - return; - } - if (doc instanceof Embedded) { - seed.push(doc); - } - seed = Object.keys(doc._doc).reduce(function(seed, path) { - return docReducer(doc._doc, seed, path); - }, seed); - }); - } else if (val instanceof Document && val.$__isNested) { - if (val) { - seed = Object.keys(val).reduce(function(seed, path) { - return docReducer(val, seed, path); - }, seed); - } - } - return seed; - } - - const _this = this; - const subDocs = Object.keys(this._doc).reduce(function(seed, path) { - return docReducer(_this, seed, path); - }, []); - - return subDocs; -}; - -/*! - * Runs queued functions - */ - -function applyQueue(doc) { - const q = doc.schema && doc.schema.callQueue; - if (!q.length) { - return; - } - let pair; - - for (let i = 0; i < q.length; ++i) { - pair = q[i]; - if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { - doc[pair[0]].apply(doc, pair[1]); - } - } -} - -/*! - * ignore - */ - -Document.prototype.$__handleReject = function handleReject(err) { - // emit on the Model if listening - if (this.listeners('error').length) { - this.emit('error', err); - } else if (this.constructor.listeners && this.constructor.listeners('error').length) { - this.constructor.emit('error', err); - } else if (this.listeners && this.listeners('error').length) { - this.emit('error', err); - } -}; - -/** - * Internal helper for toObject() and toJSON() that doesn't manipulate options - * - * @api private - * @method $toObject - * @memberOf Document - * @instance - */ - -Document.prototype.$toObject = function(options, json) { - let defaultOptions = { - transform: true, - flattenDecimals: true - }; - - const path = json ? 'toJSON' : 'toObject'; - const baseOptions = get(this, 'constructor.base.options.' + path, {}); - const schemaOptions = get(this, 'schema.options', {}); - // merge base default options with Schema's set default options if available. - // `clone` is necessary here because `utils.options` directly modifies the second input. - defaultOptions = utils.options(defaultOptions, clone(baseOptions)); - defaultOptions = utils.options(defaultOptions, clone(schemaOptions[path] || {})); - - // If options do not exist or is not an object, set it to empty object - options = utils.isPOJO(options) ? clone(options) : {}; - - if (!('flattenMaps' in options)) { - options.flattenMaps = defaultOptions.flattenMaps; - } - - let _minimize; - if (options.minimize != null) { - _minimize = options.minimize; - } else if (defaultOptions.minimize != null) { - _minimize = defaultOptions.minimize; - } else { - _minimize = schemaOptions.minimize; - } - - // The original options that will be passed to `clone()`. Important because - // `clone()` will recursively call `$toObject()` on embedded docs, so we - // need the original options the user passed in, plus `_isNested` and - // `_parentOptions` for checking whether we need to depopulate. - const cloneOptions = Object.assign(utils.clone(options), { - _isNested: true, - json: json, - minimize: _minimize - }); - - const depopulate = options.depopulate || - get(options, '_parentOptions.depopulate', false); - // _isNested will only be true if this is not the top level document, we - // should never depopulate - if (depopulate && options._isNested && this.$__.wasPopulated) { - // populated paths that we set to a document - return clone(this._id, cloneOptions); - } - - // merge default options with input options. - options = utils.options(defaultOptions, options); - options._isNested = true; - options.json = json; - options.minimize = _minimize; - - cloneOptions._parentOptions = options; - - // remember the root transform function - // to save it from being overwritten by sub-transform functions - const originalTransform = options.transform; - - let ret = clone(this._doc, cloneOptions) || {}; - - if (options.getters) { - applyGetters(this, ret, 'paths', cloneOptions); - // applyGetters for paths will add nested empty objects; - // if minimize is set, we need to remove them. - if (options.minimize) { - ret = minimize(ret) || {}; - } - } - - if (options.virtuals || options.getters && options.virtuals !== false) { - applyGetters(this, ret, 'virtuals', cloneOptions); - } - - if (options.versionKey === false && this.schema.options.versionKey) { - delete ret[this.schema.options.versionKey]; - } - - let transform = options.transform; - - // In the case where a subdocument has its own transform function, we need to - // check and see if the parent has a transform (options.transform) and if the - // child schema has a transform (this.schema.options.toObject) In this case, - // we need to adjust options.transform to be the child schema's transform and - // not the parent schema's - if (transform === true || (schemaOptions.toObject && transform)) { - const opts = options.json ? schemaOptions.toJSON : schemaOptions.toObject; - - if (opts) { - transform = (typeof options.transform === 'function' ? options.transform : opts.transform); - } - } else { - options.transform = originalTransform; - } - - if (typeof transform === 'function') { - const xformed = transform(this, ret, options); - if (typeof xformed !== 'undefined') { - ret = xformed; - } - } - - return ret; -}; - -/** - * Converts this document into a plain javascript object, ready for storage in MongoDB. - * - * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. - * - * ####Options: - * - * - `getters` apply all getters (path and virtual getters), defaults to false - * - `virtuals` apply virtual getters (can override `getters` option), defaults to false - * - `minimize` remove empty objects (defaults to true) - * - `transform` a transform function to apply to the resulting document before returning - * - `depopulate` depopulate any populated paths, replacing them with their original refs (defaults to false) - * - `versionKey` whether to include the version key (defaults to true) - * - * ####Getters/Virtuals - * - * Example of only applying path getters - * - * doc.toObject({ getters: true, virtuals: false }) - * - * Example of only applying virtual getters - * - * doc.toObject({ virtuals: true }) - * - * Example of applying both path and virtual getters - * - * doc.toObject({ getters: true }) - * - * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. - * - * schema.set('toObject', { virtuals: true }) - * - * ####Transform - * - * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. - * - * Transform functions receive three arguments - * - * function (doc, ret, options) {} - * - * - `doc` The mongoose document which is being converted - * - `ret` The plain object representation which has been converted - * - `options` The options in use (either schema options or the options passed inline) - * - * ####Example - * - * // specify the transform schema option - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.transform = function (doc, ret, options) { - * // remove the _id of every document before returning the result - * delete ret._id; - * return ret; - * } - * - * // without the transformation in the schema - * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } - * - * // with the transformation - * doc.toObject(); // { name: 'Wreck-it Ralph' } - * - * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: - * - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.transform = function (doc, ret, options) { - * return { movie: ret.name } - * } - * - * // without the transformation in the schema - * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } - * - * // with the transformation - * doc.toObject(); // { movie: 'Wreck-it Ralph' } - * - * _Note: if a transform function returns `undefined`, the return value will be ignored._ - * - * Transformations may also be applied inline, overridding any transform set in the options: - * - * function xform (doc, ret, options) { - * return { inline: ret.name, custom: true } - * } - * - * // pass the transform as an inline option - * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } - * - * If you want to skip transformations, use `transform: false`: - * - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.hide = '_id'; - * schema.options.toObject.transform = function (doc, ret, options) { - * if (options.hide) { - * options.hide.split(' ').forEach(function (prop) { - * delete ret[prop]; - * }); - * } - * return ret; - * } - * - * var doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); - * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } - * doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } - * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } - * - * Transforms are applied _only to the document and are not applied to sub-documents_. - * - * Transforms, like all of these options, are also available for `toJSON`. - * - * See [schema options](/docs/guide.html#toObject) for some more details. - * - * _During save, no custom options are applied to the document before being sent to the database._ - * - * @param {Object} [options] - * @param {Boolean} [options.getters=false] if true, apply all getters, including virtuals - * @param {Boolean} [options.virtuals=false] if true, apply virtuals. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals - * @param {Boolean} [options.minimize=true] if true, omit any empty objects from the output - * @param {Function|null} [options.transform=null] if set, mongoose will call this function to allow you to transform the returned object - * @param {Boolean} [options.depopulate=false] if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. - * @param {Boolean} [options.versionKey=true] if false, exclude the version key (`__v` by default) from the output - * @param {Boolean} [options.flattenMaps=false] if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. - * @return {Object} js object - * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.toObject = function(options) { - return this.$toObject(options); -}; - -/*! - * Minimizes an object, removing undefined values and empty objects - * - * @param {Object} object to minimize - * @return {Object} - */ - -function minimize(obj) { - const keys = Object.keys(obj); - let i = keys.length; - let hasKeys; - let key; - let val; - - while (i--) { - key = keys[i]; - val = obj[key]; - - if (utils.isObject(val) && !Buffer.isBuffer(val)) { - obj[key] = minimize(val); - } - - if (undefined === obj[key]) { - delete obj[key]; - continue; - } - - hasKeys = true; - } - - return hasKeys - ? obj - : undefined; -} - -/*! - * Applies virtuals properties to `json`. - * - * @param {Document} self - * @param {Object} json - * @param {String} type either `virtuals` or `paths` - * @return {Object} `json` - */ - -function applyGetters(self, json, type, options) { - const schema = self.schema; - const paths = Object.keys(schema[type]); - let i = paths.length; - const numPaths = i; - let path; - let assignPath; - let cur = self._doc; - let v; - - if (!cur) { - return json; - } - - if (type === 'virtuals') { - options = options || {}; - for (i = 0; i < numPaths; ++i) { - path = paths[i]; - // We may be applying virtuals to a nested object, for example if calling - // `doc.nestedProp.toJSON()`. If so, the path we assign to, `assignPath`, - // will be a trailing substring of the `path`. - assignPath = path; - if (options.path != null) { - if (!path.startsWith(options.path + '.')) { - continue; - } - assignPath = path.substr(options.path.length + 1); - } - const parts = assignPath.split('.'); - v = clone(self.get(path), options); - if (v === void 0) { - continue; - } - const plen = parts.length; - cur = json; - for (let j = 0; j < plen - 1; ++j) { - cur[parts[j]] = cur[parts[j]] || {}; - cur = cur[parts[j]]; - } - cur[parts[plen - 1]] = v; - } - - return json; - } - - while (i--) { - path = paths[i]; - - const parts = path.split('.'); - const plen = parts.length; - const last = plen - 1; - let branch = json; - let part; - cur = self._doc; - - for (let ii = 0; ii < plen; ++ii) { - part = parts[ii]; - v = cur[part]; - if (ii === last) { - const val = self.get(path); - // Ignore single nested docs: getters will run because of `clone()` - // before `applyGetters()` in `$toObject()`. Quirk because single - // nested subdocs are hydrated docs in `_doc` as opposed to POJOs. - if (val != null && val.$__ == null) { - branch[part] = clone(val, options); - } - } else if (v == null) { - if (part in cur) { - branch[part] = v; - } - break; - } else { - branch = branch[part] || (branch[part] = {}); - } - cur = v; - } - } - - return json; -} - -/** - * The return value of this method is used in calls to JSON.stringify(doc). - * - * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. - * - * schema.set('toJSON', { virtuals: true }) - * - * See [schema options](/docs/guide.html#toJSON) for details. - * - * @param {Object} options - * @return {Object} - * @see Document#toObject #document_Document-toObject - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.toJSON = function(options) { - return this.$toObject(options, true); -}; - -/** - * Helper for console.log - * - * @api public - * @method inspect - * @memberOf Document - * @instance - */ - -Document.prototype.inspect = function(options) { - const isPOJO = utils.isPOJO(options); - let opts; - if (isPOJO) { - opts = options; - opts.minimize = false; - } - return this.toObject(opts); -}; - -if (inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ - - Document.prototype[inspect.custom] = Document.prototype.inspect; -} - -/** - * Helper for console.log - * - * @api public - * @method toString - * @memberOf Document - * @instance - */ - -Document.prototype.toString = function() { - return inspect(this.inspect()); -}; - -/** - * Returns true if the Document stores the same data as doc. - * - * Documents are considered equal when they have matching `_id`s, unless neither - * document has an `_id`, in which case this function falls back to using - * `deepEqual()`. - * - * @param {Document} doc a document to compare - * @return {Boolean} - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.equals = function(doc) { - if (!doc) { - return false; - } - - const tid = this.get('_id'); - const docid = doc.get ? doc.get('_id') : doc; - if (!tid && !docid) { - return deepEqual(this, doc); - } - return tid && tid.equals - ? tid.equals(docid) - : tid === docid; -}; - -/** - * Populates document references, executing the `callback` when complete. - * If you want to use promises instead, use this function with - * [`execPopulate()`](#document_Document-execPopulate) - * - * ####Example: - * - * doc - * .populate('company') - * .populate({ - * path: 'notes', - * match: /airline/, - * select: 'text', - * model: 'modelName' - * options: opts - * }, function (err, user) { - * assert(doc._id === user._id) // the document itself is passed - * }) - * - * // summary - * doc.populate(path) // not executed - * doc.populate(options); // not executed - * doc.populate(path, callback) // executed - * doc.populate(options, callback); // executed - * doc.populate(callback); // executed - * doc.populate(options).execPopulate() // executed, returns promise - * - * - * ####NOTE: - * - * Population does not occur unless a `callback` is passed *or* you explicitly - * call `execPopulate()`. - * Passing the same path a second time will overwrite the previous path options. - * See [Model.populate()](#model_Model.populate) for explaination of options. - * - * @see Model.populate #model_Model.populate - * @see Document.execPopulate #document_Document-execPopulate - * @param {String|Object} [path] The path to populate or an options object - * @param {Function} [callback] When passed, population is invoked - * @api public - * @return {Document} this - * @memberOf Document - * @instance - */ - -Document.prototype.populate = function populate() { - if (arguments.length === 0) { - return this; - } - - const pop = this.$__.populate || (this.$__.populate = {}); - const args = utils.args(arguments); - let fn; - - if (typeof args[args.length - 1] === 'function') { - fn = args.pop(); - } - - // allow `doc.populate(callback)` - if (args.length) { - // use hash to remove duplicate paths - const res = utils.populate.apply(null, args); - for (let i = 0; i < res.length; ++i) { - pop[res[i].path] = res[i]; - } - } - - if (fn) { - const paths = utils.object.vals(pop); - this.$__.populate = undefined; - let topLevelModel = this.constructor; - if (this.$__isNested) { - topLevelModel = this.$__.scope.constructor; - const nestedPath = this.$__.nestedPath; - paths.forEach(function(populateOptions) { - populateOptions.path = nestedPath + '.' + populateOptions.path; - }); - } - - // Use `$session()` by default if the document has an associated session - // See gh-6754 - if (this.$session() != null) { - const session = this.$session(); - paths.forEach(path => { - if (path.options == null) { - path.options = { session: session }; - return; - } - if (!('session' in path.options)) { - path.options.session = session; - } - }); - } - - topLevelModel.populate(this, paths, fn); - } - - return this; -}; - -/** - * Explicitly executes population and returns a promise. Useful for ES2015 - * integration. - * - * ####Example: - * - * var promise = doc. - * populate('company'). - * populate({ - * path: 'notes', - * match: /airline/, - * select: 'text', - * model: 'modelName' - * options: opts - * }). - * execPopulate(); - * - * // summary - * doc.execPopulate().then(resolve, reject); - * - * - * @see Document.populate #document_Document-populate - * @api public - * @param {Function} [callback] optional callback. If specified, a promise will **not** be returned - * @return {Promise} promise that resolves to the document when population is done - * @memberOf Document - * @instance - */ - -Document.prototype.execPopulate = function(callback) { - return utils.promiseOrCallback(callback, cb => { - this.populate(cb); - }, this.constructor.events); -}; - -/** - * Gets _id(s) used during population of the given `path`. - * - * ####Example: - * - * Model.findOne().populate('author').exec(function (err, doc) { - * console.log(doc.author.name) // Dr.Seuss - * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' - * }) - * - * If the path was not populated, undefined is returned. - * - * @param {String} path - * @return {Array|ObjectId|Number|Buffer|String|undefined} - * @memberOf Document - * @instance - * @api public - */ - -Document.prototype.populated = function(path, val, options) { - // val and options are internal - if (val === null || val === void 0) { - if (!this.$__.populated) { - return undefined; - } - const v = this.$__.populated[path]; - if (v) { - return v.value; - } - return undefined; - } - - // internal - - if (val === true) { - if (!this.$__.populated) { - return undefined; - } - return this.$__.populated[path]; - } - - this.$__.populated || (this.$__.populated = {}); - this.$__.populated[path] = {value: val, options: options}; - return val; -}; - -/** - * Takes a populated field and returns it to its unpopulated state. - * - * ####Example: - * - * Model.findOne().populate('author').exec(function (err, doc) { - * console.log(doc.author.name); // Dr.Seuss - * console.log(doc.depopulate('author')); - * console.log(doc.author); // '5144cf8050f071d979c118a7' - * }) - * - * If the path was not populated, this is a no-op. - * - * @param {String} path - * @return {Document} this - * @see Document.populate #document_Document-populate - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.depopulate = function(path) { - if (typeof path === 'string') { - path = path.split(' '); - } - let populatedIds; - const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : []; - const populated = get(this, '$__.populated', {}); - - if (arguments.length === 0) { - // Depopulate all - for (let i = 0; i < virtualKeys.length; i++) { - delete this.$$populatedVirtuals[virtualKeys[i]]; - delete this._doc[virtualKeys[i]]; - delete populated[virtualKeys[i]]; - } - - const keys = Object.keys(populated); - - for (let i = 0; i < keys.length; i++) { - populatedIds = this.populated(keys[i]); - if (!populatedIds) { - continue; - } - delete populated[keys[i]]; - this.$set(keys[i], populatedIds); - } - return this; - } - - for (let i = 0; i < path.length; i++) { - populatedIds = this.populated(path[i]); - delete populated[path[i]]; - - if (virtualKeys.indexOf(path[i]) !== -1) { - delete this.$$populatedVirtuals[path[i]]; - delete this._doc[path[i]]; - } else { - this.$set(path[i], populatedIds); - } - } - return this; -}; - - -/** - * Returns the full path to this document. - * - * @param {String} [path] - * @return {String} - * @api private - * @method $__fullPath - * @memberOf Document - * @instance - */ - -Document.prototype.$__fullPath = function(path) { - // overridden in SubDocuments - return path || ''; -}; - -/*! - * Module exports. - */ - -Document.ValidationError = ValidationError; -module.exports = exports = Document; diff --git a/node_modules/mongoose/lib/document_provider.js b/node_modules/mongoose/lib/document_provider.js deleted file mode 100644 index 1ace61f4fb386ae02e93ed6b94ce6a9b3f8e746d..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/document_provider.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -/* eslint-env browser */ - -/*! - * Module dependencies. - */ -const Document = require('./document.js'); -const BrowserDocument = require('./browserDocument.js'); - -let isBrowser = false; - -/** - * Returns the Document constructor for the current context - * - * @api private - */ -module.exports = function() { - if (isBrowser) { - return BrowserDocument; - } - return Document; -}; - -/*! - * ignore - */ -module.exports.setBrowser = function(flag) { - isBrowser = flag; -}; diff --git a/node_modules/mongoose/lib/driver.js b/node_modules/mongoose/lib/driver.js deleted file mode 100644 index cf7ca3d7b252db92e49bb5dd387d1429ec61f1a4..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/driver.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -let driver = null; - -module.exports.get = function() { - return driver; -}; - -module.exports.set = function(v) { - driver = v; -}; diff --git a/node_modules/mongoose/lib/drivers/SPEC.md b/node_modules/mongoose/lib/drivers/SPEC.md deleted file mode 100644 index 64646931e832da518fbf02331b243eb28a998c28..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/SPEC.md +++ /dev/null @@ -1,4 +0,0 @@ - -# Driver Spec - -TODO diff --git a/node_modules/mongoose/lib/drivers/browser/ReadPreference.js b/node_modules/mongoose/lib/drivers/browser/ReadPreference.js deleted file mode 100644 index 1363570810b179b092e84e55140b85fdec9b6853..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/browser/ReadPreference.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * ignore - */ - -'use strict'; - -module.exports = function() {}; diff --git a/node_modules/mongoose/lib/drivers/browser/binary.js b/node_modules/mongoose/lib/drivers/browser/binary.js deleted file mode 100644 index 4658f7b9e0f720ae4e8582a8d6865fbb88600081..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/browser/binary.js +++ /dev/null @@ -1,14 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const Binary = require('bson').Binary; - -/*! - * Module exports. - */ - -module.exports = exports = Binary; diff --git a/node_modules/mongoose/lib/drivers/browser/decimal128.js b/node_modules/mongoose/lib/drivers/browser/decimal128.js deleted file mode 100644 index 5668182b354912f711420632150dbe65f11b72c4..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/browser/decimal128.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * ignore - */ - -'use strict'; - -module.exports = require('bson').Decimal128; diff --git a/node_modules/mongoose/lib/drivers/browser/index.js b/node_modules/mongoose/lib/drivers/browser/index.js deleted file mode 100644 index 56d0b8a75c9f61c803cac9adf9c3a46c10daa2ac..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/browser/index.js +++ /dev/null @@ -1,13 +0,0 @@ -/*! - * Module exports. - */ - -'use strict'; - -exports.Binary = require('./binary'); -exports.Collection = function() { - throw new Error('Cannot create a collection from browser library'); -}; -exports.Decimal128 = require('./decimal128'); -exports.ObjectId = require('./objectid'); -exports.ReadPreference = require('./ReadPreference'); diff --git a/node_modules/mongoose/lib/drivers/browser/objectid.js b/node_modules/mongoose/lib/drivers/browser/objectid.js deleted file mode 100644 index b1e603d714e75000f73640a7fa38e8d4b9f64ff5..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/browser/objectid.js +++ /dev/null @@ -1,28 +0,0 @@ - -/*! - * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId - * @constructor NodeMongoDbObjectId - * @see ObjectId - */ - -'use strict'; - -const ObjectId = require('bson').ObjectID; - -/*! - * Getter for convenience with populate, see gh-6115 - */ - -Object.defineProperty(ObjectId.prototype, '_id', { - enumerable: false, - configurable: true, - get: function() { - return this; - } -}); - -/*! - * ignore - */ - -module.exports = exports = ObjectId; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js deleted file mode 100644 index 024ee181a55875088b32558f3bf3b59794ee4254..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js +++ /dev/null @@ -1,47 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const mongodb = require('mongodb'); -const ReadPref = mongodb.ReadPreference; - -/*! - * Converts arguments to ReadPrefs the driver - * can understand. - * - * @param {String|Array} pref - * @param {Array} [tags] - */ - -module.exports = function readPref(pref, tags) { - if (Array.isArray(pref)) { - tags = pref[1]; - pref = pref[0]; - } - - if (pref instanceof ReadPref) { - return 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 new ReadPref(pref, tags); -}; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js deleted file mode 100644 index 4e3c86f78c83e89ed25d3ade1b97029dbb772f47..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js +++ /dev/null @@ -1,10 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const Binary = require('mongodb').Binary; - -module.exports = exports = Binary; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js deleted file mode 100644 index be68049ba40a53ff4760ee4879aa605914cfa262..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js +++ /dev/null @@ -1,332 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseCollection = require('../../collection'); -const Collection = require('mongodb').Collection; -const get = require('../../helpers/get'); -const sliced = require('sliced'); -const stream = require('stream'); -const util = require('util'); - -/** - * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation. - * - * All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management. - * - * @inherits Collection - * @api private - */ - -function NativeCollection() { - this.collection = null; - MongooseCollection.apply(this, arguments); -} - -/*! - * Inherit from abstract Collection. - */ - -NativeCollection.prototype.__proto__ = MongooseCollection.prototype; - -/** - * Called when the connection opens. - * - * @api private - */ - -NativeCollection.prototype.onOpen = function() { - const _this = this; - - // always get a new collection in case the user changed host:port - // of parent db instance when re-opening the connection. - - if (!_this.opts.capped.size) { - // non-capped - callback(null, _this.conn.db.collection(_this.name)); - return _this.collection; - } - - // capped - return _this.conn.db.collection(_this.name, function(err, c) { - if (err) return callback(err); - - // discover if this collection exists and if it is capped - _this.conn.db.listCollections({name: _this.name}).toArray(function(err, docs) { - if (err) { - return callback(err); - } - const doc = docs[0]; - const exists = !!doc; - - if (exists) { - if (doc.options && doc.options.capped) { - callback(null, c); - } else { - const msg = 'A non-capped collection exists with the name: ' + _this.name + '\n\n' - + ' To use this collection as a capped collection, please ' - + 'first convert it.\n' - + ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped'; - err = new Error(msg); - callback(err); - } - } else { - // create - const opts = Object.assign({}, _this.opts.capped); - opts.capped = true; - _this.conn.db.createCollection(_this.name, opts, callback); - } - }); - }); - - function callback(err, collection) { - if (err) { - // likely a strict mode error - _this.conn.emit('error', err); - } else { - _this.collection = collection; - MongooseCollection.prototype.onOpen.call(_this); - } - } -}; - -/** - * Called when the connection closes - * - * @api private - */ - -NativeCollection.prototype.onClose = function(force) { - MongooseCollection.prototype.onClose.call(this, force); -}; - -/*! - * ignore - */ - -const syncCollectionMethods = { watch: true }; - -/*! - * Copy the collection methods and make them subject to queues - */ - -function iter(i) { - NativeCollection.prototype[i] = function() { - const collection = this.collection; - const args = arguments; - const _this = this; - const debug = get(_this, 'conn.base.options.debug'); - - // If user force closed, queueing will hang forever. See #5664 - if (this.opts.$wasForceClosed) { - return this.conn.db.collection(this.name)[i].apply(collection, args); - } - if (this.buffer) { - if (syncCollectionMethods[i]) { - throw new Error('Collection method ' + i + ' is synchronous'); - } - this.addQueue(i, arguments); - return; - } - - if (debug) { - if (typeof debug === 'function') { - debug.apply(_this, - [_this.name, i].concat(sliced(args, 0, args.length - 1))); - } else if (debug instanceof stream.Writable) { - this.$printToStream(_this.name, i, args, debug); - } else { - this.$print(_this.name, i, args); - } - } - - try { - return collection[i].apply(collection, args); - } catch (error) { - // Collection operation may throw because of max bson size, catch it here - // See gh-3906 - if (args.length > 0 && - typeof args[args.length - 1] === 'function') { - args[args.length - 1](error); - } else { - throw error; - } - } - }; -} - -for (const i in Collection.prototype) { - // Janky hack to work around gh-3005 until we can get rid of the mongoose - // collection abstraction - try { - if (typeof Collection.prototype[i] !== 'function') { - continue; - } - } catch (e) { - continue; - } - - iter(i); -} - -/** - * Debug print helper - * - * @api public - * @method $print - */ - -NativeCollection.prototype.$print = function(name, i, args) { - const moduleName = '\x1B[0;36mMongoose:\x1B[0m '; - const functionCall = [name, i].join('.'); - const _args = []; - for (let j = args.length - 1; j >= 0; --j) { - if (this.$format(args[j]) || _args.length) { - _args.unshift(this.$format(args[j])); - } - } - const params = '(' + _args.join(', ') + ')'; - - console.info(moduleName + functionCall + params); -}; - -/** - * Debug print helper - * - * @api public - * @method $print - */ - -NativeCollection.prototype.$printToStream = function(name, i, args, stream) { - const functionCall = [name, i].join('.'); - const _args = []; - for (let j = args.length - 1; j >= 0; --j) { - if (this.$format(args[j]) || _args.length) { - _args.unshift(this.$format(args[j])); - } - } - const params = '(' + _args.join(', ') + ')'; - - stream.write(functionCall + params, 'utf8'); -}; - -/** - * Formatter for debug print args - * - * @api public - * @method $format - */ - -NativeCollection.prototype.$format = function(arg) { - const type = typeof arg; - if (type === 'function' || type === 'undefined') return ''; - return format(arg); -}; - -/*! - * Debug print helper - */ - -function inspectable(representation) { - const ret = { - inspect: function() { return representation; }, - }; - if (util.inspect.custom) { - ret[util.inspect.custom] = ret.inspect; - } - return ret; -} -function map(o) { - return format(o, true); -} -function formatObjectId(x, key) { - x[key] = inspectable('ObjectId("' + x[key].toHexString() + '")'); -} -function formatDate(x, key) { - x[key] = inspectable('new Date("' + x[key].toUTCString() + '")'); -} -function format(obj, sub) { - if (obj && typeof obj.toBSON === 'function') { - obj = obj.toBSON(); - } - if (obj == null) { - return obj; - } - - let x = require('../../utils').clone(obj, {transform: false}); - - if (x.constructor.name === 'Binary') { - x = 'BinData(' + x.sub_type + ', "' + x.toString('base64') + '")'; - } else if (x.constructor.name === 'ObjectID') { - x = inspectable('ObjectId("' + x.toHexString() + '")'); - } else if (x.constructor.name === 'Date') { - x = inspectable('new Date("' + x.toUTCString() + '")'); - } else if (x.constructor.name === 'Object') { - const keys = Object.keys(x); - const numKeys = keys.length; - let key; - for (let i = 0; i < numKeys; ++i) { - key = keys[i]; - if (x[key]) { - let error; - if (typeof x[key].toBSON === 'function') { - try { - // `session.toBSON()` throws an error. This means we throw errors - // in debug mode when using transactions, see gh-6712. As a - // workaround, catch `toBSON()` errors, try to serialize without - // `toBSON()`, and rethrow if serialization still fails. - x[key] = x[key].toBSON(); - } catch (_error) { - error = _error; - } - } - if (x[key].constructor.name === 'Binary') { - x[key] = 'BinData(' + x[key].sub_type + ', "' + - x[key].buffer.toString('base64') + '")'; - } else if (x[key].constructor.name === 'Object') { - x[key] = format(x[key], true); - } else if (x[key].constructor.name === 'ObjectID') { - formatObjectId(x, key); - } else if (x[key].constructor.name === 'Date') { - formatDate(x, key); - } else if (x[key].constructor.name === 'ClientSession') { - x[key] = inspectable('ClientSession("' + - get(x[key], 'id.id.buffer', '').toString('hex') + '")'); - } else if (Array.isArray(x[key])) { - x[key] = x[key].map(map); - } else if (error != null) { - // If there was an error with `toBSON()` and the object wasn't - // already converted to a string representation, rethrow it. - // Open to better ideas on how to handle this. - throw error; - } - } - } - } - if (sub) { - return x; - } - - return util. - inspect(x, false, 10, true). - replace(/\n/g, ''). - replace(/\s{2,}/g, ' '); -} - -/** - * Retrieves information about this collections indexes. - * - * @param {Function} callback - * @method getIndexes - * @api public - */ - -NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation; - -/*! - * Module exports. - */ - -module.exports = NativeCollection; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js deleted file mode 100644 index 9fd4b82fea80634537cdf1c82b317b230b1dbc90..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js +++ /dev/null @@ -1,181 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseConnection = require('../../connection'); -const STATES = require('../../connectionstate'); - -/** - * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation. - * - * @inherits Connection - * @api private - */ - -function NativeConnection() { - MongooseConnection.apply(this, arguments); - this._listening = false; -} - -/** - * Expose the possible connection states. - * @api public - */ - -NativeConnection.STATES = STATES; - -/*! - * Inherits from Connection. - */ - -NativeConnection.prototype.__proto__ = MongooseConnection.prototype; - -/** - * Switches to a different database using the same connection pool. - * - * Returns a new connection object, with the new db. - * - * @param {String} name The database name - * @return {Connection} New Connection Object - * @api public - */ - -NativeConnection.prototype.useDb = function(name, options) { - // Return immediately if cached - if (options && options.useCache && this.relatedDbs[name]) { - return this.relatedDbs[name]; - } - - // we have to manually copy all of the attributes... - const newConn = new this.constructor(); - newConn.name = name; - newConn.base = this.base; - newConn.collections = {}; - newConn.models = {}; - newConn.replica = this.replica; - newConn.name = this.name; - newConn.options = this.options; - newConn._readyState = this._readyState; - newConn._closeCalled = this._closeCalled; - newConn._hasOpened = this._hasOpened; - newConn._listening = false; - - newConn.host = this.host; - newConn.port = this.port; - newConn.user = this.user; - newConn.pass = this.pass; - - // First, when we create another db object, we are not guaranteed to have a - // db object to work with. So, in the case where we have a db object and it - // is connected, we can just proceed with setting everything up. However, if - // we do not have a db or the state is not connected, then we need to wait on - // the 'open' event of the connection before doing the rest of the setup - // the 'connected' event is the first time we'll have access to the db object - - const _this = this; - - newConn.client = _this.client; - - if (this.db && this._readyState === STATES.connected) { - wireup(); - } else { - this.once('connected', wireup); - } - - function wireup() { - newConn.client = _this.client; - newConn.db = _this.client.db(name); - newConn.onOpen(); - // setup the events appropriately - listen(newConn); - } - - newConn.name = name; - - // push onto the otherDbs stack, this is used when state changes - this.otherDbs.push(newConn); - newConn.otherDbs.push(this); - - // push onto the relatedDbs cache, this is used when state changes - if (options && options.useCache) { - this.relatedDbs[newConn.name] = newConn; - newConn.relatedDbs = this.relatedDbs; - } - - return newConn; -}; - -/*! - * Register listeners for important events and bubble appropriately. - */ - -function listen(conn) { - if (conn.db._listening) { - return; - } - conn.db._listening = true; - - conn.db.on('close', function(force) { - if (conn._closeCalled) return; - - // the driver never emits an `open` event. auto_reconnect still - // emits a `close` event but since we never get another - // `open` we can't emit close - if (conn.db.serverConfig.autoReconnect) { - conn.readyState = STATES.disconnected; - conn.emit('close'); - return; - } - conn.onClose(force); - }); - conn.db.on('error', function(err) { - conn.emit('error', err); - }); - conn.db.on('reconnect', function() { - conn.readyState = STATES.connected; - conn.emit('reconnect'); - conn.emit('reconnected'); - conn.onOpen(); - }); - conn.db.on('timeout', function(err) { - conn.emit('timeout', err); - }); - conn.db.on('open', function(err, db) { - if (STATES.disconnected === conn.readyState && db && db.databaseName) { - conn.readyState = STATES.connected; - conn.emit('reconnect'); - conn.emit('reconnected'); - } - }); - conn.db.on('parseError', function(err) { - conn.emit('parseError', err); - }); -} - -/** - * Closes the connection - * - * @param {Boolean} [force] - * @param {Function} [fn] - * @return {Connection} this - * @api private - */ - -NativeConnection.prototype.doClose = function(force, fn) { - this.client.close(force, (err, res) => { - // Defer because the driver will wait at least 1ms before finishing closing - // the pool, see https://github.com/mongodb-js/mongodb-core/blob/a8f8e4ce41936babc3b9112bf42d609779f03b39/lib/connection/pool.js#L1026-L1030. - // If there's queued operations, you may still get some background work - // after the callback is called. - setTimeout(() => fn(err, res), 1); - }); - return this; -}; - -/*! - * Module exports. - */ - -module.exports = NativeConnection; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js deleted file mode 100644 index c895f17fd2a413ac2e35a4bccb69c4a9854e49f9..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * ignore - */ - -'use strict'; - -module.exports = require('mongodb').Decimal128; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js deleted file mode 100644 index 648207d712a28aad9d13bda58554956437c20e12..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * Module exports. - */ - -'use strict'; - -exports.Binary = require('./binary'); -exports.Collection = require('./collection'); -exports.Decimal128 = require('./decimal128'); -exports.ObjectId = require('./objectid'); -exports.ReadPreference = require('./ReadPreference'); diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js deleted file mode 100644 index 6f432b796855243c134b0d4be8b4d6b2028a6495..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js +++ /dev/null @@ -1,16 +0,0 @@ - -/*! - * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId - * @constructor NodeMongoDbObjectId - * @see ObjectId - */ - -'use strict'; - -const ObjectId = require('mongodb').ObjectId; - -/*! - * ignore - */ - -module.exports = exports = ObjectId; diff --git a/node_modules/mongoose/lib/error/browserMissingSchema.js b/node_modules/mongoose/lib/error/browserMissingSchema.js deleted file mode 100644 index 852f8739bc3f242682b5a39568a6fbfdba4fba9c..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/browserMissingSchema.js +++ /dev/null @@ -1,38 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/*! - * MissingSchema Error constructor. - * - * @inherits MongooseError - */ - -function MissingSchemaError() { - const msg = 'Schema hasn\'t been registered for document.\n' - + 'Use mongoose.Document(name, schema)'; - MongooseError.call(this, msg); - this.name = 'MissingSchemaError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -MissingSchemaError.prototype = Object.create(MongooseError.prototype); -MissingSchemaError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = MissingSchemaError; diff --git a/node_modules/mongoose/lib/error/cast.js b/node_modules/mongoose/lib/error/cast.js deleted file mode 100644 index 1980d38baec85bbd2d3a82d219e610c50db9dcf2..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/cast.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./mongooseError'); -const util = require('util'); - -/** - * Casting Error constructor. - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function CastError(type, value, path, reason) { - let stringValue = util.inspect(value); - stringValue = stringValue.replace(/^'/, '"').replace(/'$/, '"'); - if (stringValue.charAt(0) !== '"') { - stringValue = '"' + stringValue + '"'; - } - MongooseError.call(this, 'Cast to ' + type + ' failed for value ' + - stringValue + ' at path "' + path + '"'); - this.name = 'CastError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - this.stringValue = stringValue; - this.kind = type; - this.value = value; - this.path = path; - this.reason = reason; -} - -/*! - * Inherits from MongooseError. - */ - -CastError.prototype = Object.create(MongooseError.prototype); -CastError.prototype.constructor = MongooseError; - -/*! - * ignore - */ - -CastError.prototype.setModel = function(model) { - this.model = model; - this.message = 'Cast to ' + this.kind + ' failed for value ' + - this.stringValue + ' at path "' + this.path + '"' + ' for model "' + - model.modelName + '"'; -}; - -/*! - * exports - */ - -module.exports = CastError; diff --git a/node_modules/mongoose/lib/error/disconnected.js b/node_modules/mongoose/lib/error/disconnected.js deleted file mode 100644 index f542459e6af3fe5954f61dd9b30a9307ef3b3653..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/disconnected.js +++ /dev/null @@ -1,42 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/** - * Casting Error constructor. - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function DisconnectedError(connectionString) { - MongooseError.call(this, 'Ran out of retries trying to reconnect to "' + - connectionString + '". Try setting `server.reconnectTries` and ' + - '`server.reconnectInterval` to something higher.'); - this.name = 'DisconnectedError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -DisconnectedError.prototype = Object.create(MongooseError.prototype); -DisconnectedError.prototype.constructor = MongooseError; - - -/*! - * exports - */ - -module.exports = DisconnectedError; diff --git a/node_modules/mongoose/lib/error/divergentArray.js b/node_modules/mongoose/lib/error/divergentArray.js deleted file mode 100644 index 872fd2bfac4989c5925abe7f8384ac68cfa36978..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/divergentArray.js +++ /dev/null @@ -1,48 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/*! - * DivergentArrayError constructor. - * - * @inherits MongooseError - */ - -function DivergentArrayError(paths) { - const msg = 'For your own good, using `document.save()` to update an array ' - + 'which was selected using an $elemMatch projection OR ' - + 'populated using skip, limit, query conditions, or exclusion of ' - + 'the _id field when the operation results in a $pop or $set of ' - + 'the entire array is not supported. The following ' - + 'path(s) would have been modified unsafely:\n' - + ' ' + paths.join('\n ') + '\n' - + 'Use Model.update() to update these arrays instead.'; - // TODO write up a docs page (FAQ) and link to it - - MongooseError.call(this, msg); - this.name = 'DivergentArrayError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -DivergentArrayError.prototype = Object.create(MongooseError.prototype); -DivergentArrayError.prototype.constructor = MongooseError; - - -/*! - * exports - */ - -module.exports = DivergentArrayError; diff --git a/node_modules/mongoose/lib/error/index.js b/node_modules/mongoose/lib/error/index.js deleted file mode 100644 index 7a5e9cf663c00e9d4a190ca16dc64f000ac72492..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/index.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -const MongooseError = require('./mongooseError'); - -/*! - * Module exports. - */ - -module.exports = exports = MongooseError; - -/** - * The default built-in validator error messages. - * - * @see Error.messages #error_messages_MongooseError-messages - * @api public - */ - -MongooseError.messages = require('./messages'); - -// backward compat -MongooseError.Messages = MongooseError.messages; - -/** - * An instance of this error class will be returned when `save()` fails - * because the underlying - * document was not found. The constructor takes one parameter, the - * conditions that mongoose passed to `update()` when trying to update - * the document. - * - * @api public - */ - -MongooseError.DocumentNotFoundError = require('./notFound'); - -/** - * An instance of this error class will be returned when mongoose failed to - * cast a value. - * - * @api public - */ - -MongooseError.CastError = require('./cast'); - -/** - * An instance of this error class will be returned when [validation](/docs/validation.html) failed. - * The `errors` property contains an object whose keys are the paths that failed and whose values are - * instances of CastError or ValidationError. - * - * @api public - */ - -MongooseError.ValidationError = require('./validation'); - -/** - * A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances - * - * @api public - */ - -MongooseError.ValidatorError = require('./validator'); - -/** - * An instance of this error class will be returned when you call `save()` after - * the document in the database was changed in a potentially unsafe way. See - * the [`versionKey` option](/docs/guide.html#versionKey) for more information. - * - * @api public - */ - -MongooseError.VersionError = require('./version'); - -/** - * An instance of this error class will be returned when you call `save()` multiple - * times on the same document in parallel. See the [FAQ](/docs/faq.html) for more - * information. - * - * @api public - */ - -MongooseError.ParallelSaveError = require('./parallelSave'); - -/** - * Thrown when a model with the given name was already registered on the connection. - * See [the FAQ about `OverwriteModelError`](/docs/faq.html#overwrite-model-error). - * - * @api public - */ - -MongooseError.OverwriteModelError = require('./overwriteModel'); - -/** - * Thrown when you try to access a model that has not been registered yet - * - * @api public - */ - -MongooseError.MissingSchemaError = require('./missingSchema'); - -/** - * An instance of this error will be returned if you used an array projection - * and then modified the array in an unsafe way. - * - * @api public - */ - -MongooseError.DivergentArrayError = require('./divergentArray'); diff --git a/node_modules/mongoose/lib/error/messages.js b/node_modules/mongoose/lib/error/messages.js deleted file mode 100644 index 4483a86d7ab8d70caa3759425c5d05d01bb0a836..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/messages.js +++ /dev/null @@ -1,46 +0,0 @@ - -/** - * The default built-in validator error messages. These may be customized. - * - * // customize within each schema or globally like so - * var mongoose = require('mongoose'); - * mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; - * - * As you might have noticed, error messages support basic templating - * - * - `{PATH}` is replaced with the invalid document path - * - `{VALUE}` is replaced with the invalid value - * - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined" - * - `{MIN}` is replaced with the declared min value for the Number.min validator - * - `{MAX}` is replaced with the declared max value for the Number.max validator - * - * Click the "show code" link below to see all defaults. - * - * @static messages - * @receiver MongooseError - * @api public - */ - -'use strict'; - -const msg = module.exports = exports = {}; - -msg.DocumentNotFoundError = null; - -msg.general = {}; -msg.general.default = 'Validator failed for path `{PATH}` with value `{VALUE}`'; -msg.general.required = 'Path `{PATH}` is required.'; - -msg.Number = {}; -msg.Number.min = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).'; -msg.Number.max = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).'; - -msg.Date = {}; -msg.Date.min = 'Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).'; -msg.Date.max = 'Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).'; - -msg.String = {}; -msg.String.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; -msg.String.match = 'Path `{PATH}` is invalid ({VALUE}).'; -msg.String.minlength = 'Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'; -msg.String.maxlength = 'Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).'; diff --git a/node_modules/mongoose/lib/error/missingSchema.js b/node_modules/mongoose/lib/error/missingSchema.js deleted file mode 100644 index 319515820fbe21599b8bc349157dfd6a0f0b526b..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/missingSchema.js +++ /dev/null @@ -1,39 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/*! - * MissingSchema Error constructor. - * - * @inherits MongooseError - */ - -function MissingSchemaError(name) { - const msg = 'Schema hasn\'t been registered for model "' + name + '".\n' - + 'Use mongoose.model(name, schema)'; - MongooseError.call(this, msg); - this.name = 'MissingSchemaError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -MissingSchemaError.prototype = Object.create(MongooseError.prototype); -MissingSchemaError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = MissingSchemaError; diff --git a/node_modules/mongoose/lib/error/mongooseError.js b/node_modules/mongoose/lib/error/mongooseError.js deleted file mode 100644 index 398c31b7df310a15ad68fbe540d2115e15212e63..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/mongooseError.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * MongooseError constructor - * - * @param {String} msg Error message - * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error - */ - -'use strict'; - -function MongooseError(msg) { - Error.call(this); - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - this.message = msg; - this.name = 'MongooseError'; -} - -/*! - * Inherits from Error. - */ - -MongooseError.prototype = Object.create(Error.prototype); -MongooseError.prototype.constructor = Error; - -module.exports = MongooseError; diff --git a/node_modules/mongoose/lib/error/notFound.js b/node_modules/mongoose/lib/error/notFound.js deleted file mode 100644 index 766fdee35e38d4a709928363e1931c1e4555e78a..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/notFound.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./'); -const util = require('util'); - -/*! - * OverwriteModel Error constructor. - * - * @inherits MongooseError - */ - -function DocumentNotFoundError(filter) { - let msg; - const messages = MongooseError.messages; - if (messages.DocumentNotFoundError != null) { - msg = typeof messages.DocumentNotFoundError === 'function' ? - messages.DocumentNotFoundError(filter) : - messages.DocumentNotFoundError; - } else { - msg = 'No document found for query "' + util.inspect(filter) + '"'; - } - - MongooseError.call(this, msg); - - this.name = 'DocumentNotFoundError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - - this.filter = filter; - // Backwards compat - this.query = filter; -} - -/*! - * Inherits from MongooseError. - */ - -DocumentNotFoundError.prototype = Object.create(MongooseError.prototype); -DocumentNotFoundError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = DocumentNotFoundError; diff --git a/node_modules/mongoose/lib/error/objectExpected.js b/node_modules/mongoose/lib/error/objectExpected.js deleted file mode 100644 index de54f4f3fd7ea466507ff8f3282cff6015a8dbfa..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/objectExpected.js +++ /dev/null @@ -1,37 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/** - * Strict mode error constructor - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function ObjectExpectedError(path, val) { - MongooseError.call(this, 'Tried to set nested object field `' + path + - '` to primitive value `' + val + '` and strict mode is set to throw.'); - this.name = 'ObjectExpectedError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - this.path = path; -} - -/*! - * Inherits from MongooseError. - */ - -ObjectExpectedError.prototype = Object.create(MongooseError.prototype); -ObjectExpectedError.prototype.constructor = MongooseError; - -module.exports = ObjectExpectedError; diff --git a/node_modules/mongoose/lib/error/objectParameter.js b/node_modules/mongoose/lib/error/objectParameter.js deleted file mode 100644 index 3a7f2849cb865b11832338cb4bfa23713e1b469b..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/objectParameter.js +++ /dev/null @@ -1,38 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/** - * Constructor for errors that happen when a parameter that's expected to be - * an object isn't an object - * - * @param {Any} value - * @param {String} paramName - * @param {String} fnName - * @inherits MongooseError - * @api private - */ - -function ObjectParameterError(value, paramName, fnName) { - MongooseError.call(this, 'Parameter "' + paramName + '" to ' + fnName + - '() must be an object, got ' + value.toString()); - this.name = 'ObjectParameterError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -ObjectParameterError.prototype = Object.create(MongooseError.prototype); -ObjectParameterError.prototype.constructor = MongooseError; - -module.exports = ObjectParameterError; diff --git a/node_modules/mongoose/lib/error/overwriteModel.js b/node_modules/mongoose/lib/error/overwriteModel.js deleted file mode 100644 index 21013b65ec99e0a740850c5b8d04e5a9a9999ff8..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/overwriteModel.js +++ /dev/null @@ -1,37 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/*! - * OverwriteModel Error constructor. - * - * @inherits MongooseError - */ - -function OverwriteModelError(name) { - MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.'); - this.name = 'OverwriteModelError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -OverwriteModelError.prototype = Object.create(MongooseError.prototype); -OverwriteModelError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = OverwriteModelError; diff --git a/node_modules/mongoose/lib/error/parallelSave.js b/node_modules/mongoose/lib/error/parallelSave.js deleted file mode 100644 index c9a189caa0fea0d09a511e1696dd483e3c316574..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/parallelSave.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./'); - -/** - * ParallelSave Error constructor. - * - * @inherits MongooseError - * @api private - */ - -function ParallelSaveError(doc) { - const msg = 'Can\'t save() the same doc multiple times in parallel. Document: '; - MongooseError.call(this, msg + doc.id); - this.name = 'ParallelSaveError'; -} - -/*! - * Inherits from MongooseError. - */ - -ParallelSaveError.prototype = Object.create(MongooseError.prototype); -ParallelSaveError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = ParallelSaveError; diff --git a/node_modules/mongoose/lib/error/strict.js b/node_modules/mongoose/lib/error/strict.js deleted file mode 100644 index 2678174768872bd2cc5212c6423424bbf3d13cbd..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/strict.js +++ /dev/null @@ -1,38 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/** - * Strict mode error constructor - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function StrictModeError(path, msg) { - msg = msg || 'Field `' + path + '` is not in schema and strict ' + - 'mode is set to throw.'; - MongooseError.call(this, msg); - this.name = 'StrictModeError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - this.path = path; -} - -/*! - * Inherits from MongooseError. - */ - -StrictModeError.prototype = Object.create(MongooseError.prototype); -StrictModeError.prototype.constructor = MongooseError; - -module.exports = StrictModeError; diff --git a/node_modules/mongoose/lib/error/validation.js b/node_modules/mongoose/lib/error/validation.js deleted file mode 100644 index 85b733c48b372442b882e1e0e58f74aecd2d17ae..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/validation.js +++ /dev/null @@ -1,112 +0,0 @@ -/*! - * Module requirements - */ - -'use strict'; - -const MongooseError = require('./'); -const util = require('util'); - -/** - * Document Validation Error - * - * @api private - * @param {Document} instance - * @inherits MongooseError - */ - -function ValidationError(instance) { - this.errors = {}; - this._message = ''; - if (instance && instance.constructor.name === 'model') { - this._message = instance.constructor.modelName + ' validation failed'; - MongooseError.call(this, this._message); - } else { - this._message = 'Validation failed'; - MongooseError.call(this, this._message); - } - this.name = 'ValidationError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - if (instance) { - instance.errors = this.errors; - } -} - -/*! - * Inherits from MongooseError. - */ - -ValidationError.prototype = Object.create(MongooseError.prototype); -ValidationError.prototype.constructor = MongooseError; - -/** - * Console.log helper - */ - -ValidationError.prototype.toString = function() { - return this.name + ': ' + _generateMessage(this); -}; - -/*! - * inspect helper - */ - -ValidationError.prototype.inspect = function() { - return Object.assign(new Error(this.message), this); -}; - -if (util.inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ - - ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect; -} - -/*! - * Helper for JSON.stringify - */ - -ValidationError.prototype.toJSON = function() { - return Object.assign({}, this, { message: this.message }); -}; - -/*! - * add message - */ - -ValidationError.prototype.addError = function(path, error) { - this.errors[path] = error; - this.message = this._message + ': ' + _generateMessage(this); -}; - -/*! - * ignore - */ - -function _generateMessage(err) { - const keys = Object.keys(err.errors || {}); - const len = keys.length; - const msgs = []; - let key; - - for (let i = 0; i < len; ++i) { - key = keys[i]; - if (err === err.errors[key]) { - continue; - } - msgs.push(key + ': ' + err.errors[key].message); - } - - return msgs.join(', '); -} - -/*! - * Module exports - */ - -module.exports = exports = ValidationError; diff --git a/node_modules/mongoose/lib/error/validator.js b/node_modules/mongoose/lib/error/validator.js deleted file mode 100644 index d07100c41829baac7271d40f5e4052137875ec91..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/validator.js +++ /dev/null @@ -1,89 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/** - * Schema validator error - * - * @param {Object} properties - * @inherits MongooseError - * @api private - */ - -function ValidatorError(properties) { - let msg = properties.message; - if (!msg) { - msg = MongooseError.messages.general.default; - } - - const message = this.formatMessage(msg, properties); - MongooseError.call(this, message); - - properties = Object.assign({}, properties, { message: message }); - this.name = 'ValidatorError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - this.properties = properties; - this.kind = properties.type; - this.path = properties.path; - this.value = properties.value; - this.reason = properties.reason; -} - -/*! - * Inherits from MongooseError - */ - -ValidatorError.prototype = Object.create(MongooseError.prototype); -ValidatorError.prototype.constructor = MongooseError; - -/*! - * The object used to define this validator. Not enumerable to hide - * it from `require('util').inspect()` output re: gh-3925 - */ - -Object.defineProperty(ValidatorError.prototype, 'properties', { - enumerable: false, - writable: true, - value: null -}); - -/*! - * Formats error messages - */ - -ValidatorError.prototype.formatMessage = function(msg, properties) { - if (typeof msg === 'function') { - return msg(properties); - } - const propertyNames = Object.keys(properties); - for (let i = 0; i < propertyNames.length; ++i) { - const propertyName = propertyNames[i]; - if (propertyName === 'message') { - continue; - } - msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); - } - return msg; -}; - -/*! - * toString helper - */ - -ValidatorError.prototype.toString = function() { - return this.message; -}; - -/*! - * exports - */ - -module.exports = ValidatorError; diff --git a/node_modules/mongoose/lib/error/version.js b/node_modules/mongoose/lib/error/version.js deleted file mode 100644 index 9fe92011650cd601335c368c459ad7cc5d378985..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/error/version.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./'); - -/** - * Version Error constructor. - * - * @inherits MongooseError - * @api private - */ - -function VersionError(doc, currentVersion, modifiedPaths) { - const modifiedPathsStr = modifiedPaths.join(', '); - MongooseError.call(this, 'No matching document found for id "' + doc._id + - '" version ' + currentVersion + ' modifiedPaths "' + modifiedPathsStr + '"'); - this.name = 'VersionError'; - this.version = currentVersion; - this.modifiedPaths = modifiedPaths; -} - -/*! - * Inherits from MongooseError. - */ - -VersionError.prototype = Object.create(MongooseError.prototype); -VersionError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = VersionError; diff --git a/node_modules/mongoose/lib/helpers/common.js b/node_modules/mongoose/lib/helpers/common.js deleted file mode 100644 index ac75317a15174d7df418e0ce06cbac91f32e0da3..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/common.js +++ /dev/null @@ -1,87 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const ObjectId = require('../types/objectid'); -const utils = require('../utils'); - -exports.flatten = flatten; -exports.modifiedPaths = modifiedPaths; - -/*! - * ignore - */ - -function flatten(update, path, options) { - let keys; - if (update && utils.isMongooseObject(update) && !Buffer.isBuffer(update)) { - keys = Object.keys(update.toObject({ transform: false, virtuals: false })); - } else { - keys = Object.keys(update || {}); - } - - const numKeys = keys.length; - const result = {}; - path = path ? path + '.' : ''; - - for (let i = 0; i < numKeys; ++i) { - const key = keys[i]; - const val = update[key]; - result[path + key] = val; - if (shouldFlatten(val)) { - if (options && options.skipArrays && Array.isArray(val)) { - continue; - } - const flat = flatten(val, path + key, options); - for (const k in flat) { - result[k] = flat[k]; - } - if (Array.isArray(val)) { - result[path + key] = val; - } - } - } - - return result; -} - -/*! - * ignore - */ - -function modifiedPaths(update, path, result) { - const keys = Object.keys(update || {}); - const numKeys = keys.length; - result = result || {}; - path = path ? path + '.' : ''; - - for (let i = 0; i < numKeys; ++i) { - const key = keys[i]; - let val = update[key]; - - result[path + key] = true; - if (utils.isMongooseObject(val) && !Buffer.isBuffer(val)) { - val = val.toObject({ transform: false, virtuals: false }); - } - if (shouldFlatten(val)) { - modifiedPaths(val, path + key, result); - } - } - - return result; -} - -/*! - * ignore - */ - -function shouldFlatten(val) { - return val && - typeof val === 'object' && - !(val instanceof Date) && - !(val instanceof ObjectId) && - (!Array.isArray(val) || val.length > 0) && - !(val instanceof Buffer); -} diff --git a/node_modules/mongoose/lib/helpers/cursor/eachAsync.js b/node_modules/mongoose/lib/helpers/cursor/eachAsync.js deleted file mode 100644 index 5ab0f5785fcb5b9a3821d1a0339ff53105d05448..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/cursor/eachAsync.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const async = require('async'); -const utils = require('../../utils'); - -/** - * Execute `fn` for every document in the cursor. If `fn` returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * - * @param {Function} next the thunk to call to get the next document - * @param {Function} fn - * @param {Object} options - * @param {Function} [callback] executed when all docs have been processed - * @return {Promise} - * @api public - * @method eachAsync - */ - -module.exports = function eachAsync(next, fn, options, callback) { - const parallel = options.parallel || 1; - - const handleNextResult = function(doc, callback) { - const promise = fn(doc); - if (promise && typeof promise.then === 'function') { - promise.then( - function() { callback(null); }, - function(error) { callback(error || new Error('`eachAsync()` promise rejected without error')); }); - } else { - callback(null); - } - }; - - const iterate = function(callback) { - let drained = false; - const nextQueue = async.queue(function(task, cb) { - if (drained) return cb(); - next(function(err, doc) { - if (err) return cb(err); - if (!doc) drained = true; - cb(null, doc); - }); - }, 1); - - const getAndRun = function(cb) { - nextQueue.push({}, function(err, doc) { - if (err) return cb(err); - if (!doc) return cb(); - handleNextResult(doc, function(err) { - if (err) return cb(err); - // Make sure to clear the stack re: gh-4697 - setTimeout(function() { - getAndRun(cb); - }, 0); - }); - }); - }; - - async.times(parallel, function(n, cb) { - getAndRun(cb); - }, callback); - }; - - return utils.promiseOrCallback(callback, cb => { - iterate(cb); - }); -}; diff --git a/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js b/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js deleted file mode 100644 index 0405b5b930d6fc0c8bc884e6834e76f7a71b4207..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function cleanModifiedSubpaths(doc, path, options) { - options = options || {}; - const skipDocArrays = options.skipDocArrays; - - let deleted = 0; - for (const modifiedPath of Object.keys(doc.$__.activePaths.states.modify)) { - if (skipDocArrays) { - const schemaType = doc.schema.path(modifiedPath); - if (schemaType && schemaType.$isMongooseDocumentArray) { - continue; - } - } - if (modifiedPath.indexOf(path + '.') === 0) { - delete doc.$__.activePaths.states.modify[modifiedPath]; - ++deleted; - } - } - return deleted; -}; diff --git a/node_modules/mongoose/lib/helpers/document/compile.js b/node_modules/mongoose/lib/helpers/document/compile.js deleted file mode 100644 index f6a5a5223bef3c2b22b6de2d12c83d4641614876..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/document/compile.js +++ /dev/null @@ -1,147 +0,0 @@ -'use strict'; - -const get = require('../../helpers/get'); -const getSymbol = require('../../helpers/symbols').getSymbol; -const utils = require('../../utils'); - -let Document; - -/*! - * exports - */ - -exports.compile = compile; -exports.defineKey = defineKey; - -/*! - * Compiles schemas. - */ - -function compile(tree, proto, prefix, options) { - Document = Document || require('../../document'); - const keys = Object.keys(tree); - const len = keys.length; - let limb; - let key; - - for (let i = 0; i < len; ++i) { - key = keys[i]; - limb = tree[key]; - - const hasSubprops = utils.isPOJO(limb) && Object.keys(limb).length && - (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type)); - const subprops = hasSubprops ? limb : null; - - defineKey(key, subprops, proto, prefix, keys, options); - } -} - -/*! - * Defines the accessor named prop on the incoming prototype. - */ - -function defineKey(prop, subprops, prototype, prefix, keys, options) { - Document = Document || require('../../document'); - const path = (prefix ? prefix + '.' : '') + prop; - prefix = prefix || ''; - - if (subprops) { - Object.defineProperty(prototype, prop, { - enumerable: true, - configurable: true, - get: function() { - const _this = this; - if (!this.$__.getters) { - this.$__.getters = {}; - } - - if (!this.$__.getters[path]) { - const nested = Object.create(Document.prototype, getOwnPropertyDescriptors(this)); - - // save scope for nested getters/setters - if (!prefix) { - nested.$__.scope = this; - } - nested.$__.nestedPath = path; - - Object.defineProperty(nested, 'schema', { - enumerable: false, - configurable: true, - writable: false, - value: prototype.schema - }); - - Object.defineProperty(nested, 'toObject', { - enumerable: false, - configurable: true, - writable: false, - value: function() { - return utils.clone(_this.get(path, null, { - virtuals: get(this, 'schema.options.toObject.virtuals', null) - })); - } - }); - - Object.defineProperty(nested, 'toJSON', { - enumerable: false, - configurable: true, - writable: false, - value: function() { - return _this.get(path, null, { - virtuals: get(_this, 'schema.options.toJSON.virtuals', null) - }); - } - }); - - Object.defineProperty(nested, '$__isNested', { - enumerable: false, - configurable: true, - writable: false, - value: true - }); - - compile(subprops, nested, path, options); - this.$__.getters[path] = nested; - } - - return this.$__.getters[path]; - }, - set: function(v) { - if (v instanceof Document) { - v = v.toObject({ transform: false }); - } - const doc = this.$__.scope || this; - return doc.$set(path, v); - } - }); - } else { - Object.defineProperty(prototype, prop, { - enumerable: true, - configurable: true, - get: function() { - return this[getSymbol].call(this.$__.scope || this, path); - }, - set: function(v) { - return this.$set.call(this.$__.scope || this, path, v); - } - }); - } -} - -// gets descriptors for all properties of `object` -// makes all properties non-enumerable to match previous behavior to #2211 -function getOwnPropertyDescriptors(object) { - const result = {}; - - Object.getOwnPropertyNames(object).forEach(function(key) { - result[key] = Object.getOwnPropertyDescriptor(object, key); - // Assume these are schema paths, ignore them re: #5470 - if (result[key].get) { - delete result[key]; - return; - } - result[key].enumerable = ['isNew', '$__', 'errors', '_doc'].indexOf(key) === -1; - }); - - return result; -} diff --git a/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js b/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js deleted file mode 100644 index 0e115b0ba037cf14dfca9d753185ae6a471143e7..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -const get = require('../get'); - -/*! - * Like `schema.path()`, except with a document, because impossible to - * determine path type without knowing the embedded discriminator key. - */ - -module.exports = function getEmbeddedDiscriminatorPath(doc, path, options) { - options = options || {}; - const typeOnly = options.typeOnly; - const parts = path.split('.'); - let schema = null; - let type = 'adhocOrUndefined'; - - for (let i = 0; i < parts.length; ++i) { - const subpath = parts.slice(0, i + 1).join('.'); - schema = doc.schema.path(subpath); - if (schema == null) { - continue; - } - type = doc.schema.pathType(subpath); - if ((schema.$isSingleNested || schema.$isMongooseDocumentArrayElement) && - schema.schema.discriminators != null) { - const discriminators = schema.schema.discriminators; - const discriminatorKey = doc.get(subpath + '.' + - get(schema, 'schema.options.discriminatorKey')); - if (discriminatorKey == null || discriminators[discriminatorKey] == null) { - continue; - } - const rest = parts.slice(i + 1).join('.'); - schema = discriminators[discriminatorKey].path(rest); - if (schema != null) { - type = discriminators[discriminatorKey].pathType(rest); - break; - } - } - } - - // Are we getting the whole schema or just the type, 'real', 'nested', etc. - return typeOnly ? type : schema; -}; diff --git a/node_modules/mongoose/lib/helpers/get.js b/node_modules/mongoose/lib/helpers/get.js deleted file mode 100644 index dcb3881f7139f0225ecb67b3ac52c4aed4363e7d..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/get.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -/*! - * Simplified lodash.get to work around the annoying null quirk. See: - * https://github.com/lodash/lodash/issues/3659 - */ - -module.exports = function get(obj, path, def) { - const parts = path.split('.'); - let rest = path; - let cur = obj; - for (const part of parts) { - if (cur == null) { - return def; - } - - // `lib/cast.js` depends on being able to get dotted paths in updates, - // like `{ $set: { 'a.b': 42 } }` - if (cur[rest] != null) { - return cur[rest]; - } - - cur = getProperty(cur, part); - - rest = rest.substr(part.length + 1); - } - - return cur == null ? def : cur; -}; - -function getProperty(obj, prop) { - if (obj == null) { - return obj; - } - if (obj instanceof Map) { - return obj.get(prop); - } - return obj[prop]; -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/immediate.js b/node_modules/mongoose/lib/helpers/immediate.js deleted file mode 100644 index ddb70607a1f4dbadb2ccedaec2278db0036007ff..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/immediate.js +++ /dev/null @@ -1,12 +0,0 @@ -/*! - * Centralize this so we can more easily work around issues with people - * stubbing out `process.nextTick()` in tests using sinon: - * https://github.com/sinonjs/lolex#automatically-incrementing-mocked-time - * See gh-6074 - */ - -'use strict'; - -module.exports = function immediate(cb) { - return process.nextTick(cb); -}; diff --git a/node_modules/mongoose/lib/helpers/model/applyHooks.js b/node_modules/mongoose/lib/helpers/model/applyHooks.js deleted file mode 100644 index 04605785b705701ce5a3ab80f8c522f558b6e054..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/model/applyHooks.js +++ /dev/null @@ -1,122 +0,0 @@ -'use strict'; - -const symbols = require('../../schema/symbols'); -const utils = require('../../utils'); - -/*! - * ignore - */ - -module.exports = applyHooks; - -/*! - * ignore - */ - -applyHooks.middlewareFunctions = [ - 'save', - 'validate', - 'remove', - 'updateOne', - 'init' -]; - -/*! - * Register hooks for this model - * - * @param {Model} model - * @param {Schema} schema - */ - -function applyHooks(model, schema, options) { - options = options || {}; - - const kareemOptions = { - useErrorHandlers: true, - numCallbackParams: 1, - nullResultByDefault: true, - contextParameter: true - }; - const objToDecorate = options.decorateDoc ? model : model.prototype; - - model.$appliedHooks = true; - for (let i = 0; i < schema.childSchemas.length; ++i) { - const childModel = schema.childSchemas[i].model; - if (childModel.$appliedHooks) { - continue; - } - applyHooks(childModel, schema.childSchemas[i].schema, options); - if (childModel.discriminators != null) { - const keys = Object.keys(childModel.discriminators); - for (let j = 0; j < keys.length; ++j) { - applyHooks(childModel.discriminators[keys[j]], - childModel.discriminators[keys[j]].schema, options); - } - } - } - - // Built-in hooks rely on hooking internal functions in order to support - // promises and make it so that `doc.save.toString()` provides meaningful - // information. - - const middleware = schema.s.hooks. - filter(hook => { - if (hook.name === 'updateOne') { - return !!hook['document']; - } - if (hook.name === 'remove') { - return hook['document'] == null || !!hook['document']; - } - return true; - }). - filter(hook => { - // If user has overwritten the method, don't apply built-in middleware - if (schema.methods[hook.name]) { - return !hook.fn[symbols.builtInMiddleware]; - } - - return true; - }); - - model._middleware = middleware; - - objToDecorate.$__save = middleware. - createWrapper('save', objToDecorate.$__save, null, kareemOptions); - objToDecorate.$__validate = middleware. - createWrapper('validate', objToDecorate.$__validate, null, kareemOptions); - objToDecorate.$__remove = middleware. - createWrapper('remove', objToDecorate.$__remove, null, kareemOptions); - objToDecorate.$__init = middleware. - createWrapperSync('init', objToDecorate.$__init, null, kareemOptions); - - // Support hooks for custom methods - const customMethods = Object.keys(schema.methods); - const customMethodOptions = Object.assign({}, kareemOptions, { - // Only use `checkForPromise` for custom methods, because mongoose - // query thunks are not as consistent as I would like about returning - // a nullish value rather than the query. If a query thunk returns - // a query, `checkForPromise` causes infinite recursion - checkForPromise: true - }); - for (const method of customMethods) { - if (!middleware.hasHooks(method)) { - // Don't wrap if there are no hooks for the custom method to avoid - // surprises. Also, `createWrapper()` enforces consistent async, - // so wrapping a sync method would break it. - continue; - } - const originalMethod = objToDecorate[method]; - objToDecorate[method] = function() { - const args = Array.prototype.slice.call(arguments); - const cb = utils.last(args); - const argsWithoutCallback = typeof cb === 'function' ? - args.slice(0, args.length - 1) : args; - return utils.promiseOrCallback(cb, callback => { - return this[`$__${method}`].apply(this, - argsWithoutCallback.concat([callback])); - }, model.events); - }; - objToDecorate[`$__${method}`] = middleware. - createWrapper(method, originalMethod, null, customMethodOptions); - } -} diff --git a/node_modules/mongoose/lib/helpers/model/applyMethods.js b/node_modules/mongoose/lib/helpers/model/applyMethods.js deleted file mode 100644 index 5a9cf394147acc7356f32196cf10f9a9ed11124f..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/model/applyMethods.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -const get = require('../get'); - -/*! - * Register methods for this model - * - * @param {Model} model - * @param {Schema} schema - */ - -module.exports = function applyMethods(model, schema) { - function apply(method, schema) { - Object.defineProperty(model.prototype, method, { - get: function() { - const h = {}; - for (const k in schema.methods[method]) { - h[k] = schema.methods[method][k].bind(this); - } - return h; - }, - configurable: true - }); - } - for (const method of Object.keys(schema.methods)) { - const fn = schema.methods[method]; - if (schema.tree.hasOwnProperty(method)) { - throw new Error('You have a method and a property in your schema both ' + - 'named "' + method + '"'); - } - if (schema.reserved[method] && - !get(schema, `methodOptions.${method}.suppressWarning`, false)) { - console.warn(`mongoose: the method name "${method}" is used by mongoose ` + - 'internally, overwriting it may cause bugs. If you\'re sure you know ' + - 'what you\'re doing, you can suppress this error by using ' + - `\`schema.method('${method}', fn, { suppressWarning: true })\`.`); - } - if (typeof fn === 'function') { - model.prototype[method] = fn; - } else { - apply(method, schema); - } - } - - // Recursively call `applyMethods()` on child schemas - model.$appliedMethods = true; - for (let i = 0; i < schema.childSchemas.length; ++i) { - if (schema.childSchemas[i].model.$appliedMethods) { - continue; - } - applyMethods(schema.childSchemas[i].model, schema.childSchemas[i].schema); - } -}; diff --git a/node_modules/mongoose/lib/helpers/model/applyStatics.js b/node_modules/mongoose/lib/helpers/model/applyStatics.js deleted file mode 100644 index 3b9501e04282a79d43c14a38dc491e27a7efa765..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/model/applyStatics.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -/*! - * Register statics for this model - * @param {Model} model - * @param {Schema} schema - */ -module.exports = function applyStatics(model, schema) { - for (const i in schema.statics) { - model[i] = schema.statics[i]; - } -}; diff --git a/node_modules/mongoose/lib/helpers/model/castBulkWrite.js b/node_modules/mongoose/lib/helpers/model/castBulkWrite.js deleted file mode 100644 index ff1324d547d200794a9adafaeef746a9b93d315c..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/model/castBulkWrite.js +++ /dev/null @@ -1,136 +0,0 @@ -'use strict'; - -const applyTimestampsToChildren = require('../update/applyTimestampsToChildren'); -const applyTimestampsToUpdate = require('../update/applyTimestampsToUpdate'); -const cast = require('../../cast'); -const castUpdate = require('../query/castUpdate'); -const setDefaultsOnInsert = require('../setDefaultsOnInsert'); - -/*! - * Given a model and a bulkWrite op, return a thunk that handles casting and - * validating the individual op. - */ - -module.exports = function castBulkWrite(model, op) { - const now = model.base.now(); - - if (op['insertOne']) { - return (callback) => { - const doc = new model(op['insertOne']['document']); - if (model.schema.options.timestamps != null) { - doc.initializeTimestamps(); - } - - op['insertOne']['document'] = doc; - op['insertOne']['document'].validate({ __noPromise: true }, function(error) { - if (error) { - return callback(error, null); - } - callback(null); - }); - }; - } else if (op['updateOne']) { - op = op['updateOne']; - return (callback) => { - try { - op['filter'] = cast(model.schema, op['filter']); - op['update'] = castUpdate(model.schema, op['update'], { - strict: model.schema.options.strict, - overwrite: false - }); - if (op.setDefaultsOnInsert) { - setDefaultsOnInsert(op['filter'], model.schema, op['update'], { - setDefaultsOnInsert: true, - upsert: op.upsert - }); - } - if (model.schema.$timestamps != null) { - const createdAt = model.schema.$timestamps.createdAt; - const updatedAt = model.schema.$timestamps.updatedAt; - applyTimestampsToUpdate(now, createdAt, updatedAt, op['update'], {}); - } - applyTimestampsToChildren(now, op['update'], model.schema); - } catch (error) { - return callback(error, null); - } - - callback(null); - }; - } else if (op['updateMany']) { - op = op['updateMany']; - return (callback) => { - try { - op['filter'] = cast(model.schema, op['filter']); - op['update'] = castUpdate(model.schema, op['update'], { - strict: model.schema.options.strict, - overwrite: false - }); - if (op.setDefaultsOnInsert) { - setDefaultsOnInsert(op['filter'], model.schema, op['update'], { - setDefaultsOnInsert: true, - upsert: op.upsert - }); - } - if (model.schema.$timestamps != null) { - const createdAt = model.schema.$timestamps.createdAt; - const updatedAt = model.schema.$timestamps.updatedAt; - applyTimestampsToUpdate(now, createdAt, updatedAt, op['update'], {}); - } - applyTimestampsToChildren(now, op['update'], model.schema); - } catch (error) { - return callback(error, null); - } - - callback(null); - }; - } else if (op['replaceOne']) { - return (callback) => { - try { - op['replaceOne']['filter'] = cast(model.schema, - op['replaceOne']['filter']); - } catch (error) { - return callback(error, null); - } - - // set `skipId`, otherwise we get "_id field cannot be changed" - const doc = new model(op['replaceOne']['replacement'], null, true); - if (model.schema.options.timestamps != null) { - doc.initializeTimestamps(); - } - op['replaceOne']['replacement'] = doc; - - op['replaceOne']['replacement'].validate({ __noPromise: true }, function(error) { - if (error) { - return callback(error, null); - } - callback(null); - }); - }; - } else if (op['deleteOne']) { - return (callback) => { - try { - op['deleteOne']['filter'] = cast(model.schema, - op['deleteOne']['filter']); - } catch (error) { - return callback(error, null); - } - - callback(null); - }; - } else if (op['deleteMany']) { - return (callback) => { - try { - op['deleteMany']['filter'] = cast(model.schema, - op['deleteMany']['filter']); - } catch (error) { - return callback(error, null); - } - - callback(null); - }; - } else { - return (callback) => { - callback(new Error('Invalid op passed to `bulkWrite()`'), null); - }; - } -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/model/discriminator.js b/node_modules/mongoose/lib/helpers/model/discriminator.js deleted file mode 100644 index d63b26c10a09ca0b0d7d8c577b99c5c777e04987..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/model/discriminator.js +++ /dev/null @@ -1,172 +0,0 @@ -'use strict'; - -const defineKey = require('../document/compile').defineKey; -const get = require('../get'); -const utils = require('../../utils'); - -const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { - toJSON: true, - toObject: true, - _id: true, - id: true -}; - -/*! - * ignore - */ - -module.exports = function discriminator(model, name, schema, tiedValue, applyPlugins) { - if (!(schema && schema.instanceOfSchema)) { - throw new Error('You must pass a valid discriminator Schema'); - } - - if (model.schema.discriminatorMapping && - !model.schema.discriminatorMapping.isRoot) { - throw new Error('Discriminator "' + name + - '" can only be a discriminator of the root model'); - } - - if (applyPlugins) { - const applyPluginsToDiscriminators = get(model.base, - 'options.applyPluginsToDiscriminators', false); - // Even if `applyPluginsToDiscriminators` isn't set, we should still apply - // global plugins to schemas embedded in the discriminator schema (gh-7370) - model.base._applyPlugins(schema, { - skipTopLevel: !applyPluginsToDiscriminators - }); - } - - const key = model.schema.options.discriminatorKey; - - const baseSchemaAddition = {}; - baseSchemaAddition[key] = { - default: void 0, - select: true, - $skipDiscriminatorCheck: true - }; - baseSchemaAddition[key][model.schema.options.typeKey] = String; - model.schema.add(baseSchemaAddition); - defineKey(key, null, model.prototype, null, [key], model.schema.options); - - if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) { - throw new Error('Discriminator "' + name + - '" cannot have field with name "' + key + '"'); - } - - let value = name; - if (typeof tiedValue == 'string' && tiedValue.length) { - value = tiedValue; - } - - function merge(schema, baseSchema) { - // Retain original schema before merging base schema - schema._originalSchema = schema.clone(); - if (baseSchema.paths._id && - baseSchema.paths._id.options && - !baseSchema.paths._id.options.auto) { - const originalSchema = schema; - utils.merge(schema, originalSchema); - delete schema.paths._id; - delete schema.tree._id; - } - - // Find conflicting paths: if something is a path in the base schema - // and a nested path in the child schema, overwrite the base schema path. - // See gh-6076 - const baseSchemaPaths = Object.keys(baseSchema.paths); - const conflictingPaths = []; - for (let i = 0; i < baseSchemaPaths.length; ++i) { - if (schema.nested[baseSchemaPaths[i]]) { - conflictingPaths.push(baseSchemaPaths[i]); - } - } - - utils.merge(schema, baseSchema, { - omit: { discriminators: true, $parentSchema: true }, - omitNested: conflictingPaths.reduce((cur, path) => { - cur['tree.' + path] = true; - return cur; - }, {}) - }); - - // Clean up conflicting paths _after_ merging re: gh-6076 - for (let i = 0; i < conflictingPaths.length; ++i) { - delete schema.paths[conflictingPaths[i]]; - } - - const obj = {}; - obj[key] = { - default: value, - select: true, - set: function(newName) { - if (newName === value) { - return value; - } - throw new Error('Can\'t set discriminator key "' + key + '"'); - }, - $skipDiscriminatorCheck: true - }; - obj[key][schema.options.typeKey] = String; - schema.add(obj); - schema.discriminatorMapping = {key: key, value: value, isRoot: false}; - - if (baseSchema.options.collection) { - schema.options.collection = baseSchema.options.collection; - } - - const toJSON = schema.options.toJSON; - const toObject = schema.options.toObject; - const _id = schema.options._id; - const id = schema.options.id; - - const keys = Object.keys(schema.options); - schema.options.discriminatorKey = baseSchema.options.discriminatorKey; - - for (let i = 0; i < keys.length; ++i) { - const _key = keys[i]; - if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) { - if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) { - throw new Error('Can\'t customize discriminator option ' + _key + - ' (can only modify ' + - Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') + - ')'); - } - } - } - - schema.options = utils.clone(baseSchema.options); - if (toJSON) schema.options.toJSON = toJSON; - if (toObject) schema.options.toObject = toObject; - if (typeof _id !== 'undefined') { - schema.options._id = _id; - } - schema.options.id = id; - schema.s.hooks = model.schema.s.hooks.merge(schema.s.hooks); - - schema.plugins = Array.prototype.slice(baseSchema.plugins); - schema.callQueue = baseSchema.callQueue.concat(schema.callQueue); - delete schema._requiredpaths; // reset just in case Schema#requiredPaths() was called on either schema - } - - // merges base schema into new discriminator schema and sets new type field. - merge(schema, model.schema); - - if (!model.discriminators) { - model.discriminators = {}; - } - - if (!model.schema.discriminatorMapping) { - model.schema.discriminatorMapping = {key: key, value: null, isRoot: true}; - } - if (!model.schema.discriminators) { - model.schema.discriminators = {}; - } - - model.schema.discriminators[name] = schema; - - if (model.discriminators[name]) { - throw new Error('Discriminator with name "' + name + '" already exists'); - } - - return schema; -}; diff --git a/node_modules/mongoose/lib/helpers/once.js b/node_modules/mongoose/lib/helpers/once.js deleted file mode 100644 index 02675799c38b1bb0cf6bd67f398dd3ac1ff82784..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/once.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -module.exports = function once(fn) { - let called = false; - return function() { - if (called) { - return; - } - called = true; - return fn.apply(null, arguments); - }; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js b/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js deleted file mode 100644 index 1de37c6e8d4dfc072ed64d391b10cf00f11a8772..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -module.exports = assignRawDocsToIdStructure; - -/*! - * Assign `vals` returned by mongo query to the `rawIds` - * structure returned from utils.getVals() honoring - * query sort order if specified by user. - * - * This can be optimized. - * - * Rules: - * - * if the value of the path is not an array, use findOne rules, else find. - * for findOne the results are assigned directly to doc path (including null results). - * for find, if user specified sort order, results are assigned directly - * else documents are put back in original order of array if found in results - * - * @param {Array} rawIds - * @param {Array} vals - * @param {Boolean} sort - * @api private - */ - -function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, recursed) { - // honor user specified sort order - const newOrder = []; - const sorting = options.sort && rawIds.length > 1; - let doc; - let sid; - let id; - - for (let i = 0; i < rawIds.length; ++i) { - id = rawIds[i]; - - if (Array.isArray(id)) { - // handle [ [id0, id2], [id3] ] - assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, true); - newOrder.push(id); - continue; - } - - if (id === null && !sorting) { - // keep nulls for findOne unless sorting, which always - // removes them (backward compat) - newOrder.push(id); - continue; - } - - sid = String(id); - - doc = resultDocs[sid]; - // If user wants separate copies of same doc, use this option - if (options.clone) { - doc = doc.constructor.hydrate(doc._doc); - } - - if (recursed) { - if (doc) { - if (sorting) { - newOrder[resultOrder[sid]] = doc; - } else { - newOrder.push(doc); - } - } else { - newOrder.push(id); - } - } else { - // apply findOne behavior - if document in results, assign, else assign null - newOrder[i] = doc || null; - } - } - - rawIds.length = 0; - if (newOrder.length) { - // reassign the documents based on corrected order - - // forEach skips over sparse entries in arrays so we - // can safely use this to our advantage dealing with sorted - // result sets too. - newOrder.forEach(function(doc, i) { - rawIds[i] = doc; - }); - } -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js b/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js deleted file mode 100644 index 5231942721876ac9db5aa23fcfebcb6ebe224791..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js +++ /dev/null @@ -1,181 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -const Mixed = require('../../schema/mixed'); -const get = require('../get'); -const leanPopulateMap = require('./leanPopulateMap'); -const mpath = require('mpath'); - -/*! - * @param {Schema} schema - * @param {Object} doc POJO - * @param {string} path - */ - -module.exports = function getSchemaTypes(schema, doc, path) { - const pathschema = schema.path(path); - const topLevelDoc = doc; - - if (pathschema) { - return pathschema; - } - - function search(parts, schema, subdoc, nestedPath) { - let p = parts.length + 1; - let foundschema; - let trypath; - - while (p--) { - trypath = parts.slice(0, p).join('.'); - foundschema = schema.path(trypath); - - if (foundschema == null) { - continue; - } - - if (foundschema.caster) { - // array of Mixed? - if (foundschema.caster instanceof Mixed) { - return foundschema.caster; - } - - let schemas = null; - if (doc != null && foundschema.schema != null && foundschema.schema.discriminators != null) { - const discriminators = foundschema.schema.discriminators; - const discriminatorKeyPath = trypath + '.' + - foundschema.schema.options.discriminatorKey; - const keys = subdoc ? mpath.get(discriminatorKeyPath, subdoc) || [] : []; - schemas = Object.keys(discriminators). - reduce(function(cur, discriminator) { - if (keys.indexOf(discriminator) !== -1) { - cur.push(discriminators[discriminator]); - } - return cur; - }, []); - } - - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length && foundschema.schema) { - let ret; - if (parts[p] === '$') { - if (p + 1 === parts.length) { - // comments.$ - return foundschema; - } - // comments.$.comments.$.title - ret = search( - parts.slice(p + 1), - schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - return ret; - } - - if (schemas != null && schemas.length > 0) { - ret = []; - for (let i = 0; i < schemas.length; ++i) { - const _ret = search( - parts.slice(p), - schemas[i], - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - if (_ret != null) { - _ret.$isUnderneathDocArray = _ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - if (_ret.$isUnderneathDocArray) { - ret.$isUnderneathDocArray = true; - } - ret.push(_ret); - } - } - return ret; - } else { - ret = search( - parts.slice(p), - foundschema.schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - - return ret; - } - } - } - - const fullPath = nestedPath.concat([trypath]).join('.'); - if (topLevelDoc.$__ && topLevelDoc.populated(fullPath) && p < parts.length) { - const schema = get(doc.$__.populated[fullPath], 'options.model.schema'); - if (schema != null) { - const ret = search( - parts.slice(p), - schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !schema.$isSingleNested; - } - - return ret; - } - } - - const _val = get(topLevelDoc, trypath); - if (_val != null) { - const model = Array.isArray(_val) && _val.length > 0 ? - leanPopulateMap.get(_val[0]) : - leanPopulateMap.get(_val); - // Populated using lean, `leanPopulateMap` value is the foreign model - const schema = model != null ? model.schema : null; - if (schema != null) { - const ret = search( - parts.slice(p), - schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !schema.$isSingleNested; - } - - return ret; - } - } - - return foundschema; - } - } - - // look for arrays - const parts = path.split('.'); - for (let i = 0; i < parts.length; ++i) { - if (parts[i] === '$') { - // Re: gh-5628, because `schema.path()` doesn't take $ into account. - parts[i] = '0'; - } - } - return search(parts, schema, doc, []); -}; diff --git a/node_modules/mongoose/lib/helpers/populate/getVirtual.js b/node_modules/mongoose/lib/helpers/populate/getVirtual.js deleted file mode 100644 index dd2644d51502869f9a0555f137b038852e6e1d2e..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/populate/getVirtual.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -module.exports = getVirtual; - -/*! - * ignore - */ - -function getVirtual(schema, name) { - if (schema.virtuals[name]) { - return schema.virtuals[name]; - } - const parts = name.split('.'); - let cur = ''; - let nestedSchemaPath = ''; - for (let i = 0; i < parts.length; ++i) { - cur += (cur.length > 0 ? '.' : '') + parts[i]; - if (schema.virtuals[cur]) { - if (i === parts.length - 1) { - schema.virtuals[cur].$nestedSchemaPath = nestedSchemaPath; - return schema.virtuals[cur]; - } - continue; - } - - if (schema.nested[cur]) { - continue; - } - - if (schema.paths[cur] && schema.paths[cur].schema) { - schema = schema.paths[cur].schema; - const rest = parts.slice(i + 1).join('.'); - - if (schema.virtuals[rest]) { - if (i === parts.length - 2) { - schema.virtuals[rest].$nestedSchemaPath = - [nestedSchemaPath, cur].filter(v => !!v).join('.'); - return schema.virtuals[rest]; - } - continue; - } - - if (i + 1 < parts.length && schema.discriminators) { - for (const key of Object.keys(schema.discriminators)) { - const _virtual = getVirtual(schema.discriminators[key], rest); - if (_virtual != null) { - _virtual.$nestedSchemaPath = [nestedSchemaPath, cur]. - filter(v => !!v).join('.'); - return _virtual; - } - } - } - - nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + cur; - cur = ''; - continue; - } - - return null; - } -} diff --git a/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js b/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js deleted file mode 100644 index a333124fa768f66fbd16dcf5134bf83729a55e9a..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = new WeakMap(); \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/normalizeRefPath.js b/node_modules/mongoose/lib/helpers/populate/normalizeRefPath.js deleted file mode 100644 index 233b741792a0bb16c7f3cf12896849fa40a3c0de..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/populate/normalizeRefPath.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -module.exports = function normalizeRefPath(refPath, doc, populatedPath) { - if (refPath == null) { - return refPath; - } - - if (typeof refPath === 'function') { - refPath = refPath.call(doc, doc, populatedPath); - } - - // If populated path has numerics, the end `refPath` should too. For example, - // if populating `a.0.b` instead of `a.b` and `b` has `refPath = a.c`, we - // should return `a.0.c` for the refPath. - const hasNumericProp = /(\.\d+$|\.\d+\.)/g; - - if (hasNumericProp.test(populatedPath)) { - const chunks = populatedPath.split(hasNumericProp); - - if (chunks[chunks.length - 1] === '') { - throw new Error('Can\'t populate individual element in an array'); - } - - let _refPath = ''; - let _remaining = refPath; - // 2nd, 4th, etc. will be numeric props. For example: `[ 'a', '.0.', 'b' ]` - for (let i = 0; i < chunks.length; i += 2) { - const chunk = chunks[i]; - if (_remaining.startsWith(chunk + '.')) { - _refPath += _remaining.substr(0, chunk.length) + chunks[i + 1]; - _remaining = _remaining.substr(chunk.length + 1); - } else if (i === chunks.length - 1) { - _refPath += _remaining; - _remaining = ''; - break; - } else { - throw new Error('Could not normalize ref path, chunk ' + chunk + ' not in populated path'); - } - } - - return _refPath; - } - - return refPath; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/validateRef.js b/node_modules/mongoose/lib/helpers/populate/validateRef.js deleted file mode 100644 index 9dc2b6fc641de5a92b93758f92cb2019cccf23e9..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/populate/validateRef.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const MongooseError = require('../../error/mongooseError'); -const util = require('util'); - -module.exports = validateRef; - -function validateRef(ref, path) { - if (typeof ref === 'string') { - return; - } - - if (typeof ref === 'function') { - return; - } - - throw new MongooseError('Invalid ref at path "' + path + '". Got ' + - util.inspect(ref, { depth: 0 })); -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/printJestWarning.js b/node_modules/mongoose/lib/helpers/printJestWarning.js deleted file mode 100644 index eb3a8eb7b1d69a6bec431e1e5fbe774ee75b146d..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/printJestWarning.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -if (typeof jest !== 'undefined' && typeof window !== 'undefined') { - console.warn('Mongoose: looks like you\'re trying to test a Mongoose app ' + - 'with Jest\'s default jsdom test environment. Please make sure you read ' + - 'Mongoose\'s docs on configuring Jest to test Node.js apps: ' + - 'http://mongoosejs.com/docs/jest.html'); -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js b/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js deleted file mode 100644 index 67dfb39fc6842ed4980a52892b1671f9d9531f93..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function isDefiningProjection(val) { - if (val == null) { - // `undefined` or `null` become exclusive projections - return true; - } - if (typeof val === 'object') { - // Only cases where a value does **not** define whether the whole projection - // is inclusive or exclusive are `$meta` and `$slice`. - return !('$meta' in val) && !('$slice' in val); - } - return true; -}; diff --git a/node_modules/mongoose/lib/helpers/projection/isExclusive.js b/node_modules/mongoose/lib/helpers/projection/isExclusive.js deleted file mode 100644 index 8c64bc50fe25e782d425234be4b0e22e69f9dcab..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/projection/isExclusive.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -const isDefiningProjection = require('./isDefiningProjection'); - -/*! - * ignore - */ - -module.exports = function isExclusive(projection) { - const keys = Object.keys(projection); - let ki = keys.length; - let exclude = null; - - if (ki === 1 && keys[0] === '_id') { - exclude = !!projection[keys[ki]]; - } else { - while (ki--) { - // Does this projection explicitly define inclusion/exclusion? - // Explicitly avoid `$meta` and `$slice` - if (keys[ki] !== '_id' && isDefiningProjection(projection[keys[ki]])) { - exclude = !projection[keys[ki]]; - break; - } - } - } - - return exclude; -}; diff --git a/node_modules/mongoose/lib/helpers/projection/isInclusive.js b/node_modules/mongoose/lib/helpers/projection/isInclusive.js deleted file mode 100644 index 7781d8cb79a1bc85fa58b5afa65b24cea7420e58..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/projection/isInclusive.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const isDefiningProjection = require('./isDefiningProjection'); - -/*! - * ignore - */ - -module.exports = function isInclusive(projection) { - if (projection == null) { - return false; - } - - const props = Object.keys(projection); - const numProps = props.length; - if (numProps === 0) { - return false; - } - - for (let i = 0; i < numProps; ++i) { - const prop = props[i]; - // Plus paths can't define the projection (see gh-7050) - if (prop.charAt(0) === '+') { - continue; - } - // If field is truthy (1, true, etc.) and not an object, then this - // projection must be inclusive. If object, assume its $meta, $slice, etc. - if (isDefiningProjection(projection[prop]) && !!projection[prop]) { - return true; - } - } - - return false; -}; diff --git a/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js b/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js deleted file mode 100644 index fc2592cda52d2992310c54e1d9b440a518482c2f..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const isDefiningProjection = require('./isDefiningProjection'); - -/*! - * Determines if `path` is excluded by `projection` - * - * @param {Object} projection - * @param {string} path - * @return {Boolean} - */ - -module.exports = function isPathExcluded(projection, path) { - if (path === '_id') { - return projection._id === 0; - } - - const paths = Object.keys(projection); - let type = null; - - for (const _path of paths) { - if (isDefiningProjection(projection[_path])) { - type = projection[path] === 1 ? 'inclusive' : 'exclusive'; - break; - } - } - - if (type === 'inclusive') { - return projection[path] !== 1; - } - if (type === 'exclusive') { - return projection[path] === 0; - } - return false; -}; diff --git a/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js b/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js deleted file mode 100644 index 8a05fc948ea89a38067ac7dcde2ff12aac5d276b..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function isPathSelectedInclusive(fields, path) { - const chunks = path.split('.'); - let cur = ''; - let j; - let keys; - let numKeys; - for (let i = 0; i < chunks.length; ++i) { - cur += cur.length ? '.' : '' + chunks[i]; - if (fields[cur]) { - keys = Object.keys(fields); - numKeys = keys.length; - for (j = 0; j < numKeys; ++j) { - if (keys[i].indexOf(cur + '.') === 0 && keys[i].indexOf(path) !== 0) { - continue; - } - } - return true; - } - } - - return false; -}; diff --git a/node_modules/mongoose/lib/helpers/query/applyQueryMiddleware.js b/node_modules/mongoose/lib/helpers/query/applyQueryMiddleware.js deleted file mode 100644 index 3a987c40392adb77871e8a1d07248b7fb1d76bc3..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/query/applyQueryMiddleware.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = applyQueryMiddleware; - -/*! - * ignore - */ - -applyQueryMiddleware.middlewareFunctions = [ - 'count', - 'countDocuments', - 'deleteMany', - 'deleteOne', - 'estimatedDocumentCount', - 'find', - 'findOne', - 'findOneAndDelete', - 'findOneAndRemove', - 'findOneAndReplace', - 'findOneAndUpdate', - 'remove', - 'replaceOne', - 'update', - 'updateMany', - 'updateOne' -]; - -/*! - * Apply query middleware - * - * @param {Query} query constructor - * @param {Model} model - */ - -function applyQueryMiddleware(Query, model) { - const kareemOptions = { - useErrorHandlers: true, - numCallbackParams: 1, - nullResultByDefault: true - }; - - const middleware = model.hooks.filter(hook => { - if (hook.name === 'updateOne') { - return hook.query == null || !!hook.query; - } - if (hook.name === 'remove') { - return !!hook.query; - } - return true; - }); - - // `update()` thunk has a different name because `_update` was already taken - Query.prototype._execUpdate = middleware.createWrapper('update', - Query.prototype._execUpdate, null, kareemOptions); - - applyQueryMiddleware.middlewareFunctions. - filter(v => v !== 'update'). - forEach(fn => { - Query.prototype[`_${fn}`] = middleware.createWrapper(fn, - Query.prototype[`_${fn}`], null, kareemOptions); - }); -} diff --git a/node_modules/mongoose/lib/helpers/query/castFilterPath.js b/node_modules/mongoose/lib/helpers/query/castFilterPath.js deleted file mode 100644 index 4cb448f16772793d044a0341f67a3ad7107adb8a..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/query/castFilterPath.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -module.exports = function castFilterPath(query, schematype, val) { - const ctx = query; - const any$conditionals = Object.keys(val).some(function(k) { - return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; - }); - - if (!any$conditionals) { - return schematype.castForQueryWrapper({ - val: val, - context: ctx - }); - } - - const ks = Object.keys(val); - - let k = ks.length; - - while (k--) { - const $cond = ks[k]; - const nested = val[$cond]; - - if ($cond === '$not') { - if (nested && schematype && !schematype.caster) { - const _keys = Object.keys(nested); - if (_keys.length && _keys[0].charAt(0) === '$') { - for (const key in nested) { - nested[key] = schematype.castForQueryWrapper({ - $conditional: key, - val: nested[key], - context: ctx - }); - } - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: ctx - }); - } - continue; - } - // cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context); - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: ctx - }); - } - } - - return val; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/castUpdate.js b/node_modules/mongoose/lib/helpers/query/castUpdate.js deleted file mode 100644 index d58fc832fb95261496f6fc3ac2ba6bab73194e8c..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/query/castUpdate.js +++ /dev/null @@ -1,428 +0,0 @@ -'use strict'; - -const CastError = require('../../error/cast'); -const StrictModeError = require('../../error/strict'); -const ValidationError = require('../../error/validation'); -const castNumber = require('../../cast/number'); -const getEmbeddedDiscriminatorPath = require('./getEmbeddedDiscriminatorPath'); -const utils = require('../../utils'); - -/*! - * Casts an update op based on the given schema - * - * @param {Schema} schema - * @param {Object} obj - * @param {Object} options - * @param {Boolean} [options.overwrite] defaults to false - * @param {Boolean|String} [options.strict] defaults to true - * @param {Query} context passed to setters - * @return {Boolean} true iff the update is non-empty - */ - -module.exports = function castUpdate(schema, obj, options, context, filter) { - if (!obj) { - return undefined; - } - - const ops = Object.keys(obj); - let i = ops.length; - const ret = {}; - let hasKeys; - let val; - let hasDollarKey = false; - const overwrite = options.overwrite; - - filter = filter || {}; - - while (i--) { - const op = ops[i]; - // if overwrite is set, don't do any of the special $set stuff - if (op[0] !== '$' && !overwrite) { - // fix up $set sugar - if (!ret.$set) { - if (obj.$set) { - ret.$set = obj.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = obj[op]; - ops.splice(i, 1); - if (!~ops.indexOf('$set')) ops.push('$set'); - } else if (op === '$set') { - if (!ret.$set) { - ret[op] = obj[op]; - } - } else { - ret[op] = obj[op]; - } - } - - // cast each value - i = ops.length; - - // if we get passed {} for the update, we still need to respect that when it - // is an overwrite scenario - if (overwrite) { - hasKeys = true; - } - - while (i--) { - const op = ops[i]; - val = ret[op]; - hasDollarKey = hasDollarKey || op.charAt(0) === '$'; - - if (val && - typeof val === 'object' && - !Buffer.isBuffer(val) && - (!overwrite || hasDollarKey)) { - hasKeys |= walkUpdatePath(schema, val, op, options, context, filter); - } else if (overwrite && ret && typeof ret === 'object') { - // if we are just using overwrite, cast the query and then we will - // *always* return the value, even if it is an empty object. We need to - // set hasKeys above because we need to account for the case where the - // user passes {} and wants to clobber the whole document - // Also, _walkUpdatePath expects an operation, so give it $set since that - // is basically what we're doing - walkUpdatePath(schema, ret, '$set', options, context, filter); - } else { - const msg = 'Invalid atomic update value for ' + op + '. ' - + 'Expected an object, received ' + typeof val; - throw new Error(msg); - } - } - - return hasKeys && ret; -}; - -/*! - * Walk each path of obj and cast its values - * according to its schema. - * - * @param {Schema} schema - * @param {Object} obj - part of a query - * @param {String} op - the atomic operator ($pull, $set, etc) - * @param {Object} options - * @param {Boolean|String} [options.strict] - * @param {Boolean} [options.omitUndefined] - * @param {Query} context - * @param {String} pref - path prefix (internal only) - * @return {Bool} true if this path has keys to update - * @api private - */ - -function walkUpdatePath(schema, obj, op, options, context, filter, pref) { - const strict = options.strict; - const prefix = pref ? pref + '.' : ''; - const keys = Object.keys(obj); - let i = keys.length; - let hasKeys = false; - let schematype; - let key; - let val; - - let aggregatedError = null; - - let useNestedStrict; - if (options.useNestedStrict === undefined) { - useNestedStrict = schema.options.useNestedStrict; - } else { - useNestedStrict = options.useNestedStrict; - } - - while (i--) { - key = keys[i]; - val = obj[key]; - - if (val && val.constructor.name === 'Object') { - // watch for embedded doc schemas - schematype = schema._getSchema(prefix + key); - if (schematype && schematype.caster && op in castOps) { - // embedded doc schema - if ('$each' in val) { - hasKeys = true; - try { - obj[key] = { - $each: castUpdateVal(schematype, val.$each, op, key, context, prefix + key) - }; - } catch (error) { - aggregatedError = _handleCastError(error, context, key, aggregatedError); - } - - if (val.$slice != null) { - obj[key].$slice = val.$slice | 0; - } - - if (val.$sort) { - obj[key].$sort = val.$sort; - } - - if (!!val.$position || val.$position === 0) { - obj[key].$position = val.$position; - } - } else { - try { - obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); - } catch (error) { - aggregatedError = _handleCastError(error, context, key, aggregatedError); - } - - if (options.omitUndefined && obj[key] === void 0) { - delete obj[key]; - continue; - } - - hasKeys = true; - } - } else if ((op === '$currentDate') || (op in castOps && schematype)) { - // $currentDate can take an object - try { - obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); - } catch (error) { - aggregatedError = _handleCastError(error, context, key, aggregatedError); - } - - if (options.omitUndefined && obj[key] === void 0) { - delete obj[key]; - continue; - } - - hasKeys = true; - } else { - const pathToCheck = (prefix + key); - const v = schema._getPathType(pathToCheck); - let _strict = strict; - if (useNestedStrict && - v && - v.schema && - 'strict' in v.schema.options) { - _strict = v.schema.options.strict; - } - - if (v.pathType === 'undefined') { - if (_strict === 'throw') { - throw new StrictModeError(pathToCheck); - } else if (_strict) { - delete obj[key]; - continue; - } - } - - // gh-2314 - // we should be able to set a schema-less field - // to an empty object literal - hasKeys |= walkUpdatePath(schema, val, op, options, context, filter, prefix + key) || - (utils.isObject(val) && Object.keys(val).length === 0); - } - } else { - const checkPath = (key === '$each' || key === '$or' || key === '$and' || key === '$in') ? - pref : prefix + key; - schematype = schema._getSchema(checkPath); - let pathDetails = schema._getPathType(checkPath); - - // If no schema type, check for embedded discriminators - if (schematype == null) { - const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, checkPath); - if (_res.schematype != null) { - schematype = _res.schematype; - pathDetails = _res.type; - } - } - - let isStrict = strict; - if (useNestedStrict && - pathDetails && - pathDetails.schema && - 'strict' in pathDetails.schema.options) { - isStrict = pathDetails.schema.options.strict; - } - - const skip = isStrict && - !schematype && - !/real|nested/.test(pathDetails.pathType); - - if (skip) { - // Even if strict is `throw`, avoid throwing an error because of - // virtuals because of #6731 - if (isStrict === 'throw' && schema.virtuals[checkPath] == null) { - throw new StrictModeError(prefix + key); - } else { - delete obj[key]; - } - } else { - // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking - // improving this. - if (op === '$rename') { - hasKeys = true; - continue; - } - - try { - obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); - } catch (error) { - aggregatedError = _handleCastError(error, context, key, aggregatedError); - } - - if (Array.isArray(obj[key]) && (op === '$addToSet' || op === '$push') && key !== '$each') { - if (schematype && schematype.caster && !schematype.caster.$isMongooseArray) { - obj[key] = { $each: obj[key] }; - } - } - - if (options.omitUndefined && obj[key] === void 0) { - delete obj[key]; - continue; - } - - hasKeys = true; - } - } - } - - if (aggregatedError != null) { - throw aggregatedError; - } - - return hasKeys; -} - -/*! - * ignore - */ - -function _handleCastError(error, query, key, aggregatedError) { - if (typeof query !== 'object' || !query.options.multipleCastError) { - throw error; - } - aggregatedError = aggregatedError || new ValidationError(); - aggregatedError.addError(key, error); - return aggregatedError; -} - -/*! - * These operators should be cast to numbers instead - * of their path schema type. - */ - -const numberOps = { - $pop: 1, - $inc: 1 -}; - -/*! - * These ops require no casting because the RHS doesn't do anything. - */ - -const noCastOps = { - $unset: 1 -}; - -/*! - * These operators require casting docs - * to real Documents for Update operations. - */ - -const castOps = { - $push: 1, - $addToSet: 1, - $set: 1, - $setOnInsert: 1 -}; - -/*! - * ignore - */ - -const overwriteOps = { - $set: 1, - $setOnInsert: 1 -}; - -/*! - * Casts `val` according to `schema` and atomic `op`. - * - * @param {SchemaType} schema - * @param {Object} val - * @param {String} op - the atomic operator ($pull, $set, etc) - * @param {String} $conditional - * @param {Query} context - * @api private - */ - -function castUpdateVal(schema, val, op, $conditional, context, path) { - if (!schema) { - // non-existing schema path - if (op in numberOps) { - try { - return castNumber(val); - } catch (err) { - throw new CastError('number', val, path); - } - } - return val; - } - - const cond = schema.caster && op in castOps && - (utils.isObject(val) || Array.isArray(val)); - if (cond && op !== '$set') { - // Cast values for ops that add data to MongoDB. - // Ensures embedded documents get ObjectIds etc. - const tmp = schema.cast(Array.isArray(val) ? val : [val]); - if (Array.isArray(val)) { - val = tmp; - } else if (Array.isArray(tmp)) { - val = tmp[0]; - } else { - val = tmp; - } - return val; - } else if (cond && op === '$set') { - return schema.cast(val); - } - - if (op in noCastOps) { - return val; - } - if (op in numberOps) { - // Null and undefined not allowed for $pop, $inc - if (val == null) { - throw new CastError('number', val, schema.path); - } - if (op === '$inc') { - // Support `$inc` with long, int32, etc. (gh-4283) - return schema.castForQueryWrapper({ - val: val, - context: context - }); - } - try { - return castNumber(val); - } catch (error) { - throw new CastError('number', val, schema.path); - } - } - if (op === '$currentDate') { - if (typeof val === 'object') { - return {$type: val.$type}; - } - return Boolean(val); - } - - if (/^\$/.test($conditional)) { - return schema.castForQueryWrapper({ - $conditional: $conditional, - val: val, - context: context - }); - } - - if (overwriteOps[op]) { - return schema.castForQueryWrapper({ - val: val, - context: context, - $skipQueryCastForUpdate: val != null && schema.$isMongooseArray && schema.$parentSchema - }); - } - - return schema.castForQueryWrapper({ val: val, context: context }); -} diff --git a/node_modules/mongoose/lib/helpers/query/completeMany.js b/node_modules/mongoose/lib/helpers/query/completeMany.js deleted file mode 100644 index aabe59632dfda77425ebf0d0789780707477ffb8..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/query/completeMany.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -const helpers = require('../../queryhelpers'); - -module.exports = completeMany; - -/*! - * Given a model and an array of docs, hydrates all the docs to be instances - * of the model. Used to initialize docs returned from the db from `find()` - * - * @param {Model} model - * @param {Array} docs - * @param {Object} fields the projection used, including `select` from schemas - * @param {Object} userProvidedFields the user-specified projection - * @param {Object} opts - * @param {Array} [opts.populated] - * @param {ClientSession} [opts.session] - * @param {Function} callback - */ - -function completeMany(model, docs, fields, userProvidedFields, opts, callback) { - const arr = []; - let count = docs.length; - const len = count; - let error = null; - - function init(_error) { - if (_error != null) { - error = error || _error; - } - if (error != null) { - --count || process.nextTick(() => callback(error)); - return; - } - --count || process.nextTick(() => callback(error, arr)); - } - - for (let i = 0; i < len; ++i) { - arr[i] = helpers.createModel(model, docs[i], fields, userProvidedFields); - try { - arr[i].init(docs[i], opts, init); - } catch (error) { - init(error); - } - arr[i].$session(opts.session); - } -} diff --git a/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js b/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js deleted file mode 100644 index 4d74864e50f7dc1b44e9c60545f25fa3257cb7a2..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -const get = require('../get'); - -/*! - * Like `schema.path()`, except with a document, because impossible to - * determine path type without knowing the embedded discriminator key. - */ - -module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, path) { - const parts = path.split('.'); - let schematype = null; - let type = 'adhocOrUndefined'; - - filter = filter || {}; - update = update || {}; - - for (let i = 0; i < parts.length; ++i) { - const subpath = parts.slice(0, i + 1).join('.'). - replace(/\.\$\./i, '.0.').replace(/\.\$$/, '.0'); - schematype = schema.path(subpath); - if (schematype == null) { - continue; - } - type = schema.pathType(subpath); - if ((schematype.$isSingleNested || schematype.$isMongooseDocumentArrayElement) && - schematype.schema.discriminators != null) { - const discriminators = schematype.schema.discriminators; - const discriminatorValuePath = subpath + '.' + - get(schematype, 'schema.options.discriminatorKey'); - const discriminatorFilterPath = - discriminatorValuePath.replace(/\.\d+\./, '.'); - let discriminatorKey = null; - if (discriminatorValuePath in filter) { - discriminatorKey = filter[discriminatorValuePath]; - } - if (discriminatorFilterPath in filter) { - discriminatorKey = filter[discriminatorFilterPath]; - } - if (discriminatorKey == null || discriminators[discriminatorKey] == null) { - continue; - } - const rest = parts.slice(i + 1).join('.'); - schematype = discriminators[discriminatorKey].path(rest); - if (schematype != null) { - type = discriminators[discriminatorKey]._getPathType(rest); - break; - } - } - } - - return { type: type, schematype: schematype }; -}; diff --git a/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js b/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js deleted file mode 100644 index fb831dab481c838040fea2c23bc9a2e7c9149999..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function(obj) { - const keys = Object.keys(obj); - const len = keys.length; - for (let i = 0; i < len; ++i) { - if (keys[i].charAt(0) === '$') { - return true; - } - } - return false; -}; diff --git a/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js b/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js deleted file mode 100644 index 15f7e99eaf0cdcdf13700b75fa0b1e180d01fcb1..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function selectPopulatedFields(query) { - const opts = query._mongooseOptions; - - if (opts.populate != null) { - const paths = Object.keys(opts.populate); - const userProvidedFields = query._userProvidedFields || {}; - if (query.selectedInclusively()) { - for (let i = 0; i < paths.length; ++i) { - if (!isPathInFields(userProvidedFields, paths[i])) { - query.select(paths[i]); - } else if (userProvidedFields[paths[i]] === 0) { - delete query._fields[paths[i]]; - } - } - } else if (query.selectedExclusively()) { - for (let i = 0; i < paths.length; ++i) { - if (userProvidedFields[paths[i]] == null) { - delete query._fields[paths[i]]; - } - } - } - } -}; - -/*! - * ignore - */ - -function isPathInFields(userProvidedFields, path) { - const pieces = path.split('.'); - const len = pieces.length; - let cur = pieces[0]; - for (let i = 1; i < len; ++i) { - if (userProvidedFields[cur] != null) { - return true; - } - cur += '.' + pieces[i]; - } - return userProvidedFields[cur] != null; -} diff --git a/node_modules/mongoose/lib/helpers/query/wrapThunk.js b/node_modules/mongoose/lib/helpers/query/wrapThunk.js deleted file mode 100644 index 0005c330c44a3eb2f0cfc3eaa789ab24ca55fed1..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/query/wrapThunk.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -/*! - * A query thunk is the function responsible for sending the query to MongoDB, - * like `Query#_findOne()` or `Query#_execUpdate()`. The `Query#exec()` function - * calls a thunk. The term "thunk" here is the traditional Node.js definition: - * a function that takes exactly 1 parameter, a callback. - * - * This function defines common behavior for all query thunks. - */ - -module.exports = function wrapThunk(fn) { - return function _wrappedThunk(cb) { - ++this._executionCount; - - fn.call(this, cb); - }; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js b/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js deleted file mode 100644 index 168156db11744c749342b3701efd66579ac6a0f4..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const get = require('../get'); - -module.exports = function applyWriteConcern(schema, options) { - const writeConcern = get(schema, 'options.writeConcern', {}); - if (!('w' in options) && writeConcern.w != null) { - options.w = writeConcern.w; - } - if (!('j' in options) && writeConcern.j != null) { - options.j = writeConcern.j; - } - if (!('wtimeout' in options) && writeConcern.wtimeout != null) { - options.wtimeout = writeConcern.wtimeout; - } -}; diff --git a/node_modules/mongoose/lib/helpers/schema/getIndexes.js b/node_modules/mongoose/lib/helpers/schema/getIndexes.js deleted file mode 100644 index 43b82e7c2d132b110ad029f914ce6a9801aa1ff4..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/schema/getIndexes.js +++ /dev/null @@ -1,124 +0,0 @@ -'use strict'; - -const get = require('../get'); -const utils = require('../../utils'); - -/*! - * Gather all indexes defined in the schema, including single nested, - * document arrays, and embedded discriminators. - */ - -module.exports = function getIndexes(schema) { - let indexes = []; - const schemaStack = new WeakMap(); - const indexTypes = schema.constructor.indexTypes; - - const collectIndexes = function(schema, prefix) { - // Ignore infinitely nested schemas, if we've already seen this schema - // along this path there must be a cycle - if (schemaStack.has(schema)) { - return; - } - schemaStack.set(schema, true); - - prefix = prefix || ''; - const keys = Object.keys(schema.paths); - const length = keys.length; - - for (let i = 0; i < length; ++i) { - const key = keys[i]; - const path = schema.paths[key]; - - if (path.$isMongooseDocumentArray || path.$isSingleNested) { - if (get(path, 'options.excludeIndexes') !== true && - get(path, 'schemaOptions.excludeIndexes') !== true) { - collectIndexes(path.schema, prefix + key + '.'); - } - - if (path.schema.discriminators != null) { - const discriminators = path.schema.discriminators; - const discriminatorKeys = Object.keys(discriminators); - for (const discriminatorKey of discriminatorKeys) { - collectIndexes(discriminators[discriminatorKey]._originalSchema, - prefix + key + '.'); - } - } - - // Retained to minimize risk of backwards breaking changes due to - // gh-6113 - if (path.$isMongooseDocumentArray) { - continue; - } - } - - const index = path._index || (path.caster && path.caster._index); - - if (index !== false && index !== null && index !== undefined) { - const field = {}; - const isObject = utils.isObject(index); - const options = isObject ? index : {}; - const type = typeof index === 'string' ? index : - isObject ? index.type : - false; - - if (type && indexTypes.indexOf(type) !== -1) { - field[prefix + key] = type; - } else if (options.text) { - field[prefix + key] = 'text'; - delete options.text; - } else { - field[prefix + key] = 1; - } - - delete options.type; - if (!('background' in options)) { - options.background = true; - } - - indexes.push([field, options]); - } - } - - schemaStack.delete(schema); - - if (prefix) { - fixSubIndexPaths(schema, prefix); - } else { - schema._indexes.forEach(function(index) { - if (!('background' in index[1])) { - index[1].background = true; - } - }); - indexes = indexes.concat(schema._indexes); - } - }; - - collectIndexes(schema); - return indexes; - - /*! - * Checks for indexes added to subdocs using Schema.index(). - * These indexes need their paths prefixed properly. - * - * schema._indexes = [ [indexObj, options], [indexObj, options] ..] - */ - - function fixSubIndexPaths(schema, prefix) { - const subindexes = schema._indexes; - const len = subindexes.length; - for (let i = 0; i < len; ++i) { - const indexObj = subindexes[i][0]; - const keys = Object.keys(indexObj); - const klen = keys.length; - const newindex = {}; - - // use forward iteration, order matters - for (let j = 0; j < klen; ++j) { - const key = keys[j]; - newindex[prefix + key] = indexObj[key]; - } - - indexes.push([newindex, subindexes[i][1]]); - } - } -}; diff --git a/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js b/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js deleted file mode 100644 index 1551b7c10f34fa77c68805f4867633fb47e229c0..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -module.exports = handleTimestampOption; - -/*! - * ignore - */ - -function handleTimestampOption(arg, prop) { - if (arg == null) { - return null; - } - - if (typeof arg === 'boolean') { - return prop; - } - if (typeof arg[prop] === 'boolean') { - return arg[prop] ? prop : null; - } - if (!(prop in arg)) { - return prop; - } - return arg[prop]; -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/merge.js b/node_modules/mongoose/lib/helpers/schema/merge.js deleted file mode 100644 index c1caba42b11fda1eef2bfaadbf54bd81c2299343..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/schema/merge.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -module.exports = function merge(s1, s2) { - s1.add(s2.obj); - - s1.callQueue = s1.callQueue.concat(s2.callQueue); - s1.method(s2.methods); - s1.static(s2.statics); - - for (const query in s2.query) { - s1.query[query] = s2.query[query]; - } - - for (const virtual in s2.virtuals) { - s1.virtual[virtual] = s2.virtual[virtual].clone(); - } - - s1.s.hooks.merge(s2.s.hooks, false); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/setParentPointers.js b/node_modules/mongoose/lib/helpers/schema/setParentPointers.js deleted file mode 100644 index 15e0bb6abe03e1654032aa6ffc23de66179e51ab..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/schema/setParentPointers.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -/*! - * Set `$parentSchema` on all schema types, and `$schemaType` on single - * nested docs. - * - * This is a slow path function, should only run when model is compiled - */ - -module.exports = function setParentPointers(schema, skipRecursion) { - for (const path of Object.keys(schema.paths)) { - const schemaType = schema.paths[path]; - if (schemaType.schema != null) { - Object.defineProperty(schemaType.schema, '$schemaType', { - configurable: true, - writable: false, - enumerable: false, - value: schemaType - }); - } - Object.defineProperty(schemaType, '$parentSchema', { - configurable: true, - writable: false, - enumerable: false, - value: schema - }); - } - - // `childSchemas` contains all descendant schemas, so no need to recurse - // further. - if (skipRecursion) { - return; - } - - for (const obj of schema.childSchemas) { - setParentPointers(obj.schema, true); - } -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js b/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js deleted file mode 100644 index 43642ad3b8a60c61cc072aec24a7c9dedce3d124..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js +++ /dev/null @@ -1,117 +0,0 @@ -'use strict'; - -const modifiedPaths = require('./common').modifiedPaths; - -/** - * Applies defaults to update and findOneAndUpdate operations. - * - * @param {Object} filter - * @param {Schema} schema - * @param {Object} castedDoc - * @param {Object} options - * @method setDefaultsOnInsert - * @api private - */ - -module.exports = function(filter, schema, castedDoc, options) { - const keys = Object.keys(castedDoc || {}); - const updatedKeys = {}; - const updatedValues = {}; - const numKeys = keys.length; - const modified = {}; - - let hasDollarUpdate = false; - - options = options || {}; - - if (!options.upsert || !options.setDefaultsOnInsert) { - return castedDoc; - } - - for (let i = 0; i < numKeys; ++i) { - if (keys[i].charAt(0) === '$') { - modifiedPaths(castedDoc[keys[i]], '', modified); - hasDollarUpdate = true; - } - } - - if (!hasDollarUpdate) { - modifiedPaths(castedDoc, '', modified); - } - - const paths = Object.keys(filter); - const numPaths = paths.length; - for (let i = 0; i < numPaths; ++i) { - const path = paths[i]; - const condition = filter[path]; - if (condition && typeof condition === 'object') { - const conditionKeys = Object.keys(condition); - const numConditionKeys = conditionKeys.length; - let hasDollarKey = false; - for (let j = 0; j < numConditionKeys; ++j) { - if (conditionKeys[j].charAt(0) === '$') { - hasDollarKey = true; - break; - } - } - if (hasDollarKey) { - continue; - } - } - updatedKeys[path] = true; - modified[path] = true; - } - - if (options && options.overwrite && !hasDollarUpdate) { - // Defaults will be set later, since we're overwriting we'll cast - // the whole update to a document - return castedDoc; - } - - schema.eachPath(function(path, schemaType) { - if (schemaType.$isSingleNested) { - // Only handle nested schemas 1-level deep to avoid infinite - // recursion re: https://github.com/mongodb-js/mongoose-autopopulate/issues/11 - schemaType.schema.eachPath(function(_path, _schemaType) { - if (_path === '_id' && _schemaType.auto) { - // Ignore _id if auto id so we don't create subdocs - return; - } - - const def = _schemaType.getDefault(null, true); - if (!isModified(modified, path + '.' + _path) && - typeof def !== 'undefined') { - castedDoc = castedDoc || {}; - castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; - castedDoc.$setOnInsert[path + '.' + _path] = def; - updatedValues[path + '.' + _path] = def; - } - }); - } else { - const def = schemaType.getDefault(null, true); - if (!isModified(modified, path) && typeof def !== 'undefined') { - castedDoc = castedDoc || {}; - castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; - castedDoc.$setOnInsert[path] = def; - updatedValues[path] = def; - } - } - }); - - return castedDoc; -}; - -function isModified(modified, path) { - if (modified[path]) { - return true; - } - const sp = path.split('.'); - let cur = sp[0]; - for (let i = 1; i < sp.length; ++i) { - if (modified[cur]) { - return true; - } - cur += '.' + sp[i]; - } - return false; -} diff --git a/node_modules/mongoose/lib/helpers/symbols.js b/node_modules/mongoose/lib/helpers/symbols.js deleted file mode 100644 index 22b339b13e7adb8f12e2f5dbba87a45f038f738d..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/symbols.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -exports.validatorErrorSymbol = Symbol.for('mongoose:validatorError'); - -exports.documentArrayParent = Symbol.for('mongoose:documentArrayParent'); - -exports.modelSymbol = Symbol.for('mongoose#Model'); - -exports.getSymbol = Symbol.for('mongoose#Document#get'); - -exports.objectIdSymbol = Symbol.for('mongoose#ObjectId'); \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js b/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js deleted file mode 100644 index f7fb5618d9bfd48a81c79a8680aae6cb6ca03146..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js +++ /dev/null @@ -1,173 +0,0 @@ -'use strict'; - -const handleTimestampOption = require('../schema/handleTimestampOption'); - -module.exports = applyTimestampsToChildren; - -/*! - * ignore - */ - -function applyTimestampsToChildren(now, update, schema) { - if (update == null) { - return; - } - - const keys = Object.keys(update); - let key; - let createdAt; - let updatedAt; - let timestamps; - let path; - - const hasDollarKey = keys.length && keys[0].charAt(0) === '$'; - - if (hasDollarKey) { - if (update.$push) { - for (key in update.$push) { - const $path = schema.path(key); - if (update.$push[key] && - $path && - $path.$isMongooseDocumentArray && - $path.schema.options.timestamps) { - timestamps = $path.schema.options.timestamps; - createdAt = handleTimestampOption(timestamps, 'createdAt'); - updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - if (update.$push[key].$each) { - update.$push[key].$each.forEach(function(subdoc) { - if (updatedAt != null) { - subdoc[updatedAt] = now; - } - if (createdAt != null) { - subdoc[createdAt] = now; - } - }); - } else { - if (updatedAt != null) { - update.$push[key][updatedAt] = now; - } - if (createdAt != null) { - update.$push[key][createdAt] = now; - } - } - } - } - } - if (update.$set != null) { - const keys = Object.keys(update.$set); - for (key of keys) { - // Replace positional operator `$` and array filters `$[]` and `$[.*]` - const keyToSearch = key. - replace(/\.\$(\[[^\]]*\])?\./g, '.0.'). - replace(/\.(\[[^\]]*\])?\$$/, '.0'); - path = schema.path(keyToSearch); - if (!path) { - continue; - } - if (Array.isArray(update.$set[key]) && path.$isMongooseDocumentArray) { - applyTimestampsToDocumentArray(update.$set[key], path, now); - } else if (update.$set[key] && path.$isSingleNested) { - applyTimestampsToSingleNested(update.$set[key], path, now); - } else if (path.$parentSchema !== schema && path.$parentSchema != null) { - const parentPath = path.$parentSchema.$schemaType; - - if (parentPath == null) { - continue; - } - - timestamps = parentPath.schema.options.timestamps; - createdAt = handleTimestampOption(timestamps, 'createdAt'); - updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - - if (updatedAt == null) { - continue; - } - - if (parentPath.$isSingleNested) { - // Single nested is easy - update.$set[parentPath.path + '.' + updatedAt] = now; - continue; - } - - let childPath = key.substr(parentPath.path.length + 1); - const firstDot = childPath.indexOf('.'); - - // Shouldn't happen, but if it does ignore this path - if (firstDot === -1) { - continue; - } - - childPath = childPath.substr(0, firstDot); - - update.$set[parentPath.path + '.' + childPath + '.' + updatedAt] = now; - } else if (path.schema != null && path.schema != schema) { - timestamps = path.schema.options.timestamps; - createdAt = handleTimestampOption(timestamps, 'createdAt'); - updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - - if (updatedAt != null) { - update.$set[key][updatedAt] = now; - } - if (createdAt != null) { - update.$set[key][createdAt] = now; - } - } - } - } - } else { - const keys = Object.keys(update).filter(key => !key.startsWith('$')); - for (key of keys) { - // Replace positional operator `$` and array filters `$[]` and `$[.*]` - const keyToSearch = key. - replace(/\.\$(\[[^\]]*\])?\./g, '.0.'). - replace(/\.(\[[^\]]*\])?\$$/, '.0'); - path = schema.path(keyToSearch); - if (!path) { - continue; - } - - if (Array.isArray(update[key]) && path.$isMongooseDocumentArray) { - applyTimestampsToDocumentArray(update[key], path, now); - } else if (update[key] != null && path.$isSingleNested) { - applyTimestampsToSingleNested(update[key], path, now); - } - } - } -} - -function applyTimestampsToDocumentArray(arr, schematype, now) { - const timestamps = schematype.schema.options.timestamps; - - if (!timestamps) { - return; - } - - const len = arr.length; - - const createdAt = handleTimestampOption(timestamps, 'createdAt'); - const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - for (let i = 0; i < len; ++i) { - if (updatedAt != null) { - arr[i][updatedAt] = now; - } - if (createdAt != null) { - arr[i][createdAt] = now; - } - } -} - -function applyTimestampsToSingleNested(subdoc, schematype, now) { - const timestamps = schematype.schema.options.timestamps; - if (!timestamps) { - return; - } - - const createdAt = handleTimestampOption(timestamps, 'createdAt'); - const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - if (updatedAt != null) { - subdoc[updatedAt] = now; - } - if (createdAt != null) { - subdoc[createdAt] = now; - } -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js b/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js deleted file mode 100644 index 85cef1a40e40c15791ded0d3c81b6177e1e92551..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -const get = require('../get'); - -module.exports = applyTimestampsToUpdate; - -/*! - * ignore - */ - -function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options) { - const updates = currentUpdate; - let _updates = updates; - const overwrite = get(options, 'overwrite', false); - const timestamps = get(options, 'timestamps', true); - - // Support skipping timestamps at the query level, see gh-6980 - if (!timestamps || updates == null) { - return currentUpdate; - } - - if (overwrite) { - if (currentUpdate && currentUpdate.$set) { - currentUpdate = currentUpdate.$set; - updates.$set = {}; - _updates = updates.$set; - } - if (updatedAt && !currentUpdate[updatedAt]) { - _updates[updatedAt] = now; - } - if (createdAt && !currentUpdate[createdAt]) { - _updates[createdAt] = now; - } - return updates; - } - updates.$set = updates.$set || {}; - currentUpdate = currentUpdate || {}; - - if (updatedAt && - (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) { - updates.$set[updatedAt] = now; - } - - if (createdAt) { - if (currentUpdate[createdAt]) { - delete currentUpdate[createdAt]; - } - if (currentUpdate.$set && currentUpdate.$set[createdAt]) { - delete currentUpdate.$set[createdAt]; - } - - updates.$setOnInsert = updates.$setOnInsert || {}; - updates.$setOnInsert[createdAt] = now; - } - - if (Object.keys(updates.$set).length === 0) { - delete updates.$set; - } - - return updates; -} diff --git a/node_modules/mongoose/lib/helpers/update/castArrayFilters.js b/node_modules/mongoose/lib/helpers/update/castArrayFilters.js deleted file mode 100644 index 5fc5fe6b9f7e273b1e9deb695e47287d37d61fff..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/update/castArrayFilters.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -const castFilterPath = require('../query/castFilterPath'); -const modifiedPaths = require('./modifiedPaths'); - -module.exports = function castArrayFilters(query) { - const arrayFilters = query.options.arrayFilters; - if (!Array.isArray(arrayFilters)) { - return; - } - - const update = query.getUpdate(); - const schema = query.schema; - - const updatedPaths = modifiedPaths(update); - - const updatedPathsByFilter = Object.keys(updatedPaths).reduce((cur, path) => { - const matches = path.match(/\$\[[^\]]+\]/g); - if (matches == null) { - return cur; - } - for (const match of matches) { - const firstMatch = path.indexOf(match); - if (firstMatch !== path.lastIndexOf(match)) { - throw new Error(`Path '${path}' contains the same array filter multiple times`); - } - cur[match.substring(2, match.length - 1)] = path.substr(0, firstMatch - 1); - } - return cur; - }, {}); - - for (const filter of arrayFilters) { - if (filter == null) { - throw new Error(`Got null array filter in ${arrayFilters}`); - } - const firstKey = Object.keys(filter)[0]; - - if (filter[firstKey] == null) { - continue; - } - - const dot = firstKey.indexOf('.'); - let filterPath = dot === -1 ? - updatedPathsByFilter[firstKey] + '.0' : - updatedPathsByFilter[firstKey.substr(0, dot)] + '.0' + firstKey.substr(dot); - - if (filterPath == null) { - throw new Error(`Filter path not found for ${firstKey}`); - } - - // If there are multiple array filters in the path being updated, make sure - // to replace them so we can get the schema path. - filterPath = filterPath.replace(/\$\[[^\]]+\]/g, '0'); - - const schematype = schema.path(filterPath); - if (typeof filter[firstKey] === 'object') { - filter[firstKey] = castFilterPath(query, schematype, filter[firstKey]); - } else { - filter[firstKey] = schematype.castForQuery(filter[firstKey]); - } - } -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/update/modifiedPaths.js b/node_modules/mongoose/lib/helpers/update/modifiedPaths.js deleted file mode 100644 index 9cb567d5a021d23241c065d71fc1ff8b03ba9d4d..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/update/modifiedPaths.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -const _modifiedPaths = require('../common').modifiedPaths; - -/** - * Given an update document with potential update operators (`$set`, etc.) - * returns an object whose keys are the directly modified paths. - * - * If there are any top-level keys that don't start with `$`, we assume those - * will get wrapped in a `$set`. The Mongoose Query is responsible for wrapping - * top-level keys in `$set`. - * - * @param {Object} update - * @return {Object} modified - */ - -module.exports = function modifiedPaths(update) { - const keys = Object.keys(update); - const res = {}; - - const withoutDollarKeys = {}; - for (const key of keys) { - if (key.startsWith('$')) { - _modifiedPaths(update[key], '', res); - continue; - } - withoutDollarKeys[key] = update[key]; - } - - _modifiedPaths(withoutDollarKeys, '', res); - - return res; -}; diff --git a/node_modules/mongoose/lib/helpers/updateValidators.js b/node_modules/mongoose/lib/helpers/updateValidators.js deleted file mode 100644 index 5c790fb1765707c96f052619bc8dc449a285b004..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/helpers/updateValidators.js +++ /dev/null @@ -1,227 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const Mixed = require('../schema/mixed'); -const ValidationError = require('../error/validation'); -const flatten = require('./common').flatten; -const modifiedPaths = require('./common').modifiedPaths; -const parallel = require('async/parallel'); - -/** - * Applies validators and defaults to update and findOneAndUpdate operations, - * specifically passing a null doc as `this` to validators and defaults - * - * @param {Query} query - * @param {Schema} schema - * @param {Object} castedDoc - * @param {Object} options - * @method runValidatorsOnUpdate - * @api private - */ - -module.exports = function(query, schema, castedDoc, options) { - let _keys; - const keys = Object.keys(castedDoc || {}); - let updatedKeys = {}; - let updatedValues = {}; - const isPull = {}; - const arrayAtomicUpdates = {}; - const numKeys = keys.length; - let hasDollarUpdate = false; - const modified = {}; - let currentUpdate; - let key; - let i; - - for (i = 0; i < numKeys; ++i) { - if (keys[i].charAt(0) === '$') { - hasDollarUpdate = true; - if (keys[i] === '$push' || keys[i] === '$addToSet') { - _keys = Object.keys(castedDoc[keys[i]]); - for (let ii = 0; ii < _keys.length; ++ii) { - currentUpdate = castedDoc[keys[i]][_keys[ii]]; - if (currentUpdate && currentUpdate.$each) { - arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []). - concat(currentUpdate.$each); - } else { - arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []). - concat([currentUpdate]); - } - } - continue; - } - modifiedPaths(castedDoc[keys[i]], '', modified); - const flat = flatten(castedDoc[keys[i]]); - const paths = Object.keys(flat); - const numPaths = paths.length; - for (let j = 0; j < numPaths; ++j) { - let updatedPath = paths[j].replace('.$.', '.0.'); - updatedPath = updatedPath.replace(/\.\$$/, '.0'); - key = keys[i]; - // With `$pull` we might flatten `$in`. Skip stuff nested under `$in` - // for the rest of the logic, it will get handled later. - if (updatedPath.indexOf('$') !== -1) { - continue; - } - if (key === '$set' || key === '$setOnInsert' || - key === '$pull' || key === '$pullAll') { - updatedValues[updatedPath] = flat[paths[j]]; - isPull[updatedPath] = key === '$pull' || key === '$pullAll'; - } else if (key === '$unset') { - updatedValues[updatedPath] = undefined; - } - updatedKeys[updatedPath] = true; - } - } - } - - if (!hasDollarUpdate) { - modifiedPaths(castedDoc, '', modified); - updatedValues = flatten(castedDoc); - updatedKeys = Object.keys(updatedValues); - } - - const updates = Object.keys(updatedValues); - const numUpdates = updates.length; - const validatorsToExecute = []; - const validationErrors = []; - - const alreadyValidated = []; - - const context = options && options.context === 'query' ? query : null; - function iter(i, v) { - const schemaPath = schema._getSchema(updates[i]); - if (schemaPath) { - // gh-4305: `_getSchema()` will report all sub-fields of a 'Mixed' path - // as 'Mixed', so avoid double validating them. - if (schemaPath instanceof Mixed && schemaPath.$fullPath !== updates[i]) { - return; - } - - if (v && Array.isArray(v.$in)) { - v.$in.forEach((v, i) => { - validatorsToExecute.push(function(callback) { - schemaPath.doValidate( - v, - function(err) { - if (err) { - err.path = updates[i] + '.$in.' + i; - validationErrors.push(err); - } - callback(null); - }, - context, - {updateValidator: true}); - }); - }); - } else { - if (isPull[updates[i]] && - !Array.isArray(v) && - schemaPath.$isMongooseArray) { - v = [v]; - } - - if (schemaPath.$isMongooseDocumentArrayElement && v != null && v.$__ != null) { - alreadyValidated.push(updates[i]); - validatorsToExecute.push(function(callback) { - schemaPath.doValidate(v, function(err) { - if (err) { - err.path = updates[i]; - validationErrors.push(err); - return callback(null); - } - - v.validate(function(err) { - if (err) { - if (err.errors) { - for (const key of Object.keys(err.errors)) { - const _err = err.errors[key]; - _err.path = updates[i] + '.' + key; - validationErrors.push(_err); - } - } - } - callback(null); - }); - }, context, { updateValidator: true }); - }); - } else { - validatorsToExecute.push(function(callback) { - for (const path of alreadyValidated) { - if (updates[i].startsWith(path + '.')) { - return callback(null); - } - } - schemaPath.doValidate(v, function(err) { - if (err) { - err.path = updates[i]; - validationErrors.push(err); - } - callback(null); - }, context, { updateValidator: true }); - }); - } - } - } - } - for (i = 0; i < numUpdates; ++i) { - iter(i, updatedValues[updates[i]]); - } - - const arrayUpdates = Object.keys(arrayAtomicUpdates); - const numArrayUpdates = arrayUpdates.length; - for (i = 0; i < numArrayUpdates; ++i) { - (function(i) { - let schemaPath = schema._getSchema(arrayUpdates[i]); - if (schemaPath && schemaPath.$isMongooseDocumentArray) { - validatorsToExecute.push(function(callback) { - schemaPath.doValidate( - arrayAtomicUpdates[arrayUpdates[i]], - function(err) { - if (err) { - err.path = arrayUpdates[i]; - validationErrors.push(err); - } - callback(null); - }, - options && options.context === 'query' ? query : null); - }); - } else { - schemaPath = schema._getSchema(arrayUpdates[i] + '.0'); - for (let j = 0; j < arrayAtomicUpdates[arrayUpdates[i]].length; ++j) { - (function(j) { - validatorsToExecute.push(function(callback) { - schemaPath.doValidate( - arrayAtomicUpdates[arrayUpdates[i]][j], - function(err) { - if (err) { - err.path = arrayUpdates[i]; - validationErrors.push(err); - } - callback(null); - }, - options && options.context === 'query' ? query : null, - { updateValidator: true }); - }); - })(j); - } - } - })(i); - } - - return function(callback) { - parallel(validatorsToExecute, function() { - if (validationErrors.length) { - const err = new ValidationError(null); - for (let i = 0; i < validationErrors.length; ++i) { - err.addError(validationErrors[i].path, validationErrors[i]); - } - return callback(err); - } - callback(null); - }); - }; -}; diff --git a/node_modules/mongoose/lib/index.js b/node_modules/mongoose/lib/index.js deleted file mode 100644 index 976f01e7b72c991e2e213987dd9696e5d27c386d..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/index.js +++ /dev/null @@ -1,997 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -if (global.MONGOOSE_DRIVER_PATH) { - require('./driver').set(require(global.MONGOOSE_DRIVER_PATH)); -} else { - require('./driver').set(require('./drivers/node-mongodb-native')); -} - -const Schema = require('./schema'); -const SchemaType = require('./schematype'); -const SchemaTypes = require('./schema/index'); -const VirtualType = require('./virtualtype'); -const STATES = require('./connectionstate'); -const Types = require('./types'); -const Query = require('./query'); -const Model = require('./model'); -const Document = require('./document'); -const get = require('./helpers/get'); -const legacyPluralize = require('mongoose-legacy-pluralize'); -const utils = require('./utils'); -const pkg = require('../package.json'); - -const removeSubdocs = require('./plugins/removeSubdocs'); -const saveSubdocs = require('./plugins/saveSubdocs'); -const validateBeforeSave = require('./plugins/validateBeforeSave'); - -const Aggregate = require('./aggregate'); -const PromiseProvider = require('./promise_provider'); -const shardingPlugin = require('./plugins/sharding'); - -const defaultMongooseSymbol = Symbol.for('mongoose:default'); - -require('./helpers/printJestWarning'); - -/** - * Mongoose constructor. - * - * The exports object of the `mongoose` module is an instance of this class. - * Most apps will only use this one instance. - * - * @api public - */ - -function Mongoose(options) { - this.connections = []; - this.models = {}; - this.modelSchemas = {}; - // default global options - this.options = { - pluralization: true - }; - const conn = this.createConnection(); // default connection - conn.models = this.models; - - this._pluralize = legacyPluralize; - - // If a user creates their own Mongoose instance, give them a separate copy - // of the `Schema` constructor so they get separate custom types. (gh-6933) - if (!options || !options[defaultMongooseSymbol]) { - const _this = this; - this.Schema = function() { - this.base = _this; - return Schema.apply(this, arguments); - }; - this.Schema.prototype = Object.create(Schema.prototype); - - Object.assign(this.Schema, Schema); - this.Schema.base = this; - this.Schema.Types = Object.assign({}, Schema.Types); - } else { - // Hack to work around babel's strange behavior with - // `import mongoose, { Schema } from 'mongoose'`. Because `Schema` is not - // an own property of a Mongoose global, Schema will be undefined. See gh-5648 - for (const key of ['Schema', 'model']) { - this[key] = Mongoose.prototype[key]; - } - } - this.Schema.prototype.base = this; - - Object.defineProperty(this, 'plugins', { - configurable: false, - enumerable: true, - writable: false, - value: [ - [saveSubdocs, { deduplicate: true }], - [validateBeforeSave, { deduplicate: true }], - [shardingPlugin, { deduplicate: true }], - [removeSubdocs, { deduplicate: true }] - ] - }); -} - -/** - * Expose connection states for user-land - * - * @memberOf Mongoose - * @property STATES - * @api public - */ -Mongoose.prototype.STATES = STATES; - -/** - * Sets mongoose options - * - * ####Example: - * - * mongoose.set('test', value) // sets the 'test' option to `value` - * - * mongoose.set('debug', true) // enable logging collection methods + arguments to the console - * - * mongoose.set('debug', function(collectionName, methodName, arg1, arg2...) {}); // use custom function to log collection methods + arguments - * - * Currently supported options are: - * - 'debug': prints the operations mongoose sends to MongoDB to the console - * - 'bufferCommands': enable/disable mongoose's buffering mechanism for all connections and models - * - 'useCreateIndex': false by default. Set to `true` to make Mongoose's default index build use `createIndex()` instead of `ensureIndex()` to avoid deprecation warnings from the MongoDB driver. - * - 'useFindAndModify': true by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. - * - 'useNewUrlParser': false by default. Set to `true` to make all connections set the `useNewUrlParser` option by default - * - 'cloneSchemas': false by default. Set to `true` to `clone()` all schemas before compiling into a model. - * - 'applyPluginsToDiscriminators': false by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema. - * - 'objectIdGetter': true by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to false to remove the getter. - * - 'runValidators': false by default. Set to true to enable [update validators](/docs/validation.html#update-validators) for all validators by default. - * - 'toObject': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](/docs/api.html#document_Document-toObject) - * - 'toJSON': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toJSON()`](/docs/api.html#document_Document-toJSON), for determining how Mongoose documents get serialized by `JSON.stringify()` - * - 'strict': true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas. - * - 'selectPopulatedPaths': true by default. Set to false to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one. - * - * @param {String} key - * @param {String|Function|Boolean} value - * @api public - */ - -Mongoose.prototype.set = function(key, value) { - if (arguments.length === 1) { - return this.options[key]; - } - - this.options[key] = value; - - if (key === 'objectIdGetter') { - if (value) { - Object.defineProperty(mongoose.Types.ObjectId.prototype, '_id', { - enumerable: false, - configurable: true, - get: function() { - return this; - } - }); - } else { - delete mongoose.Types.ObjectId.prototype._id; - } - } - - return this; -}; - -/** - * Gets mongoose options - * - * ####Example: - * - * mongoose.get('test') // returns the 'test' value - * - * @param {String} key - * @method get - * @api public - */ - -Mongoose.prototype.get = Mongoose.prototype.set; - -/** - * Creates a Connection instance. - * - * Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections. - * - * - * _Options passed take precedence over options included in connection strings._ - * - * ####Example: - * - * // with mongodb:// URI - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); - * - * // and options - * var opts = { db: { native_parser: true }} - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts); - * - * // replica sets - * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database'); - * - * // and options - * var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }} - * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts); - * - * // and options - * var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' } - * db = mongoose.createConnection('localhost', 'database', port, opts) - * - * // initialize now, connect later - * db = mongoose.createConnection(); - * db.openUri('localhost', 'database', port, [opts]); - * - * @param {String} [uri] a mongodb:// URI - * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below. - * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. - * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. - * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. - * @return {Connection} the created Connection object. Connections are thenable, so you can do `await mongoose.createConnection()` - * @api public - */ - -Mongoose.prototype.createConnection = function(uri, options, callback) { - const conn = new Connection(this); - if (typeof options === 'function') { - callback = options; - options = null; - } - this.connections.push(conn); - - if (arguments.length > 0) { - return conn.openUri(uri, options, callback); - } - - return conn; -}; - -/** - * Opens the default mongoose connection. - * - * ####Example: - * - * mongoose.connect('mongodb://user:pass@localhost:port/database'); - * - * // replica sets - * var uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase'; - * mongoose.connect(uri); - * - * // with options - * mongoose.connect(uri, options); - * - * // optional callback that gets fired when initial connection completed - * var uri = 'mongodb://nonexistent.domain:27000'; - * mongoose.connect(uri, function(error) { - * // if error is truthy, the initial connection failed. - * }) - * - * @param {String} uri(s) - * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below. - * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. - * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. - * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. - * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#-ensureindex-) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init). - * @param {Boolean} [options.useFindAndModify=true] True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. - * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to make all connections set the `useNewUrlParser` option by default. - * @param {Function} [callback] - * @see Mongoose#createConnection #index_Mongoose-createConnection - * @api public - * @return {Promise} resolves to `this` if connection succeeded - */ - -Mongoose.prototype.connect = function() { - const _mongoose = this instanceof Mongoose ? this : mongoose; - const conn = _mongoose.connection; - return conn.openUri(arguments[0], arguments[1], arguments[2]).then(() => _mongoose); -}; - -/** - * Runs `.close()` on all connections in parallel. - * - * @param {Function} [callback] called after all connection close, or when first error occurred. - * @return {Promise} resolves when all connections are closed, or rejects with the first error that occurred. - * @api public - */ - -Mongoose.prototype.disconnect = function(callback) { - return utils.promiseOrCallback(callback, cb => { - let remaining = this.connections.length; - if (remaining <= 0) { - return cb(null); - } - this.connections.forEach(conn => { - conn.close(function(error) { - if (error) { - return cb(error); - } - if (!--remaining) { - cb(null); - } - }); - }); - }); -}; - -/** - * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) - * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), - * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). - * - * Calling `mongoose.startSession()` is equivalent to calling `mongoose.connection.startSession()`. - * Sessions are scoped to a connection, so calling `mongoose.startSession()` - * starts a session on the [default mongoose connection](/docs/api.html#mongoose_Mongoose-connection). - * - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) - * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency - * @param {Function} [callback] - * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession` - * @api public - */ - -Mongoose.prototype.startSession = function() { - return this.connection.startSession.apply(this.connection, arguments); -}; - -/** - * Getter/setter around function for pluralizing collection names. - * - * @param {Function|null} [fn] overwrites the function used to pluralize collection names - * @return {Function|null} the current function used to pluralize collection names, defaults to the legacy function from `mongoose-legacy-pluralize`. - * @api public - */ - -Mongoose.prototype.pluralize = function(fn) { - if (arguments.length > 0) { - this._pluralize = fn; - } - return this._pluralize; -}; - -/** - * Defines a model or retrieves it. - * - * Models defined on the `mongoose` instance are available to all connection - * created by the same `mongoose` instance. - * - * If you call `mongoose.model()` with twice the same name but a different schema, - * you will get an `OverwriteModelError`. If you call `mongoose.model()` with - * the same name and same schema, you'll get the same schema back. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * - * // define an Actor model with this mongoose instance - * const Schema = new Schema({ name: String }); - * mongoose.model('Actor', schema); - * - * // create a new connection - * var conn = mongoose.createConnection(..); - * - * // create Actor model - * var Actor = conn.model('Actor', schema); - * conn.model('Actor') === Actor; // true - * conn.model('Actor', schema) === Actor; // true, same schema - * conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name - * - * // This throws an `OverwriteModelError` because the schema is different. - * conn.model('Actor', new Schema({ name: String })); - * - * _When no `collection` argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use `mongoose.pluralize()`, or set your schemas collection name option._ - * - * ####Example: - * - * var schema = new Schema({ name: String }, { collection: 'actor' }); - * - * // or - * - * schema.set('collection', 'actor'); - * - * // or - * - * var collectionName = 'actor' - * var M = mongoose.model('Actor', schema, collectionName) - * - * @param {String|Function} name model name or class extending Model - * @param {Schema} [schema] the schema to use. - * @param {String} [collection] name (optional, inferred from model name) - * @param {Boolean} [skipInit] whether to skip initialization (defaults to false) - * @return {Model} The model associated with `name`. Mongoose will create the model if it doesn't already exist. - * @api public - */ - -Mongoose.prototype.model = function(name, schema, collection, skipInit) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - let model; - if (typeof name === 'function') { - model = name; - name = model.name; - if (!(model.prototype instanceof Model)) { - throw new _mongoose.Error('The provided class ' + name + ' must extend Model'); - } - } - - if (typeof schema === 'string') { - collection = schema; - schema = false; - } - - if (utils.isObject(schema) && !(schema.instanceOfSchema)) { - schema = new Schema(schema); - } - if (schema && !schema.instanceOfSchema) { - throw new Error('The 2nd parameter to `mongoose.model()` should be a ' + - 'schema or a POJO'); - } - - if (typeof collection === 'boolean') { - skipInit = collection; - collection = null; - } - - // handle internal options from connection.model() - let options; - if (skipInit && utils.isObject(skipInit)) { - options = skipInit; - skipInit = true; - } else { - options = {}; - } - - // look up schema for the collection. - if (!_mongoose.modelSchemas[name]) { - if (schema) { - // cache it so we only apply plugins once - _mongoose.modelSchemas[name] = schema; - } else { - throw new mongoose.Error.MissingSchemaError(name); - } - } - - const originalSchema = schema; - if (schema) { - if (_mongoose.get('cloneSchemas')) { - schema = schema.clone(); - } - _mongoose._applyPlugins(schema); - } - - let sub; - - // connection.model() may be passing a different schema for - // an existing model name. in this case don't read from cache. - if (_mongoose.models[name] && options.cache !== false) { - if (originalSchema && - originalSchema.instanceOfSchema && - originalSchema !== _mongoose.models[name].schema) { - throw new _mongoose.Error.OverwriteModelError(name); - } - - if (collection && collection !== _mongoose.models[name].collection.name) { - // subclass current model with alternate collection - model = _mongoose.models[name]; - schema = model.prototype.schema; - sub = model.__subclass(_mongoose.connection, schema, collection); - // do not cache the sub model - return sub; - } - - return _mongoose.models[name]; - } - - // ensure a schema exists - if (!schema) { - schema = this.modelSchemas[name]; - if (!schema) { - throw new mongoose.Error.MissingSchemaError(name); - } - } - - // Apply relevant "global" options to the schema - if (!('pluralization' in schema.options)) { - schema.options.pluralization = _mongoose.options.pluralization; - } - - if (!collection) { - collection = schema.get('collection') || - utils.toCollectionName(name, _mongoose.pluralize()); - } - - const connection = options.connection || _mongoose.connection; - model = _mongoose.Model.compile(model || name, schema, collection, connection, _mongoose); - - if (!skipInit) { - // Errors handled internally, so safe to ignore error - model.init(function $modelInitNoop() {}); - } - - if (options.cache === false) { - return model; - } - - _mongoose.models[name] = model; - return _mongoose.models[name]; -}; - -/** - * Removes the model named `name` from the default connection, if it exists. - * You can use this function to clean up any models you created in your tests to - * prevent OverwriteModelErrors. - * - * Equivalent to `mongoose.connection.deleteModel(name)`. - * - * ####Example: - * - * mongoose.model('User', new Schema({ name: String })); - * console.log(mongoose.model('User')); // Model object - * mongoose.deleteModel('User'); - * console.log(mongoose.model('User')); // undefined - * - * // Usually useful in a Mocha `afterEach()` hook - * afterEach(function() { - * mongoose.deleteModel(/.+/); // Delete every model - * }); - * - * @api public - * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. - * @return {Mongoose} this - */ - -Mongoose.prototype.deleteModel = function(name) { - this.connection.deleteModel(name); - return this; -}; - -/** - * Returns an array of model names created on this instance of Mongoose. - * - * ####Note: - * - * _Does not include names of models created using `connection.model()`._ - * - * @api public - * @return {Array} - */ - -Mongoose.prototype.modelNames = function() { - const names = Object.keys(this.models); - return names; -}; - -/** - * Applies global plugins to `schema`. - * - * @param {Schema} schema - * @api private - */ - -Mongoose.prototype._applyPlugins = function(schema, options) { - if (schema.$globalPluginsApplied) { - return; - } - schema.$globalPluginsApplied = true; - - if (!options || !options.skipTopLevel) { - for (let i = 0; i < this.plugins.length; ++i) { - schema.plugin(this.plugins[i][0], this.plugins[i][1]); - } - } - - for (let i = 0; i < schema.childSchemas.length; ++i) { - this._applyPlugins(schema.childSchemas[i].schema); - } - - const discriminators = schema.discriminators; - if (discriminators == null) { - return; - } - - const applyPluginsToDiscriminators = get(this, - 'options.applyPluginsToDiscriminators', false); - - const keys = Object.keys(discriminators); - for (let i = 0; i < keys.length; ++i) { - const discriminatorKey = keys[i]; - const discriminatorSchema = discriminators[discriminatorKey]; - - this._applyPlugins(discriminatorSchema, { skipTopLevel: !applyPluginsToDiscriminators }); - } -}; - -/** - * Declares a global plugin executed on all Schemas. - * - * Equivalent to calling `.plugin(fn)` on each Schema you create. - * - * @param {Function} fn plugin callback - * @param {Object} [opts] optional options - * @return {Mongoose} this - * @see plugins ./plugins.html - * @api public - */ - -Mongoose.prototype.plugin = function(fn, opts) { - this.plugins.push([fn, opts]); - return this; -}; - -/** - * The Mongoose module's default connection. Equivalent to `mongoose.connections][0]`, see [`connections`](#mongoose_Mongoose-connections). - * - * ####Example: - * - * var mongoose = require('mongoose'); - * mongoose.connect(...); - * mongoose.connection.on('error', cb); - * - * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model). - * - * To create a new connection, use [`createConnection()`](#mongoose_Mongoose-createConnection). - * - * @memberOf Mongoose - * @instance - * @property {Connection} connection - * @api public - */ - -Mongoose.prototype.__defineGetter__('connection', function() { - return this.connections[0]; -}); - -Mongoose.prototype.__defineSetter__('connection', function(v) { - if (v instanceof Connection) { - this.connections[0] = v; - this.models = v.models; - } -}); - -/** - * An array containing all [connections](connections.html) associated with this - * Mongoose instance. By default, there is 1 connection. Calling - * [`createConnection()`](#mongoose_Mongoose-createConnection) adds a connection - * to this array. - * - * ####Example: - * - * const mongoose = require('mongoose'); - * mongoose.connections.length; // 1, just the default connection - * mongoose.connections[0] === mongoose.connection; // true - * - * mongoose.createConnection('mongodb://localhost:27017/test'); - * mongoose.connections.length; // 2 - * - * @memberOf Mongoose - * @instance - * @property {Array} connections - * @api public - */ - -Mongoose.prototype.connections; - -/*! - * Driver dependent APIs - */ - -const driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native'; - -/*! - * Connection - */ - -const Connection = require(driver + '/connection'); - -/*! - * Collection - */ - -const Collection = require(driver + '/collection'); - -/** - * The Mongoose Aggregate constructor - * - * @method Aggregate - * @api public - */ - -Mongoose.prototype.Aggregate = Aggregate; - -/** - * The Mongoose Collection constructor - * - * @method Collection - * @api public - */ - -Mongoose.prototype.Collection = Collection; - -/** - * The Mongoose [Connection](#connection_Connection) constructor - * - * @memberOf Mongoose - * @instance - * @method Connection - * @api public - */ - -Mongoose.prototype.Connection = Connection; - -/** - * The Mongoose version - * - * #### Example - * - * console.log(mongoose.version); // '5.x.x' - * - * @property version - * @api public - */ - -Mongoose.prototype.version = pkg.version; - -/** - * The Mongoose constructor - * - * The exports of the mongoose module is an instance of this class. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var mongoose2 = new mongoose.Mongoose(); - * - * @method Mongoose - * @api public - */ - -Mongoose.prototype.Mongoose = Mongoose; - -/** - * The Mongoose [Schema](#schema_Schema) constructor - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var Schema = mongoose.Schema; - * var CatSchema = new Schema(..); - * - * @method Schema - * @api public - */ - -Mongoose.prototype.Schema = Schema; - -/** - * The Mongoose [SchemaType](#schematype_SchemaType) constructor - * - * @method SchemaType - * @api public - */ - -Mongoose.prototype.SchemaType = SchemaType; - -/** - * The various Mongoose SchemaTypes. - * - * ####Note: - * - * _Alias of mongoose.Schema.Types for backwards compatibility._ - * - * @property SchemaTypes - * @see Schema.SchemaTypes #schema_Schema.Types - * @api public - */ - -Mongoose.prototype.SchemaTypes = Schema.Types; - -/** - * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor - * - * @method VirtualType - * @api public - */ - -Mongoose.prototype.VirtualType = VirtualType; - -/** - * The various Mongoose Types. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var array = mongoose.Types.Array; - * - * ####Types: - * - * - [ObjectId](#types-objectid-js) - * - [Buffer](#types-buffer-js) - * - [SubDocument](#types-embedded-js) - * - [Array](#types-array-js) - * - [DocumentArray](#types-documentarray-js) - * - * Using this exposed access to the `ObjectId` type, we can construct ids on demand. - * - * var ObjectId = mongoose.Types.ObjectId; - * var id1 = new ObjectId; - * - * @property Types - * @api public - */ - -Mongoose.prototype.Types = Types; - -/** - * The Mongoose [Query](#query_Query) constructor. - * - * @method Query - * @api public - */ - -Mongoose.prototype.Query = Query; - -/** - * The Mongoose [Promise](#promise_Promise) constructor. - * - * @memberOf Mongoose - * @instance - * @property Promise - * @api public - */ - -Object.defineProperty(Mongoose.prototype, 'Promise', { - get: function() { - return PromiseProvider.get(); - }, - set: function(lib) { - PromiseProvider.set(lib); - } -}); - -/** - * Storage layer for mongoose promises - * - * @method PromiseProvider - * @api public - */ - -Mongoose.prototype.PromiseProvider = PromiseProvider; - -/** - * The Mongoose [Model](#model_Model) constructor. - * - * @method Model - * @api public - */ - -Mongoose.prototype.Model = Model; - -/** - * The Mongoose [Document](#document-js) constructor. - * - * @method Document - * @api public - */ - -Mongoose.prototype.Document = Document; - -/** - * The Mongoose DocumentProvider constructor. Mongoose users should not have to - * use this directly - * - * @method DocumentProvider - * @api public - */ - -Mongoose.prototype.DocumentProvider = require('./document_provider'); - -/** - * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that should be - * [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/). - * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId` - * instead. - * - * ####Example: - * - * const childSchema = new Schema({ parentId: mongoose.ObjectId }); - * - * @property ObjectId - * @api public - */ - -Mongoose.prototype.ObjectId = SchemaTypes.ObjectId; - -/** - * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that should be - * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html). - * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128` - * instead. - * - * ####Example: - * - * const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 }); - * - * @property Decimal128 - * @api public - */ - -Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128; - -/** - * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that Mongoose's change tracking, casting, - * and validation should ignore. - * - * ####Example: - * - * const schema = new Schema({ arbitrary: mongoose.Mixed }); - * - * @property Mixed - * @api public - */ - -Mongoose.prototype.Mixed = SchemaTypes.Mixed; - -/** - * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that Mongoose should cast to numbers. - * - * ####Example: - * - * const schema = new Schema({ num: mongoose.Number }); - * // Equivalent to: - * const schema = new Schema({ num: 'number' }); - * - * @property Number - * @api public - */ - -Mongoose.prototype.Number = SchemaTypes.Number; - -/** - * The [MongooseError](#error_MongooseError) constructor. - * - * @method Error - * @api public - */ - -Mongoose.prototype.Error = require('./error'); - -/** - * Mongoose uses this function to get the current time when setting - * [timestamps](/docs/guide.html#timestamps). You may stub out this function - * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing. - * - * @method now - * @returns Date the current time - * @api public - */ - -Mongoose.prototype.now = function now() { return new Date(); }; - -/** - * The Mongoose CastError constructor - * - * @method CastError - * @param {String} type The name of the type - * @param {Any} value The value that failed to cast - * @param {String} path The path `a.b.c` in the doc where this cast error occurred - * @param {Error} [reason] The original error that was thrown - * @api public - */ - -Mongoose.prototype.CastError = require('./error/cast'); - -/** - * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses. - * - * @property mongo - * @api public - */ - -Mongoose.prototype.mongo = require('mongodb'); - -/** - * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses. - * - * @property mquery - * @api public - */ - -Mongoose.prototype.mquery = require('mquery'); - -/*! - * The exports object is an instance of Mongoose. - * - * @api public - */ - -const mongoose = module.exports = exports = new Mongoose({ - [defaultMongooseSymbol]: true -}); diff --git a/node_modules/mongoose/lib/internal.js b/node_modules/mongoose/lib/internal.js deleted file mode 100644 index 9364658c0481a90d49df93b067c1aa143ac2a965..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/internal.js +++ /dev/null @@ -1,37 +0,0 @@ -/*! - * Dependencies - */ - -'use strict'; - -const StateMachine = require('./statemachine'); -const ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore'); - -module.exports = exports = InternalCache; - -function InternalCache() { - this.strictMode = undefined; - this.selected = undefined; - this.shardval = undefined; - this.saveError = undefined; - this.validationError = undefined; - this.adhocPaths = undefined; - this.removing = undefined; - this.inserting = undefined; - this.saving = undefined; - this.version = undefined; - this.getters = {}; - this._id = undefined; - this.populate = undefined; // what we want to populate in this doc - this.populated = undefined;// the _ids that have been populated - this.wasPopulated = false; // if this doc was the result of a population - this.scope = undefined; - this.activePaths = new ActiveRoster; - this.pathsToScopes = {}; - this.cachedRequired = {}; - this.session = null; - - // embedded docs - this.ownerDocument = undefined; - this.fullPath = undefined; -} diff --git a/node_modules/mongoose/lib/model.js b/node_modules/mongoose/lib/model.js deleted file mode 100644 index ddb92a63f2f0a13cc047f062b012bfb5e8713736..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/model.js +++ /dev/null @@ -1,4701 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const Aggregate = require('./aggregate'); -const ChangeStream = require('./cursor/ChangeStream'); -const Document = require('./document'); -const DocumentNotFoundError = require('./error').DocumentNotFoundError; -const DivergentArrayError = require('./error').DivergentArrayError; -const Error = require('./error'); -const EventEmitter = require('events').EventEmitter; -const MongooseMap = require('./types/map'); -const OverwriteModelError = require('./error').OverwriteModelError; -const PromiseProvider = require('./promise_provider'); -const Query = require('./query'); -const Schema = require('./schema'); -const VersionError = require('./error').VersionError; -const ParallelSaveError = require('./error').ParallelSaveError; -const applyQueryMiddleware = require('./helpers/query/applyQueryMiddleware'); -const applyHooks = require('./helpers/model/applyHooks'); -const applyMethods = require('./helpers/model/applyMethods'); -const applyStatics = require('./helpers/model/applyStatics'); -const applyWriteConcern = require('./helpers/schema/applyWriteConcern'); -const assignRawDocsToIdStructure = require('./helpers/populate/assignRawDocsToIdStructure'); -const castBulkWrite = require('./helpers/model/castBulkWrite'); -const discriminator = require('./helpers/model/discriminator'); -const getDiscriminatorByValue = require('./queryhelpers').getDiscriminatorByValue; -const immediate = require('./helpers/immediate'); -const internalToObjectOptions = require('./options').internalToObjectOptions; -const isPathExcluded = require('./helpers/projection/isPathExcluded'); -const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive'); -const get = require('./helpers/get'); -const getSchemaTypes = require('./helpers/populate/getSchemaTypes'); -const getVirtual = require('./helpers/populate/getVirtual'); -const leanPopulateMap = require('./helpers/populate/leanPopulateMap'); -const modifiedPaths = require('./helpers/update/modifiedPaths'); -const mpath = require('mpath'); -const normalizeRefPath = require('./helpers/populate/normalizeRefPath'); -const parallel = require('async/parallel'); -const parallelLimit = require('async/parallelLimit'); -const setParentPointers = require('./helpers/schema/setParentPointers'); -const util = require('util'); -const utils = require('./utils'); - -const VERSION_WHERE = 1; -const VERSION_INC = 2; -const VERSION_ALL = VERSION_WHERE | VERSION_INC; - -const modelCollectionSymbol = Symbol.for('mongoose#Model#collection'); -const modelSymbol = require('./helpers/symbols').modelSymbol; -const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol; - -/** - * A Model is a class that's your primary tool for interacting with MongoDB. - * An instance of a Model is called a [Document](./api.html#Document). - * - * In Mongoose, the term "Model" refers to subclasses of the `mongoose.Model` - * class. You should not use the `mongoose.Model` class directly. The - * [`mongoose.model()`](./api.html#mongoose_Mongoose-model) and - * [`connection.model()`](./api.html#connection_Connection-model) functions - * create subclasses of `mongoose.Model` as shown below. - * - * ####Example: - * - * // `UserModel` is a "Model", a subclass of `mongoose.Model`. - * const UserModel = mongoose.model('User', new Schema({ name: String })); - * - * // You can use a Model to create new documents using `new`: - * const userDoc = new UserModel({ name: 'Foo' }); - * await userDoc.save(); - * - * // You also use a model to create queries: - * const userFromDb = await UserModel.findOne({ name: 'Foo' }); - * - * @param {Object} doc values for initial set - * @param [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projetion](./api.html#query_Query-select). - * @inherits Document http://mongoosejs.com/docs/api.html#document-js - * @event `error`: If listening to this event, 'error' is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. - * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. - * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event. - * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed. - * @api public - */ - -function Model(doc, fields, skipId) { - if (fields instanceof Schema) { - throw new TypeError('2nd argument to `Model` must be a POJO or string, ' + - '**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' + - '`mongoose.Model()`.'); - } - Document.call(this, doc, fields, skipId); -} - -/*! - * Inherits from Document. - * - * All Model.prototype features are available on - * top level (non-sub) documents. - */ - -Model.prototype.__proto__ = Document.prototype; -Model.prototype.$isMongooseModelPrototype = true; - -/** - * Connection the model uses. - * - * @api public - * @property db - * @memberOf Model - * @instance - */ - -Model.prototype.db; - -/** - * Collection the model uses. - * - * This property is read-only. Modifying this property is a no-op. - * - * @api public - * @property collection - * @memberOf Model - * @instance - */ - -Model.prototype.collection; - -/** - * The name of the model - * - * @api public - * @property modelName - * @memberOf Model - * @instance - */ - -Model.prototype.modelName; - -/** - * Additional properties to attach to the query when calling `save()` and - * `isNew` is false. - * - * @api public - * @property $where - * @memberOf Model - * @instance - */ - -Model.prototype.$where; - -/** - * If this is a discriminator model, `baseModelName` is the name of - * the base model. - * - * @api public - * @property baseModelName - * @memberOf Model - * @instance - */ - -Model.prototype.baseModelName; - -/** - * Event emitter that reports any errors that occurred. Useful for global error - * handling. - * - * ####Example: - * - * MyModel.events.on('error', err => console.log(err.message)); - * - * // Prints a 'CastError' because of the above handler - * await MyModel.findOne({ _id: 'notanid' }).catch(noop); - * - * @api public - * @fires error whenever any query or model function errors - * @memberOf Model - * @static events - */ - -Model.events; - -/*! - * Compiled middleware for this model. Set in `applyHooks()`. - * - * @api private - * @property _middleware - * @memberOf Model - * @static - */ - -Model._middleware; - -/*! - * ignore - */ - -function _applyCustomWhere(doc, where) { - if (doc.$where == null) { - return; - } - - const keys = Object.keys(doc.$where); - const len = keys.length; - for (let i = 0; i < len; ++i) { - where[keys[i]] = doc.$where[keys[i]]; - } -} - -/*! - * ignore - */ - -Model.prototype.$__handleSave = function(options, callback) { - const _this = this; - let saveOptions = {}; - - if ('safe' in options) { - _handleSafe(options); - } - applyWriteConcern(this.schema, options); - if ('w' in options) { - saveOptions.w = options.w; - } - if ('j' in options) { - saveOptions.j = options.j; - } - if ('wtimeout' in options) { - saveOptions.wtimeout = options.wtimeout; - } - if ('checkKeys' in options) { - saveOptions.checkKeys = options.checkKeys; - } - - const session = 'session' in options ? options.session : this.$session(); - if (session != null) { - saveOptions.session = session; - this.$session(session); - } - - if (Object.keys(saveOptions).length === 0) { - saveOptions = null; - } - - if (this.isNew) { - // send entire doc - const obj = this.toObject(internalToObjectOptions); - - if ((obj || {})._id === void 0) { - // documents must have an _id else mongoose won't know - // what to update later if more changes are made. the user - // wouldn't know what _id was generated by mongodb either - // nor would the ObjectId generated my mongodb necessarily - // match the schema definition. - setTimeout(function() { - callback(new Error('document must have an _id before saving')); - }, 0); - return; - } - - this.$__version(true, obj); - this[modelCollectionSymbol].insertOne(obj, saveOptions, function(err, ret) { - if (err) { - _this.isNew = true; - _this.emit('isNew', true); - _this.constructor.emit('isNew', true); - - callback(err, null); - return; - } - - callback(null, ret); - }); - this.$__reset(); - this.isNew = false; - this.emit('isNew', false); - this.constructor.emit('isNew', false); - // Make it possible to retry the insert - this.$__.inserting = true; - } else { - // Make sure we don't treat it as a new object on error, - // since it already exists - this.$__.inserting = false; - - const delta = this.$__delta(); - - if (delta) { - if (delta instanceof Error) { - callback(delta); - return; - } - - const where = this.$__where(delta[0]); - if (where instanceof Error) { - callback(where); - return; - } - - _applyCustomWhere(this, where); - - this[modelCollectionSymbol].updateOne(where, delta[1], saveOptions, function(err, ret) { - if (err) { - callback(err); - return; - } - ret.$where = where; - callback(null, ret); - }); - } else { - this.$__reset(); - callback(); - return; - } - - this.emit('isNew', false); - this.constructor.emit('isNew', false); - } -}; - -/*! - * ignore - */ - -Model.prototype.$__save = function(options, callback) { - this.$__handleSave(options, (error, result) => { - if (error) { - return this.schema.s.hooks.execPost('save:error', this, [this], { error: error }, function(error) { - callback(error); - }); - } - - // store the modified paths before the document is reset - const modifiedPaths = this.modifiedPaths(); - - this.$__reset(); - - let numAffected = 0; - if (get(options, 'safe.w') !== 0 && get(options, 'w') !== 0) { - // Skip checking if write succeeded if writeConcern is set to - // unacknowledged writes, because otherwise `numAffected` will always be 0 - if (result) { - if (Array.isArray(result)) { - numAffected = result.length; - } else if (result.result && result.result.n !== undefined) { - numAffected = result.result.n; - } else if (result.result && result.result.nModified !== undefined) { - numAffected = result.result.nModified; - } else { - numAffected = result; - } - } - - // was this an update that required a version bump? - if (this.$__.version && !this.$__.inserting) { - const doIncrement = VERSION_INC === (VERSION_INC & this.$__.version); - this.$__.version = undefined; - - const key = this.schema.options.versionKey; - const version = this.getValue(key) || 0; - - if (numAffected <= 0) { - // the update failed. pass an error back - const err = options.$versionError || new VersionError(this, version, modifiedPaths); - return callback(err); - } - - // increment version if was successful - if (doIncrement) { - this.setValue(key, version + 1); - } - } - - if (result != null && numAffected <= 0) { - error = new DocumentNotFoundError(result.$where); - return this.schema.s.hooks.execPost('save:error', this, [this], { error: error }, function(error) { - callback(error); - }); - } - } - this.$__.saving = undefined; - this.emit('save', this, numAffected); - this.constructor.emit('save', this, numAffected); - callback(null, this); - }); -}; - -/*! - * ignore - */ - -function generateVersionError(doc, modifiedPaths) { - const key = doc.schema.options.versionKey; - if (!key) { - return null; - } - const version = doc.getValue(key) || 0; - return new VersionError(doc, version, modifiedPaths); -} - -/** - * Saves this document. - * - * ####Example: - * - * product.sold = Date.now(); - * product.save(function (err, product) { - * if (err) .. - * }) - * - * The callback will receive two parameters - * - * 1. `err` if an error occurred - * 2. `product` which is the saved `product` - * - * As an extra measure of flow control, save will return a Promise. - * ####Example: - * product.save().then(function(product) { - * ... - * }); - * - * @param {Object} [options] options optional options - * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. - * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. - * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) - * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) - * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). - * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) - * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. - * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). - * @param {Function} [fn] optional callback - * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. - * @api public - * @see middleware http://mongoosejs.com/docs/middleware.html - */ - -Model.prototype.save = function(options, fn) { - let parallelSave; - - if (this.$__.saving) { - parallelSave = new ParallelSaveError(this); - } else { - this.$__.saving = new ParallelSaveError(this); - } - - if (typeof options === 'function') { - fn = options; - options = undefined; - } - - if (options != null) { - options = utils.clone(options); - } else { - options = {}; - } - - if (fn) { - fn = this.constructor.$wrapCallback(fn); - } - - options.$versionError = generateVersionError(this, this.modifiedPaths()); - - return utils.promiseOrCallback(fn, cb => { - if (parallelSave) { - this.$__handleReject(parallelSave); - return cb(parallelSave); - } - - this.$__.saveOptions = options; - - this.$__save(options, error => { - this.$__.saving = undefined; - delete this.$__.saveOptions; - - if (error) { - this.$__handleReject(error); - return cb(error); - } - cb(null, this); - }); - }, this.constructor.events); -}; - -/*! - * Determines whether versioning should be skipped for the given path - * - * @param {Document} self - * @param {String} path - * @return {Boolean} true if versioning should be skipped for the given path - */ -function shouldSkipVersioning(self, path) { - const skipVersioning = self.schema.options.skipVersioning; - if (!skipVersioning) return false; - - // Remove any array indexes from the path - path = path.replace(/\.\d+\./, '.'); - - return skipVersioning[path]; -} - -/*! - * Apply the operation to the delta (update) clause as - * well as track versioning for our where clause. - * - * @param {Document} self - * @param {Object} where - * @param {Object} delta - * @param {Object} data - * @param {Mixed} val - * @param {String} [operation] - */ - -function operand(self, where, delta, data, val, op) { - // delta - op || (op = '$set'); - if (!delta[op]) delta[op] = {}; - delta[op][data.path] = val; - - // disabled versioning? - if (self.schema.options.versionKey === false) return; - - // path excluded from versioning? - if (shouldSkipVersioning(self, data.path)) return; - - // already marked for versioning? - if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; - - switch (op) { - case '$set': - case '$unset': - case '$pop': - case '$pull': - case '$pullAll': - case '$push': - case '$addToSet': - break; - default: - // nothing to do - return; - } - - // ensure updates sent with positional notation are - // editing the correct array element. - // only increment the version if an array position changes. - // modifying elements of an array is ok if position does not change. - if (op === '$push' || op === '$addToSet' || op === '$pullAll' || op === '$pull') { - self.$__.version = VERSION_INC; - } else if (/^\$p/.test(op)) { - // potentially changing array positions - self.increment(); - } else if (Array.isArray(val)) { - // $set an array - self.increment(); - } else if (/\.\d+\.|\.\d+$/.test(data.path)) { - // now handling $set, $unset - // subpath of array - self.$__.version = VERSION_WHERE; - } -} - -/*! - * Compiles an update and where clause for a `val` with _atomics. - * - * @param {Document} self - * @param {Object} where - * @param {Object} delta - * @param {Object} data - * @param {Array} value - */ - -function handleAtomics(self, where, delta, data, value) { - if (delta.$set && delta.$set[data.path]) { - // $set has precedence over other atomics - return; - } - - if (typeof value.$__getAtomics === 'function') { - value.$__getAtomics().forEach(function(atomic) { - const op = atomic[0]; - const val = atomic[1]; - operand(self, where, delta, data, val, op); - }); - return; - } - - // legacy support for plugins - - const atomics = value._atomics; - const ops = Object.keys(atomics); - let i = ops.length; - let val; - let op; - - if (i === 0) { - // $set - - if (utils.isMongooseObject(value)) { - value = value.toObject({depopulate: 1, _isNested: true}); - } else if (value.valueOf) { - value = value.valueOf(); - } - - return operand(self, where, delta, data, value); - } - - function iter(mem) { - return utils.isMongooseObject(mem) - ? mem.toObject({depopulate: 1, _isNested: true}) - : mem; - } - - while (i--) { - op = ops[i]; - val = atomics[op]; - - if (utils.isMongooseObject(val)) { - val = val.toObject({depopulate: true, transform: false, _isNested: true}); - } else if (Array.isArray(val)) { - val = val.map(iter); - } else if (val.valueOf) { - val = val.valueOf(); - } - - if (op === '$addToSet') { - val = {$each: val}; - } - - operand(self, where, delta, data, val, op); - } -} - -/** - * Produces a special query document of the modified properties used in updates. - * - * @api private - * @method $__delta - * @memberOf Model - * @instance - */ - -Model.prototype.$__delta = function() { - const dirty = this.$__dirty(); - if (!dirty.length && VERSION_ALL !== this.$__.version) { - return; - } - - const where = {}; - const delta = {}; - const len = dirty.length; - const divergent = []; - let d = 0; - - where._id = this._doc._id; - // If `_id` is an object, need to depopulate, but also need to be careful - // because `_id` can technically be null (see gh-6406) - if (get(where, '_id.$__', null) != null) { - where._id = where._id.toObject({ transform: false, depopulate: true }); - } - - for (; d < len; ++d) { - const data = dirty[d]; - let value = data.value; - - const match = checkDivergentArray(this, data.path, value); - if (match) { - divergent.push(match); - continue; - } - - const pop = this.populated(data.path, true); - if (!pop && this.$__.selected) { - // If any array was selected using an $elemMatch projection, we alter the path and where clause - // NOTE: MongoDB only supports projected $elemMatch on top level array. - const pathSplit = data.path.split('.'); - const top = pathSplit[0]; - if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) { - // If the selected array entry was modified - if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') { - where[top] = this.$__.selected[top]; - pathSplit[1] = '$'; - data.path = pathSplit.join('.'); - } - // if the selected array was modified in any other way throw an error - else { - divergent.push(data.path); - continue; - } - } - } - - if (divergent.length) continue; - - if (value === undefined) { - operand(this, where, delta, data, 1, '$unset'); - } else if (value === null) { - operand(this, where, delta, data, null); - } else if (value._path && value._atomics) { - // arrays and other custom types (support plugins etc) - handleAtomics(this, where, delta, data, value); - } else if (value._path && Buffer.isBuffer(value)) { - // MongooseBuffer - value = value.toObject(); - operand(this, where, delta, data, value); - } else { - value = utils.clone(value, { - depopulate: true, - transform: false, - virtuals: false, - _isNested: true - }); - operand(this, where, delta, data, value); - } - } - - if (divergent.length) { - return new DivergentArrayError(divergent); - } - - if (this.$__.version) { - this.$__version(where, delta); - } - - return [where, delta]; -}; - -/*! - * Determine if array was populated with some form of filter and is now - * being updated in a manner which could overwrite data unintentionally. - * - * @see https://github.com/Automattic/mongoose/issues/1334 - * @param {Document} doc - * @param {String} path - * @return {String|undefined} - */ - -function checkDivergentArray(doc, path, array) { - // see if we populated this path - const pop = doc.populated(path, true); - - if (!pop && doc.$__.selected) { - // If any array was selected using an $elemMatch projection, we deny the update. - // NOTE: MongoDB only supports projected $elemMatch on top level array. - const top = path.split('.')[0]; - if (doc.$__.selected[top + '.$']) { - return top; - } - } - - if (!(pop && array && array.isMongooseArray)) return; - - // If the array was populated using options that prevented all - // documents from being returned (match, skip, limit) or they - // deselected the _id field, $pop and $set of the array are - // not safe operations. If _id was deselected, we do not know - // how to remove elements. $pop will pop off the _id from the end - // of the array in the db which is not guaranteed to be the - // same as the last element we have here. $set of the entire array - // would be similarily destructive as we never received all - // elements of the array and potentially would overwrite data. - const check = pop.options.match || - pop.options.options && utils.object.hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted - pop.options.options && pop.options.options.skip || // 0 is permitted - pop.options.select && // deselected _id? - (pop.options.select._id === 0 || - /\s?-_id\s?/.test(pop.options.select)); - - if (check) { - const atomics = array._atomics; - if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) { - return path; - } - } -} - -/** - * Appends versioning to the where and update clauses. - * - * @api private - * @method $__version - * @memberOf Model - * @instance - */ - -Model.prototype.$__version = function(where, delta) { - const key = this.schema.options.versionKey; - - if (where === true) { - // this is an insert - if (key) this.setValue(key, delta[key] = 0); - return; - } - - // updates - - // only apply versioning if our versionKey was selected. else - // there is no way to select the correct version. we could fail - // fast here and force them to include the versionKey but - // thats a bit intrusive. can we do this automatically? - if (!this.isSelected(key)) { - return; - } - - // $push $addToSet don't need the where clause set - if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { - const value = this.getValue(key); - if (value != null) where[key] = value; - } - - if (VERSION_INC === (VERSION_INC & this.$__.version)) { - if (get(delta.$set, key, null) != null) { - // Version key is getting set, means we'll increment the doc's version - // after a successful save, so we should set the incremented version so - // future saves don't fail (gh-5779) - ++delta.$set[key]; - } else { - delta.$inc = delta.$inc || {}; - delta.$inc[key] = 1; - } - } -}; - -/** - * Signal that we desire an increment of this documents version. - * - * ####Example: - * - * Model.findById(id, function (err, doc) { - * doc.increment(); - * doc.save(function (err) { .. }) - * }) - * - * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey - * @api public - */ - -Model.prototype.increment = function increment() { - this.$__.version = VERSION_ALL; - return this; -}; - -/** - * Returns a query object - * - * @api private - * @method $__where - * @memberOf Model - * @instance - */ - -Model.prototype.$__where = function _where(where) { - where || (where = {}); - - if (!where._id) { - where._id = this._doc._id; - } - - if (this._doc._id === void 0) { - return new Error('No _id found on document!'); - } - - return where; -}; - -/** - * Removes this document from the db. - * - * ####Example: - * product.remove(function (err, product) { - * if (err) return handleError(err); - * Product.findById(product._id, function (err, product) { - * console.log(product) // null - * }) - * }) - * - * - * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recieve errors - * - * ####Example: - * product.remove().then(function (product) { - * ... - * }).catch(function (err) { - * assert.ok(err) - * }) - * - * @param {function(err,product)} [fn] optional callback - * @return {Promise} Promise - * @api public - */ - -Model.prototype.remove = function remove(options, fn) { - if (typeof options === 'function') { - fn = options; - options = undefined; - } - - if (!options) { - options = {}; - } - - if (fn) { - fn = this.constructor.$wrapCallback(fn); - } - - return utils.promiseOrCallback(fn, cb => { - this.$__remove(options, cb); - }, this.constructor.events); -}; - -/** - * Alias for remove - */ - -Model.prototype.delete = Model.prototype.remove; - -/*! - * ignore - */ - -Model.prototype.$__remove = function $__remove(options, cb) { - if (this.$__.isDeleted) { - return immediate(() => cb(null, this)); - } - - const where = this.$__where(); - if (where instanceof Error) { - return cb(where); - } - - _applyCustomWhere(this, where); - - if (this.$session() != null) { - options = options || {}; - if (!('session' in options)) { - options.session = this.$session(); - } - } - - this[modelCollectionSymbol].deleteOne(where, options, err => { - if (!err) { - this.$__.isDeleted = true; - this.emit('remove', this); - this.constructor.emit('remove', this); - return cb(null, this); - } - this.$__.isDeleted = false; - cb(err); - }); -}; - -/** - * Returns another Model instance. - * - * ####Example: - * - * var doc = new Tank; - * doc.model('User').findById(id, callback); - * - * @param {String} name model name - * @api public - */ - -Model.prototype.model = function model(name) { - return this.db.model(name); -}; - -/** - * Adds a discriminator type. - * - * ####Example: - * - * function BaseSchema() { - * Schema.apply(this, arguments); - * - * this.add({ - * name: String, - * createdAt: Date - * }); - * } - * util.inherits(BaseSchema, Schema); - * - * var PersonSchema = new BaseSchema(); - * var BossSchema = new BaseSchema({ department: String }); - * - * var Person = mongoose.model('Person', PersonSchema); - * var Boss = Person.discriminator('Boss', BossSchema); - * new Boss().__t; // "Boss". `__t` is the default `discriminatorKey` - * - * var employeeSchema = new Schema({ boss: ObjectId }); - * var Employee = Person.discriminator('Employee', employeeSchema, 'staff'); - * new Employee().__t; // "staff" because of 3rd argument above - * - * @param {String} name discriminator model name - * @param {Schema} schema discriminator model schema - * @param {String} value the string stored in the `discriminatorKey` property - * @api public - */ - -Model.discriminator = function(name, schema, value) { - let model; - if (typeof name === 'function') { - model = name; - name = utils.getFunctionName(model); - if (!(model.prototype instanceof Model)) { - throw new Error('The provided class ' + name + ' must extend Model'); - } - } - - schema = discriminator(this, name, schema, value, true); - if (this.db.models[name]) { - throw new OverwriteModelError(name); - } - - schema.$isRootDiscriminator = true; - schema.$globalPluginsApplied = true; - - model = this.db.model(model || name, schema, this.collection.name); - this.discriminators[name] = model; - const d = this.discriminators[name]; - d.prototype.__proto__ = this.prototype; - Object.defineProperty(d, 'baseModelName', { - value: this.modelName, - configurable: true, - writable: false - }); - - // apply methods and statics - applyMethods(d, schema); - applyStatics(d, schema); - - return d; -}; - -// Model (class) features - -/*! - * Give the constructor the ability to emit events. - */ - -for (const i in EventEmitter.prototype) { - Model[i] = EventEmitter.prototype[i]; -} - -/** - * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/), - * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off. - * - * Mongoose calls this function automatically when a model is created using - * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or - * * [`connection.model()`](/docs/api.html#connection_Connection-model), so you - * don't need to call it. This function is also idempotent, so you may call it - * to get back a promise that will resolve when your indexes are finished - * building as an alternative to [`MyModel.on('index')`](/docs/guide.html#indexes) - * - * ####Example: - * - * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) - * // This calls `Event.init()` implicitly, so you don't need to call - * // `Event.init()` on your own. - * var Event = mongoose.model('Event', eventSchema); - * - * Event.init().then(function(Event) { - * // You can also use `Event.on('index')` if you prefer event emitters - * // over promises. - * console.log('Indexes are done building!'); - * }); - * - * @api public - * @param {Function} [callback] - * @returns {Promise} - */ - -Model.init = function init(callback) { - this.schema.emit('init', this); - - if (this.$init != null) { - if (callback) { - this.$init.then(() => callback(), err => callback(err)); - return null; - } - return this.$init; - } - - // If `dropDatabase()` is called, this model's collection will not be - // init-ed. It is sufficiently common to call `dropDatabase()` after - // `mongoose.connect()` but before creating models that we want to - // support this. See gh-6967 - this.db.$internalEmitter.once('dropDatabase', () => { - delete this.$init; - }); - - const Promise = PromiseProvider.get(); - const autoIndex = this.schema.options.autoIndex == null ? - this.db.config.autoIndex : - this.schema.options.autoIndex; - const autoCreate = this.schema.options.autoCreate == null ? - this.db.config.autoCreate : - this.schema.options.autoCreate; - - const _ensureIndexes = autoIndex ? - cb => this.ensureIndexes({ _automatic: true }, cb) : - cb => cb(); - const _createCollection = autoCreate ? - cb => this.createCollection({}, cb) : - cb => cb(); - - this.$init = new Promise((resolve, reject) => { - _createCollection(error => { - if (error) { - return reject(error); - } - _ensureIndexes(error => { - if (error) { - return reject(error); - } - resolve(this); - }); - }); - }); - - if (callback) { - this.$init.then(() => callback(), err => callback(err)); - this.$caught = true; - return null; - } else { - const _catch = this.$init.catch; - const _this = this; - this.$init.catch = function() { - this.$caught = true; - return _catch.apply(_this.$init, arguments); - }; - } - - return this.$init; -}; - - -/** - * Create the collection for this model. By default, if no indexes are specified, - * mongoose will not create the collection for the model until any documents are - * created. Use this method to create the collection explicitly. - * - * Note 1: You may need to call this before starting a transaction - * See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations - * - * Note 2: You don't have to call this if your schema contains index or unique field. - * In that case, just use `Model.init()` - * - * ####Example: - * - * var userSchema = new Schema({ name: String }) - * var User = mongoose.model('User', userSchema); - * - * User.createCollection().then(function(collection) { - * console.log('Collection is created!'); - * }); - * - * @api public - * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection) - * @param {Function} [callback] - * @returns {Promise} - */ - -Model.createCollection = function createCollection(options, callback) { - if (typeof options === 'string') { - throw new Error('You can\'t specify a new collection name in Model.createCollection.' + - 'This is not like Connection.createCollection. Only options are accepted here.'); - } else if (typeof options === 'function') { - callback = options; - options = null; - } - - if (callback) { - callback = this.$wrapCallback(callback); - } - - const schemaCollation = get(this, 'schema.options.collation', null); - if (schemaCollation != null) { - options = Object.assign({ collation: schemaCollation }, options); - } - - return utils.promiseOrCallback(callback, cb => { - this.db.createCollection(this.collection.collectionName, options, utils.tick((error) => { - if (error) { - return cb(error); - } - this.collection = this.db.collection(this.collection.collectionName, options); - cb(null, this.collection); - })); - }, this.events); -}; - -/** - * Makes the indexes in MongoDB match the indexes defined in this model's - * schema. This function will drop any indexes that are not defined in - * the model's schema except the `_id` index, and build any indexes that - * are in your schema but not in MongoDB. - * - * See the [introductory blog post](http://thecodebarbarian.com/whats-new-in-mongoose-5-2-syncindexes) - * for more information. - * - * ####Example: - * - * const schema = new Schema({ name: { type: String, unique: true } }); - * const Customer = mongoose.model('Customer', schema); - * await Customer.createIndex({ age: 1 }); // Index is not in schema - * // Will drop the 'age' index and create an index on `name` - * await Customer.syncIndexes(); - * - * @param {Object} [options] options to pass to `ensureIndexes()` - * @param {Function} [callback] optional callback - * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. - * @api public - */ - -Model.syncIndexes = function syncIndexes(options, callback) { - callback = this.$wrapCallback(callback); - - const dropNonSchemaIndexes = (cb) => { - this.listIndexes((err, indexes) => { - if (err != null) { - return cb(err); - } - - const schemaIndexes = this.schema.indexes(); - const toDrop = []; - - for (const index of indexes) { - let found = false; - // Never try to drop `_id` index, MongoDB server doesn't allow it - if (index.key._id) { - continue; - } - - for (const schemaIndex of schemaIndexes) { - const key = schemaIndex[0]; - const options = _decorateDiscriminatorIndexOptions(this, - utils.clone(schemaIndex[1])); - - // If these options are different, need to rebuild the index - const optionKeys = ['unique', 'partialFilterExpression', 'sparse', 'expireAfterSeconds']; - const indexCopy = Object.assign({}, index); - for (const key of optionKeys) { - if (!(key in options) && !(key in indexCopy)) { - continue; - } - indexCopy[key] = options[key]; - } - if (utils.deepEqual(key, index.key) && - utils.deepEqual(index, indexCopy)) { - found = true; - break; - } - } - - if (!found) { - toDrop.push(index.name); - } - } - - if (toDrop.length === 0) { - return cb(null, []); - } - - dropIndexes(toDrop, cb); - }); - }; - - const dropIndexes = (toDrop, cb) => { - let remaining = toDrop.length; - let error = false; - toDrop.forEach(indexName => { - this.collection.dropIndex(indexName, err => { - if (err != null) { - error = true; - return cb(err); - } - if (!error) { - --remaining || cb(null, toDrop); - } - }); - }); - }; - - return utils.promiseOrCallback(callback, cb => { - dropNonSchemaIndexes((err, dropped) => { - if (err != null) { - return cb(err); - } - this.createIndexes(options, err => { - if (err != null) { - return cb(err); - } - cb(null, dropped); - }); - }); - }, this.events); -}; - -/** - * Lists the indexes currently defined in MongoDB. This may or may not be - * the same as the indexes defined in your schema depending on whether you - * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you - * build indexes manually. - * - * @param {Function} [cb] optional callback - * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. - * @api public - */ - -Model.listIndexes = function init(callback) { - callback = this.$wrapCallback(callback); - - const _listIndexes = cb => { - this.collection.listIndexes().toArray(cb); - }; - - return utils.promiseOrCallback(callback, cb => { - // Buffering - if (this.collection.buffer) { - this.collection.addQueue(_listIndexes, [cb]); - } else { - _listIndexes(cb); - } - }, this.events); -}; - -/** - * Sends `createIndex` commands to mongo for each index declared in the schema. - * The `createIndex` commands are sent in series. - * - * ####Example: - * - * Event.ensureIndexes(function (err) { - * if (err) return handleError(err); - * }); - * - * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. - * - * ####Example: - * - * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) - * var Event = mongoose.model('Event', eventSchema); - * - * Event.on('index', function (err) { - * if (err) console.error(err); // error occurred during index creation - * }) - * - * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ - * - * @param {Object} [options] internal options - * @param {Function} [cb] optional callback - * @return {Promise} - * @api public - */ - -Model.ensureIndexes = function ensureIndexes(options, callback) { - if (typeof options === 'function') { - callback = options; - options = null; - } - - if (callback) { - callback = this.$wrapCallback(callback); - } - - return utils.promiseOrCallback(callback, cb => { - _ensureIndexes(this, options || {}, error => { - if (error) { - return cb(error); - } - cb(null); - }); - }, this.events); -}; - -/** - * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex) - * function. - * - * @param {Object} [options] internal options - * @param {Function} [cb] optional callback - * @return {Promise} - * @api public - */ - -Model.createIndexes = function createIndexes(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - options.createIndex = true; - return this.ensureIndexes(options, callback); -}; - -/*! - * ignore - */ - -function _ensureIndexes(model, options, callback) { - const indexes = model.schema.indexes(); - - options = options || {}; - - const done = function(err) { - if (err && !model.$caught) { - model.emit('error', err); - } - model.emit('index', err); - callback && callback(err); - }; - - for (const index of indexes) { - const keys = Object.keys(index[0]); - if (keys.length === 1 && keys[0] === '_id' && index[0]._id !== 'hashed') { - console.warn('mongoose: Cannot specify a custom index on `_id` for ' + - 'model name "' + model.modelName + '", ' + - 'MongoDB does not allow overwriting the default `_id` index. See ' + - 'http://bit.ly/mongodb-id-index'); - } - } - - if (!indexes.length) { - immediate(function() { - done(); - }); - return; - } - // Indexes are created one-by-one to support how MongoDB < 2.4 deals - // with background indexes. - - const indexSingleDone = function(err, fields, options, name) { - model.emit('index-single-done', err, fields, options, name); - }; - const indexSingleStart = function(fields, options) { - model.emit('index-single-start', fields, options); - }; - - const create = function() { - if (options._automatic) { - if (model.schema.options.autoIndex === false || - (model.schema.options.autoIndex == null && model.db.config.autoIndex === false)) { - return done(); - } - } - - const index = indexes.shift(); - if (!index) { - return done(); - } - - const indexFields = utils.clone(index[0]); - const indexOptions = utils.clone(index[1]); - - _decorateDiscriminatorIndexOptions(model, indexOptions); - if ('safe' in options) { - _handleSafe(options); - } - applyWriteConcern(model.schema, indexOptions); - - indexSingleStart(indexFields, options); - let useCreateIndex = !!model.base.options.useCreateIndex; - if ('useCreateIndex' in model.db.config) { - useCreateIndex = !!model.db.config.useCreateIndex; - } - if ('createIndex' in options) { - useCreateIndex = !!options.createIndex; - } - - const methodName = useCreateIndex ? 'createIndex' : 'ensureIndex'; - model.collection[methodName](indexFields, indexOptions, utils.tick(function(err, name) { - indexSingleDone(err, indexFields, indexOptions, name); - if (err) { - return done(err); - } - create(); - })); - }; - - immediate(function() { - // If buffering is off, do this manually. - if (options._automatic && !model.collection.collection) { - model.collection.addQueue(create, []); - } else { - create(); - } - }); -} - -function _decorateDiscriminatorIndexOptions(model, indexOptions) { - // If the model is a discriminator and it has a unique index, add a - // partialFilterExpression by default so the unique index will only apply - // to that discriminator. - if (model.baseModelName != null && indexOptions.unique && - !('partialFilterExpression' in indexOptions) && - !('sparse' in indexOptions)) { - indexOptions.partialFilterExpression = { - [model.schema.options.discriminatorKey]: model.modelName - }; - } - return indexOptions; -} - -const safeDeprecationWarning = 'Mongoose: the `safe` option for `save()` is ' + - 'deprecated. Use the `w` option instead: http://bit.ly/mongoose-save'; - -const _handleSafe = util.deprecate(function _handleSafe(options) { - if (options.safe) { - if (typeof options.safe === 'boolean') { - options.w = options.safe; - delete options.safe; - } - if (typeof options.safe === 'object') { - options.w = options.safe.w; - options.j = options.safe.j; - options.wtimeout = options.safe.wtimeout; - delete options.safe; - } - } -}, safeDeprecationWarning); - -/** - * Schema the model uses. - * - * @property schema - * @receiver Model - * @api public - * @memberOf Model - */ - -Model.schema; - -/*! - * Connection instance the model uses. - * - * @property db - * @api public - * @memberOf Model - */ - -Model.db; - -/*! - * Collection the model uses. - * - * @property collection - * @api public - * @memberOf Model - */ - -Model.collection; - -/** - * Base Mongoose instance the model uses. - * - * @property base - * @api public - * @memberOf Model - */ - -Model.base; - -/** - * Registered discriminators for this model. - * - * @property discriminators - * @api public - * @memberOf Model - */ - -Model.discriminators; - -/** - * Translate any aliases fields/conditions so the final query or document object is pure - * - * ####Example: - * - * Character - * .find(Character.translateAliases({ - * '名': 'Eddard Stark' // Alias for 'name' - * }) - * .exec(function(err, characters) {}) - * - * ####Note: - * Only translate arguments of object type anything else is returned raw - * - * @param {Object} raw fields/conditions that may contain aliased keys - * @return {Object} the translated 'pure' fields/conditions - */ -Model.translateAliases = function translateAliases(fields) { - if (typeof fields === 'object') { - // Fields is an object (query conditions or document fields) - for (const key in fields) { - let alias; - const translated = []; - const fieldKeys = key.split('.'); - let currentSchema = this.schema; - for (const field in fieldKeys) { - const name = fieldKeys[field]; - if (currentSchema && currentSchema.aliases[name]) { - alias = currentSchema.aliases[name]; - // Alias found, - translated.push(alias); - } else { - // Alias not found, so treat as un-aliased key - translated.push(name); - } - - // Check if aliased path is a schema - if (currentSchema.paths[alias]) - currentSchema = currentSchema.paths[alias].schema; - else - currentSchema = null; - } - - const translatedKey = translated.join('.'); - fields[translatedKey] = fields[key]; - if (translatedKey !== key) - delete fields[key]; // We'll be using the translated key instead - } - - return fields; - } else { - // Don't know typeof fields - return fields; - } -}; - -/** - * Removes all documents that match `conditions` from the collection. - * To remove just the first document that matches `conditions`, set the `single` - * option to true. - * - * ####Example: - * - * Character.remove({ name: 'Eddard Stark' }, function (err) {}); - * - * ####Note: - * - * This method sends a remove command directly to MongoDB, no Mongoose documents - * are involved. Because no Mongoose documents are involved, _no middleware - * (hooks) are executed_. - * - * @param {Object} conditions - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.remove = function remove(conditions, callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - } - - // get the mongodb collection object - const mq = new this.Query({}, {}, this, this.collection); - - callback = this.$wrapCallback(callback); - - return mq.remove(conditions, callback); -}; - -/** - * Deletes the first document that matches `conditions` from the collection. - * Behaves like `remove()`, but deletes at most one document regardless of the - * `single` option. - * - * ####Example: - * - * Character.deleteOne({ name: 'Eddard Stark' }, function (err) {}); - * - * ####Note: - * - * Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks. - * - * @param {Object} conditions - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.deleteOne = function deleteOne(conditions, callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - } - - // get the mongodb collection object - const mq = new this.Query(conditions, {}, this, this.collection); - - callback = this.$wrapCallback(callback); - - return mq.deleteOne(callback); -}; - -/** - * Deletes all of the documents that match `conditions` from the collection. - * Behaves like `remove()`, but deletes all documents that match `conditions` - * regardless of the `single` option. - * - * ####Example: - * - * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {}); - * - * ####Note: - * - * Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks. - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.deleteMany = function deleteMany(conditions, options, callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - options = null; - } - else if (typeof options === 'function') { - callback = options; - options = null; - } - - // get the mongodb collection object - const mq = new this.Query(conditions, {}, this, this.collection); - mq.setOptions(options); - - if (callback) { - callback = this.$wrapCallback(callback); - } - - return mq.deleteMany(callback); -}; - -/** - * Finds documents - * - * The `conditions` are cast to their respective SchemaTypes before the command is sent. - * - * ####Examples: - * - * // named john and at least 18 - * MyModel.find({ name: 'john', age: { $gte: 18 }}); - * - * // executes, passing results to callback - * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); - * - * // executes, name LIKE john and only selecting the "name" and "friends" fields - * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) - * - * // passing options - * MyModel.find({ name: /john/i }, null, { skip: 10 }) - * - * // passing options and executes - * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); - * - * // executing a query explicitly - * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }) - * query.exec(function (err, docs) {}); - * - * // using the promise returned from executing a query - * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }); - * var promise = query.exec(); - * promise.addBack(function (err, docs) {}); - * - * @param {Object} conditions - * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see promise #promise-js - * @api public - */ - -Model.find = function find(conditions, projection, options, callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - projection = null; - options = null; - } else if (typeof projection === 'function') { - callback = projection; - projection = null; - options = null; - } else if (typeof options === 'function') { - callback = options; - options = null; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(projection); - - mq.setOptions(options); - if (this.schema.discriminatorMapping && - this.schema.discriminatorMapping.isRoot && - mq.selectedInclusively()) { - // Need to select discriminator key because original schema doesn't have it - mq.select(this.schema.options.discriminatorKey); - } - - if (callback) { - callback = this.$wrapCallback(callback); - } - - return mq.find(conditions, callback); -}; - -/** - * Finds a single document by its _id field. `findById(id)` is almost* - * equivalent to `findOne({ _id: id })`. If you want to query by a document's - * `_id`, use `findById()` instead of `findOne()`. - * - * The `id` is cast based on the Schema before sending the command. - * - * This function triggers the following middleware. - * - * - `findOne()` - * - * \* Except for how it treats `undefined`. If you use `findOne()`, you'll see - * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent - * to `findOne({})` and return arbitrary documents. However, mongoose - * translates `findById(undefined)` into `findOne({ _id: null })`. - * - * ####Example: - * - * // find adventure by id and execute - * Adventure.findById(id, function (err, adventure) {}); - * - * // same as above - * Adventure.findById(id).exec(callback); - * - * // select only the adventures name and length - * Adventure.findById(id, 'name length', function (err, adventure) {}); - * - * // same as above - * Adventure.findById(id, 'name length').exec(callback); - * - * // include all properties except for `length` - * Adventure.findById(id, '-length').exec(function (err, adventure) {}); - * - * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean` - * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {}); - * - * // same as above - * Adventure.findById(id, 'name').lean().exec(function (err, doc) {}); - * - * @param {Object|String|Number} id value of `_id` to query by - * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see lean queries #query_Query-lean - * @api public - */ - -Model.findById = function findById(id, projection, options, callback) { - if (typeof id === 'undefined') { - id = null; - } - - if (callback) { - callback = this.$wrapCallback(callback); - } - - return this.findOne({_id: id}, projection, options, callback); -}; - -/** - * Finds one document. - * - * The `conditions` are cast to their respective SchemaTypes before the command is sent. - * - * *Note:* `conditions` is optional, and if `conditions` is null or undefined, - * mongoose will send an empty `findOne` command to MongoDB, which will return - * an arbitrary document. If you're querying by `_id`, use `findById()` instead. - * - * ####Example: - * - * // find one iphone adventures - iphone adventures?? - * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {}); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); - * - * // select only the adventures name - * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); - * - * // specify options, in this case lean - * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback); - * - * // chaining findOne queries (same as above) - * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback); - * - * @param {Object} [conditions] - * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see lean queries #query_Query-lean - * @api public - */ - -Model.findOne = function findOne(conditions, projection, options, callback) { - if (typeof options === 'function') { - callback = options; - options = null; - } else if (typeof projection === 'function') { - callback = projection; - projection = null; - options = null; - } else if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - projection = null; - options = null; - } - - // get the mongodb collection object - const mq = new this.Query({}, {}, this, this.collection); - mq.select(projection); - - mq.setOptions(options); - if (this.schema.discriminatorMapping && - this.schema.discriminatorMapping.isRoot && - mq.selectedInclusively()) { - mq.select(this.schema.options.discriminatorKey); - } - - if (callback) { - callback = this.$wrapCallback(callback); - } - - return mq.findOne(conditions, callback); -}; - -/** - * Estimates the number of documents in the MongoDB collection. Faster than - * using `countDocuments()` for large collections because - * `estimatedDocumentCount()` uses collection metadata rather than scanning - * the entire collection. - * - * ####Example: - * - * const numAdventures = Adventure.estimatedDocumentCount(); - * - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.estimatedDocumentCount = function estimatedDocumentCount(options, callback) { - // get the mongodb collection object - const mq = new this.Query({}, {}, this, this.collection); - - callback = this.$wrapCallback(callback); - - return mq.estimatedDocumentCount(options, callback); -}; - -/** - * Counts number of documents matching `filter` in a database collection. - * - * ####Example: - * - * Adventure.countDocuments({ type: 'jungle' }, function (err, count) { - * console.log('there are %d jungle adventures', count); - * }); - * - * If you want to count all documents in a large collection, - * use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) - * instead. If you call `countDocuments({})`, MongoDB will always execute - * a full collection scan and **not** use any indexes. - * - * The `countDocuments()` function is similar to `count()`, but there are a - * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). - * Below are the operators that `count()` supports but `countDocuments()` does not, - * and the suggested replacement: - * - * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) - * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) - * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) - * - * @param {Object} filter - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.countDocuments = function countDocuments(conditions, callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - } - - // get the mongodb collection object - const mq = new this.Query({}, {}, this, this.collection); - - callback = this.$wrapCallback(callback); - - return mq.countDocuments(conditions, callback); -}; - -/** - * Counts number of documents that match `filter` in a database collection. - * - * This method is deprecated. If you want to count the number of documents in - * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) - * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#model_Model.countDocuments) function instead. - * - * ####Example: - * - * Adventure.count({ type: 'jungle' }, function (err, count) { - * if (err) .. - * console.log('there are %d jungle adventures', count); - * }); - * - * @deprecated - * @param {Object} filter - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.count = function count(conditions, callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - } - - // get the mongodb collection object - const mq = new this.Query({}, {}, this, this.collection); - - if (callback) { - callback = this.$wrapCallback(callback); - } - - return mq.count(conditions, callback); -}; - -/** - * Creates a Query for a `distinct` operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { - * if (err) return handleError(err); - * - * assert(Array.isArray(result)); - * console.log('unique urls with more than 100 clicks', result); - * }) - * - * var query = Link.distinct('url'); - * query.exec(callback); - * - * @param {String} field - * @param {Object} [conditions] optional - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.distinct = function distinct(field, conditions, callback) { - // get the mongodb collection object - const mq = new this.Query({}, {}, this, this.collection); - - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - } - if (callback) { - callback = this.$wrapCallback(callback); - } - - return mq.distinct(field, conditions, callback); -}; - -/** - * Creates a Query, applies the passed conditions, and returns the Query. - * - * For example, instead of writing: - * - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * we can instead write: - * - * User.where('age').gte(21).lte(65).exec(callback); - * - * Since the Query class also supports `where` you can continue chaining - * - * User - * .where('age').gte(21).lte(65) - * .where('name', /^b/i) - * ... etc - * - * @param {String} path - * @param {Object} [val] optional value - * @return {Query} - * @api public - */ - -Model.where = function where(path, val) { - void val; // eslint - // get the mongodb collection object - const mq = new this.Query({}, {}, this, this.collection).find({}); - return mq.where.apply(mq, arguments); -}; - -/** - * Creates a `Query` and specifies a `$where` condition. - * - * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. - * - * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {}); - * - * @param {String|Function} argument is a javascript string or anonymous function - * @method $where - * @memberOf Model - * @return {Query} - * @see Query.$where #query_Query-%24where - * @api public - */ - -Model.$where = function $where() { - const mq = new this.Query({}, {}, this, this.collection).find({}); - return mq.$where.apply(mq, arguments); -}; - -/** - * Issues a mongodb findAndModify 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 if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndUpdate(conditions, update, options, callback) // executes - * A.findOneAndUpdate(conditions, update, options) // returns Query - * A.findOneAndUpdate(conditions, update, callback) // executes - * A.findOneAndUpdate(conditions, update) // returns Query - * A.findOneAndUpdate() // returns Query - * - * ####Note: - * - * All top level update keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * var query = { name: 'borne' }; - * Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback) - * - * // is sent as - * Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback) - * - * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. - * - * ####Note: - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object} [conditions] - * @param {Object} [update] - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean). - * @param {Function} [callback] - * @return {Query} - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findOneAndUpdate = function(conditions, update, options, callback) { - if (typeof options === 'function') { - callback = options; - options = null; - } else if (arguments.length === 1) { - if (typeof conditions === 'function') { - const msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n' - + ' ' + this.modelName + '.findOneAndUpdate(update)\n' - + ' ' + this.modelName + '.findOneAndUpdate()\n'; - throw new TypeError(msg); - } - update = conditions; - conditions = undefined; - } - if (callback) { - callback = this.$wrapCallback(callback); - } - - let fields; - if (options) { - fields = options.fields || options.projection; - } - - update = utils.clone(update, { - depopulate: true, - _isNested: true - }); - - _decorateUpdateWithVersionKey(update, options, this.schema.options.versionKey); - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndUpdate(conditions, update, options, callback); -}; - -/*! - * Decorate the update with a version key, if necessary - */ - -function _decorateUpdateWithVersionKey(update, options, versionKey) { - if (!versionKey || !get(options, 'upsert', false)) { - return; - } - - const updatedPaths = modifiedPaths(update); - if (!updatedPaths[versionKey]) { - if (options.overwrite) { - update[versionKey] = 0; - } else { - if (!update.$setOnInsert) { - update.$setOnInsert = {}; - } - update.$setOnInsert[versionKey] = 0; - } - } -} - -/** - * Issues a mongodb findAndModify update command by a document's _id field. - * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`. - * - * 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 if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndUpdate()` - * - * ####Options: - * - * - `new`: bool - true to return the modified document rather than the original. defaults to false - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findByIdAndUpdate(id, update, options, callback) // executes - * A.findByIdAndUpdate(id, update, options) // returns Query - * A.findByIdAndUpdate(id, update, callback) // executes - * A.findByIdAndUpdate(id, update) // returns Query - * A.findByIdAndUpdate() // returns Query - * - * ####Note: - * - * All top level update keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback) - * - * // is sent as - * Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback) - * - * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. - * - * ####Note: - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object|Number|String} id value of `_id` to query by - * @param {Object} [update] - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean). - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findByIdAndUpdate = function(id, update, options, callback) { - if (callback) { - callback = this.$wrapCallback(callback); - } - if (arguments.length === 1) { - if (typeof id === 'function') { - const msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' - + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' - + ' ' + this.modelName + '.findByIdAndUpdate()\n'; - throw new TypeError(msg); - } - return this.findOneAndUpdate({_id: id}, undefined); - } - - // if a model is passed in instead of an id - if (id instanceof Document) { - id = id._id; - } - - return this.findOneAndUpdate.call(this, {_id: id}, update, options, callback); -}; - -/** - * Issue a MongoDB `findOneAndDelete()` command. - * - * Finds a matching document, removes it, and passes the found document - * (if any) to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndDelete()` - * - * This function differs slightly from `Model.findOneAndRemove()` in that - * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), - * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, - * this distinction is purely pedantic. You should use `findOneAndDelete()` - * unless you have a good reason not to. - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `select`: sets the document fields to return - * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndDelete(conditions, options, callback) // executes - * A.findOneAndDelete(conditions, options) // return Query - * A.findOneAndDelete(conditions, callback) // executes - * A.findOneAndDelete(conditions) // returns Query - * A.findOneAndDelete() // returns Query - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.findOneAndDelete = function(conditions, options, callback) { - if (arguments.length === 1 && typeof conditions === 'function') { - const msg = 'Model.findOneAndDelete(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndDelete(conditions, callback)\n' - + ' ' + this.modelName + '.findOneAndDelete(conditions)\n' - + ' ' + this.modelName + '.findOneAndDelete()\n'; - throw new TypeError(msg); - } - - if (typeof options === 'function') { - callback = options; - options = undefined; - } - if (callback) { - callback = this.$wrapCallback(callback); - } - - let fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndDelete(conditions, options, callback); -}; - -/** - * Issue a MongoDB `findOneAndDelete()` command by a document's _id field. - * In other words, `findByIdAndDelete(id)` is a shorthand for - * `findOneAndDelete({ _id: id })`. - * - * This function triggers the following middleware. - * - * - `findOneAndDelete()` - * - * @param {Object|Number|String} id value of `_id` to query by - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndRemove #model_Model.findOneAndRemove - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - */ - -Model.findByIdAndDelete = function(id, options, callback) { - if (arguments.length === 1 && typeof id === 'function') { - const msg = 'Model.findByIdAndDelete(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findByIdAndDelete(id, callback)\n' - + ' ' + this.modelName + '.findByIdAndDelete(id)\n' - + ' ' + this.modelName + '.findByIdAndDelete()\n'; - throw new TypeError(msg); - } - if (callback) { - callback = this.$wrapCallback(callback); - } - - return this.findOneAndDelete({_id: id}, options, callback); -}; - -/** - * Issue a MongoDB `findOneAndReplace()` command. - * - * Finds a matching document, replaces it with the provided doc, and passes the - * returned doc to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following query middleware. - * - * - `findOneAndReplace()` - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `select`: sets the document fields to return - * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndReplace(conditions, options, callback) // executes - * A.findOneAndReplace(conditions, options) // return Query - * A.findOneAndReplace(conditions, callback) // executes - * A.findOneAndReplace(conditions) // returns Query - * A.findOneAndReplace() // returns Query - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.findOneAndReplace = function(conditions, options, callback) { - if (arguments.length === 1 && typeof conditions === 'function') { - const msg = 'Model.findOneAndDelete(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndDelete(conditions, callback)\n' - + ' ' + this.modelName + '.findOneAndDelete(conditions)\n' - + ' ' + this.modelName + '.findOneAndDelete()\n'; - throw new TypeError(msg); - } - - if (typeof options === 'function') { - callback = options; - options = undefined; - } - if (callback) { - callback = this.$wrapCallback(callback); - } - - let fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndReplace(conditions, options, callback); -}; - -/** - * Issue a mongodb findAndModify remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndRemove()` - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `select`: sets the document fields to return - * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndRemove(conditions, options, callback) // executes - * A.findOneAndRemove(conditions, options) // return Query - * A.findOneAndRemove(conditions, callback) // executes - * A.findOneAndRemove(conditions) // returns Query - * A.findOneAndRemove() // returns Query - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findOneAndRemove = function(conditions, options, callback) { - if (arguments.length === 1 && typeof conditions === 'function') { - const msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' - + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' - + ' ' + this.modelName + '.findOneAndRemove()\n'; - throw new TypeError(msg); - } - - if (typeof options === 'function') { - callback = options; - options = undefined; - } - if (callback) { - callback = this.$wrapCallback(callback); - } - - let fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndRemove(conditions, options, callback); -}; - -/** - * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndRemove()` - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findByIdAndRemove(id, options, callback) // executes - * A.findByIdAndRemove(id, options) // return Query - * A.findByIdAndRemove(id, callback) // executes - * A.findByIdAndRemove(id) // returns Query - * A.findByIdAndRemove() // returns Query - * - * @param {Object|Number|String} id value of `_id` to query by - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndRemove #model_Model.findOneAndRemove - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - */ - -Model.findByIdAndRemove = function(id, options, callback) { - if (arguments.length === 1 && typeof id === 'function') { - const msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' - + ' ' + this.modelName + '.findByIdAndRemove(id)\n' - + ' ' + this.modelName + '.findByIdAndRemove()\n'; - throw new TypeError(msg); - } - if (callback) { - callback = this.$wrapCallback(callback); - } - - return this.findOneAndRemove({_id: id}, options, callback); -}; - -/** - * Shortcut for saving one or more documents to the database. - * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in - * docs. - * - * This function triggers the following middleware. - * - * - `save()` - * - * ####Example: - * - * // pass a spread of docs and a callback - * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) { - * if (err) // ... - * }); - * - * // pass an array of docs - * var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; - * Candy.create(array, function (err, candies) { - * if (err) // ... - * - * var jellybean = candies[0]; - * var snickers = candies[1]; - * // ... - * }); - * - * // callback is optional; use the returned promise if you like: - * var promise = Candy.create({ type: 'jawbreaker' }); - * promise.then(function (jawbreaker) { - * // ... - * }) - * - * @param {Array|Object} docs Documents to insert, as a spread or array - * @param {Object} [options] Options passed down to `save()`. To specify `options`, `docs` **must** be an array, not a spread. - * @param {Function} [callback] callback - * @return {Promise} - * @api public - */ - -Model.create = function create(doc, options, callback) { - let args; - let cb; - const discriminatorKey = this.schema.options.discriminatorKey; - - if (Array.isArray(doc)) { - args = doc; - cb = typeof options === 'function' ? options : callback; - options = options != null && typeof options === 'object' ? options : {}; - } else { - const last = arguments[arguments.length - 1]; - options = {}; - // Handle falsy callbacks re: #5061 - if (typeof last === 'function' || !last) { - cb = last; - args = utils.args(arguments, 0, arguments.length - 1); - } else { - args = utils.args(arguments); - } - } - - if (cb) { - cb = this.$wrapCallback(cb); - } - - return utils.promiseOrCallback(cb, cb => { - if (args.length === 0) { - return cb(null); - } - - const toExecute = []; - let firstError; - args.forEach(doc => { - toExecute.push(callback => { - const Model = this.discriminators && doc[discriminatorKey] != null ? - this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this, doc[discriminatorKey]) : - this; - if (Model == null) { - throw new Error(`Discriminator "${doc[discriminatorKey]}" not ` + - `found for model "${this.modelName}"`); - } - let toSave = doc; - const callbackWrapper = (error, doc) => { - if (error) { - if (!firstError) { - firstError = error; - } - return callback(null, { error: error }); - } - callback(null, { doc: doc }); - }; - - if (!(toSave instanceof Model)) { - try { - toSave = new Model(toSave); - } catch (error) { - return callbackWrapper(error); - } - } - - toSave.save(options, callbackWrapper); - }); - }); - - parallel(toExecute, (error, res) => { - const savedDocs = []; - const len = res.length; - for (let i = 0; i < len; ++i) { - if (res[i].doc) { - savedDocs.push(res[i].doc); - } - } - - if (firstError) { - return cb(firstError, savedDocs); - } - - if (doc instanceof Array) { - cb(null, savedDocs); - } else { - cb.apply(this, [null].concat(savedDocs)); - } - }); - }, this.events); -}; - -/** - * _Requires a replica set running MongoDB >= 3.6.0._ Watches the - * underlying collection for changes using - * [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). - * - * This function does **not** trigger any middleware. In particular, it - * does **not** trigger aggregate middleware. - * - * The ChangeStream object is an event emitter that emits the following events: - * - * - 'change': A change occurred, see below example - * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates. - * - 'end': Emitted if the underlying stream is closed - * - 'close': Emitted if the underlying stream is closed - * - * ####Example: - * - * const doc = await Person.create({ name: 'Ned Stark' }); - * const changeStream = Person.watch().on('change', change => console.log(change)); - * // Will print from the above `console.log()`: - * // { _id: { _data: ... }, - * // operationType: 'delete', - * // ns: { db: 'mydb', coll: 'Person' }, - * // documentKey: { _id: 5a51b125c5500f5aa094c7bd } } - * await doc.remove(); - * - * @param {Array} [pipeline] - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch) - * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter - * @api public - */ - -Model.watch = function(pipeline, options) { - return new ChangeStream(this, pipeline, options); -}; - -/** - * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) - * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), - * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). - * - * Calling `MyModel.startSession()` is equivalent to calling `MyModel.db.startSession()`. - * - * This function does not trigger any middleware. - * - * ####Example: - * - * const session = await Person.startSession(); - * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); - * await doc.remove(); - * // `doc` will always be null, even if reading from a replica set - * // secondary. Without causal consistency, it is possible to - * // get a doc back from the below query if the query reads from a - * // secondary that is experiencing replication lag. - * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); - * - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) - * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency - * @param {Function} [callback] - * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession` - * @api public - */ - -Model.startSession = function() { - return this.db.startSession.apply(this.db, arguments); -}; - -/** - * Shortcut for validating an array of documents and inserting them into - * MongoDB if they're all valid. This function is faster than `.create()` - * because it only sends one operation to the server, rather than one for each - * document. - * - * Mongoose always validates each document **before** sending `insertMany` - * to MongoDB. So if one document has a validation error, no documents will - * be saved, unless you set - * [the `ordered` option to false](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#error-handling). - * - * This function does **not** trigger save middleware. - * - * This function triggers the following middleware. - * - * - `insertMany()` - * - * ####Example: - * - * var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }]; - * Movies.insertMany(arr, function(error, docs) {}); - * - * @param {Array|Object|*} doc(s) - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany) - * @param {Boolean} [options.ordered = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`. - * @param {Boolean} [options.rawResult = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. - * @param {Function} [callback] callback - * @return {Promise} - * @api public - */ - -Model.insertMany = function(arr, options, callback) { - if (typeof options === 'function') { - callback = options; - options = null; - } - return utils.promiseOrCallback(callback, cb => { - this.$__insertMany(arr, options, cb); - }, this.events); -}; - -/*! - * ignore - */ - -Model.$__insertMany = function(arr, options, callback) { - const _this = this; - if (typeof options === 'function') { - callback = options; - options = null; - } - if (callback) { - callback = this.$wrapCallback(callback); - } - callback = callback || utils.noop; - options = options || {}; - const limit = get(options, 'limit', 1000); - const rawResult = get(options, 'rawResult', false); - const ordered = get(options, 'ordered', true); - - if (!Array.isArray(arr)) { - arr = [arr]; - } - - const toExecute = []; - const validationErrors = []; - arr.forEach(function(doc) { - toExecute.push(function(callback) { - if (!(doc instanceof _this)) { - doc = new _this(doc); - } - doc.validate({ __noPromise: true }, function(error) { - if (error) { - // Option `ordered` signals that insert should be continued after reaching - // a failing insert. Therefore we delegate "null", meaning the validation - // failed. It's up to the next function to filter out all failed models - if (ordered === false) { - validationErrors.push(error); - return callback(null, null); - } - return callback(error); - } - callback(null, doc); - }); - }); - }); - - parallelLimit(toExecute, limit, function(error, docs) { - if (error) { - callback(error, null); - return; - } - // We filter all failed pre-validations by removing nulls - const docAttributes = docs.filter(function(doc) { - return doc != null; - }); - // Quickly escape while there aren't any valid docAttributes - if (docAttributes.length < 1) { - callback(null, []); - return; - } - const docObjects = docAttributes.map(function(doc) { - if (doc.schema.options.versionKey) { - doc[doc.schema.options.versionKey] = 0; - } - if (doc.initializeTimestamps) { - return doc.initializeTimestamps().toObject(internalToObjectOptions); - } - return doc.toObject(internalToObjectOptions); - }); - - _this.collection.insertMany(docObjects, options, function(error, res) { - if (error) { - callback(error, null); - return; - } - for (let i = 0; i < docAttributes.length; ++i) { - docAttributes[i].isNew = false; - docAttributes[i].emit('isNew', false); - docAttributes[i].constructor.emit('isNew', false); - } - if (rawResult) { - if (ordered === false) { - // Decorate with mongoose validation errors in case of unordered, - // because then still do `insertMany()` - res.mongoose = { - validationErrors: validationErrors - }; - } - return callback(null, res); - } - callback(null, docAttributes); - }); - }); -}; - -/** - * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`, - * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one - * command. This is faster than sending multiple independent operations (like) - * if you use `create()`) because with `bulkWrite()` there is only one round - * trip to MongoDB. - * - * Mongoose will perform casting on all operations you provide. - * - * This function does **not** trigger any middleware, not `save()` nor `update()`. - * If you need to trigger - * `save()` middleware for every document use [`create()`](http://mongoosejs.com/docs/api.html#model_Model.create) instead. - * - * ####Example: - * - * Character.bulkWrite([ - * { - * insertOne: { - * document: { - * name: 'Eddard Stark', - * title: 'Warden of the North' - * } - * } - * }, - * { - * updateOne: { - * filter: { name: 'Eddard Stark' }, - * // If you were using the MongoDB driver directly, you'd need to do - * // `update: { $set: { title: ... } }` but mongoose adds $set for - * // you. - * update: { title: 'Hand of the King' } - * } - * }, - * { - * deleteOne: { - * { - * filter: { name: 'Eddard Stark' } - * } - * } - * } - * ]).then(res => { - * // Prints "1 1 1" - * console.log(res.insertedCount, res.modifiedCount, res.deletedCount); - * }); - * - * @param {Array} ops - * @param {Object} [options] - * @param {Function} [callback] callback `function(error, bulkWriteOpResult) {}` - * @return {Promise} resolves to a [`BulkWriteOpResult`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult) if the operation succeeds - * @api public - */ - -Model.bulkWrite = function(ops, options, callback) { - if (typeof options === 'function') { - callback = options; - options = null; - } - if (callback) { - callback = this.$wrapCallback(callback); - } - options = options || {}; - - const validations = ops.map(op => castBulkWrite(this, op)); - - return utils.promiseOrCallback(callback, cb => { - parallel(validations, error => { - if (error) { - return cb(error); - } - - this.collection.bulkWrite(ops, options, (error, res) => { - if (error) { - return cb(error); - } - - cb(null, res); - }); - }); - }, this.events); -}; - -/** - * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. - * The document returned has no paths marked as modified initially. - * - * ####Example: - * - * // hydrate previous data into a Mongoose document - * var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' }); - * - * @param {Object} obj - * @return {Model} document instance - * @api public - */ - -Model.hydrate = function(obj) { - const model = require('./queryhelpers').createModel(this, obj); - model.init(obj); - return model; -}; - -/** - * Updates one document in the database without returning it. - * - * This function triggers the following middleware. - * - * - `update()` - * - * ####Examples: - * - * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); - * MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, raw) { - * if (err) return handleError(err); - * console.log('The raw response from Mongo was ', raw); - * }); - * - * ####Valid options: - * - * - `safe` (boolean) safe mode (defaults to value set in schema (true)) - * - `upsert` (boolean) whether to create the doc if it doesn't match (false) - * - `multi` (boolean) whether multiple documents should be updated (false) - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `strict` (boolean) overrides the `strict` option for this update - * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false) - * - * All `update` values are cast to their appropriate SchemaTypes before being sent. - * - * The `callback` function receives `(err, rawResponse)`. - * - * - `err` is the error if any occurred - * - `rawResponse` is the full response from Mongo - * - * ####Note: - * - * All top level keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * var query = { name: 'borne' }; - * Model.update(query, { name: 'jason bourne' }, options, callback) - * - * // is sent as - * Model.update(query, { $set: { name: 'jason bourne' }}, options, callback) - * // if overwrite option is false. If overwrite is true, sent without the $set wrapper. - * - * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason bourne' }`. - * - * ####Note: - * - * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. - * - * ####Note: - * - * Although values are casted to their appropriate types when using update, the following are *not* applied: - * - * - defaults - * - setters - * - validators - * - middleware - * - * If you need those features, use the traditional approach of first retrieving the document. - * - * Model.findOne({ name: 'borne' }, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }) - * - * @see strict http://mongoosejs.com/docs/guide.html#strict - * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output - * @param {Object} conditions - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.update = function update(conditions, doc, options, callback) { - return _update(this, 'update', conditions, doc, options, callback); -}; - -/** - * Same as `update()`, except MongoDB will update _all_ documents that match - * `criteria` (as opposed to just the first one) regardless of the value of - * the `multi` option. - * - * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` - * and `post('updateMany')` instead. - * - * This function triggers the following middleware. - * - * - `updateMany()` - * - * @param {Object} conditions - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.updateMany = function updateMany(conditions, doc, options, callback) { - return _update(this, 'updateMany', conditions, doc, options, callback); -}; - -/** - * Same as `update()`, except it does not support the `multi` or `overwrite` - * options. - * - * - MongoDB will update _only_ the first document that matches `criteria` regardless of the value of the `multi` option. - * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`. - * - * This function triggers the following middleware. - * - * - `updateOne()` - * - * @param {Object} conditions - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.updateOne = function updateOne(conditions, doc, options, callback) { - return _update(this, 'updateOne', conditions, doc, options, callback); -}; - -/** - * Same as `update()`, except MongoDB replace the existing document with the - * given document (no atomic operators like `$set`). - * - * This function triggers the following middleware. - * - * - `replaceOne()` - * - * @param {Object} conditions - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.replaceOne = function replaceOne(conditions, doc, options, callback) { - const versionKey = get(this, 'schema.options.versionKey', null); - if (versionKey && !doc[versionKey]) { - doc[versionKey] = 0; - } - - return _update(this, 'replaceOne', conditions, doc, options, callback); -}; - -/*! - * Common code for `updateOne()`, `updateMany()`, `replaceOne()`, and `update()` - * because they need to do the same thing - */ - -function _update(model, op, conditions, doc, options, callback) { - const mq = new model.Query({}, {}, model, model.collection); - if (callback) { - callback = model.$wrapCallback(callback); - } - // gh-2406 - // make local deep copy of conditions - if (conditions instanceof Document) { - conditions = conditions.toObject(); - } else { - conditions = utils.clone(conditions); - } - options = typeof options === 'function' ? options : utils.clone(options); - - const versionKey = get(model, 'schema.options.versionKey', null); - _decorateUpdateWithVersionKey(doc, options, versionKey); - - return mq[op](conditions, doc, options, callback); -} - -/** - * Executes a mapReduce command. - * - * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options. - * - * This function does not trigger any middleware. - * - * ####Example: - * - * var o = {}; - * // `map()` and `reduce()` are run on the MongoDB server, not Node.js, - * // these functions are converted to strings - * o.map = function () { emit(this.name, 1) }; - * o.reduce = function (k, vals) { return vals.length }; - * User.mapReduce(o, function (err, results) { - * console.log(results) - * }) - * - * ####Other options: - * - * - `query` {Object} query filter object. - * - `sort` {Object} sort input objects using this key - * - `limit` {Number} max number of documents - * - `keeptemp` {Boolean, default:false} keep temporary data - * - `finalize` {Function} finalize function - * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution - * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X - * - `verbose` {Boolean, default:false} provide statistics on job execution time. - * - `readPreference` {String} - * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. - * - * ####* out options: - * - * - `{inline:1}` the results are returned in an array - * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection - * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions - * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old - * - * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the `lean` option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). - * - * ####Example: - * - * var o = {}; - * // You can also define `map()` and `reduce()` as strings if your - * // linter complains about `emit()` not being defined - * o.map = 'function () { emit(this.name, 1) }'; - * o.reduce = 'function (k, vals) { return vals.length }'; - * o.out = { replace: 'createdCollectionNameForResults' } - * o.verbose = true; - * - * User.mapReduce(o, function (err, model, stats) { - * console.log('map reduce took %d ms', stats.processtime) - * model.find().where('value').gt(10).exec(function (err, docs) { - * console.log(docs); - * }); - * }) - * - * // `mapReduce()` returns a promise. However, ES6 promises can only - * // resolve to exactly one value, - * o.resolveToObject = true; - * var promise = User.mapReduce(o); - * promise.then(function (res) { - * var model = res.model; - * var stats = res.stats; - * console.log('map reduce took %d ms', stats.processtime) - * return model.find().where('value').gt(10).exec(); - * }).then(function (docs) { - * console.log(docs); - * }).then(null, handleError).end() - * - * @param {Object} o an object specifying map-reduce options - * @param {Function} [callback] optional callback - * @see http://www.mongodb.org/display/DOCS/MapReduce - * @return {Promise} - * @api public - */ - -Model.mapReduce = function mapReduce(o, callback) { - if (callback) { - callback = this.$wrapCallback(callback); - } - return utils.promiseOrCallback(callback, cb => { - if (!Model.mapReduce.schema) { - const opts = {noId: true, noVirtualId: true, strict: false}; - Model.mapReduce.schema = new Schema({}, opts); - } - - if (!o.out) o.out = {inline: 1}; - if (o.verbose !== false) o.verbose = true; - - o.map = String(o.map); - o.reduce = String(o.reduce); - - if (o.query) { - let q = new this.Query(o.query); - q.cast(this); - o.query = q._conditions; - q = undefined; - } - - this.collection.mapReduce(null, null, o, (err, res) => { - if (err) { - return cb(err); - } - if (res.collection) { - // returned a collection, convert to Model - const model = Model.compile('_mapreduce_' + res.collection.collectionName, - Model.mapReduce.schema, res.collection.collectionName, this.db, - this.base); - - model._mapreduce = true; - res.model = model; - - return cb(null, res); - } - - cb(null, res); - }); - }, this.events); -}; - -/** - * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. - * - * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. - * - * This function triggers the following middleware. - * - * - `aggregate()` - * - * ####Example: - * - * // Find the max balance of all accounts - * Users.aggregate([ - * { $group: { _id: null, maxBalance: { $max: '$balance' }}}, - * { $project: { _id: 0, maxBalance: 1 }} - * ]). - * then(function (res) { - * console.log(res); // [ { maxBalance: 98000 } ] - * }); - * - * // Or use the aggregation pipeline builder. - * Users.aggregate(). - * group({ _id: null, maxBalance: { $max: '$balance' } }). - * project('-id maxBalance'). - * exec(function (err, res) { - * if (err) return handleError(err); - * console.log(res); // [ { maxBalance: 98 } ] - * }); - * - * ####NOTE: - * - * - Arguments are not cast to the model's schema because `$project` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. - * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). - * - Requires MongoDB >= 2.1 - * - * @see Aggregate #aggregate_Aggregate - * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ - * @param {Array} [pipeline] aggregation pipeline as an array of objects - * @param {Function} [callback] - * @return {Aggregate} - * @api public - */ - -Model.aggregate = function aggregate(pipeline, callback) { - if (arguments.length > 2 || get(pipeline, 'constructor.name') === 'Object') { - throw new Error('Mongoose 5.x disallows passing a spread of operators ' + - 'to `Model.aggregate()`. Instead of ' + - '`Model.aggregate({ $match }, { $skip })`, do ' + - '`Model.aggregate([{ $match }, { $skip }])`'); - } - - if (typeof pipeline === 'function') { - callback = pipeline; - pipeline = []; - } - - const aggregate = new Aggregate(pipeline || []); - aggregate.model(this); - - if (typeof callback === 'undefined') { - return aggregate; - } - - if (callback) { - callback = this.$wrapCallback(callback); - } - - aggregate.exec(callback); - return aggregate; -}; - -/** - * Implements `$geoSearch` functionality for Mongoose - * - * This function does not trigger any middleware - * - * ####Example: - * - * var options = { near: [10, 10], maxDistance: 5 }; - * Locations.geoSearch({ type : "house" }, options, function(err, res) { - * console.log(res); - * }); - * - * ####Options: - * - `near` {Array} x,y point to search for - * - `maxDistance` {Number} the maximum distance from the point near that a result can be - * - `limit` {Number} The maximum number of results to return - * - `lean` {Boolean} return the raw object instead of the Mongoose Model - * - * @param {Object} conditions an object that specifies the match condition (required) - * @param {Object} options for the geoSearch, some (near, maxDistance) are required - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean). - * @param {Function} [callback] optional callback - * @return {Promise} - * @see http://docs.mongodb.org/manual/reference/command/geoSearch/ - * @see http://docs.mongodb.org/manual/core/geohaystack/ - * @api public - */ - -Model.geoSearch = function(conditions, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - if (callback) { - callback = this.$wrapCallback(callback); - } - - return utils.promiseOrCallback(callback, cb => { - let error; - if (conditions === undefined || !utils.isObject(conditions)) { - error = new Error('Must pass conditions to geoSearch'); - } else if (!options.near) { - error = new Error('Must specify the near option in geoSearch'); - } else if (!Array.isArray(options.near)) { - error = new Error('near option must be an array [x, y]'); - } - - if (error) { - return cb(error); - } - - // send the conditions in the options object - options.search = conditions; - - this.collection.geoHaystackSearch(options.near[0], options.near[1], options, (err, res) => { - if (err) { - return cb(err); - } - - let count = res.results.length; - if (options.lean || count === 0) { - return cb(null, res.results); - } - - const errSeen = false; - - function init(err) { - if (err && !errSeen) { - return cb(err); - } - - if (!--count && !errSeen) { - cb(null, res.results); - } - } - - for (let i = 0; i < res.results.length; ++i) { - const temp = res.results[i]; - res.results[i] = new this(); - res.results[i].init(temp, {}, init); - } - }); - }, this.events); -}; - -/** - * Populates document references. - * - * ####Available top-level options: - * - * - path: space delimited path(s) to populate - * - select: optional fields to select - * - match: optional query conditions to match - * - model: optional name of the model to use for population - * - options: optional query options like sort, limit, etc - * - justOne: optional boolean, if true Mongoose will always set `path` to an array. Inferred from schema by default. - * - * ####Examples: - * - * // populates a single object - * User.findById(id, function (err, user) { - * var opts = [ - * { path: 'company', match: { x: 1 }, select: 'name' } - * , { path: 'notes', options: { limit: 10 }, model: 'override' } - * ] - * - * User.populate(user, opts, function (err, user) { - * console.log(user); - * }); - * }); - * - * // populates an array of objects - * User.find(match, function (err, users) { - * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }] - * - * var promise = User.populate(users, opts); - * promise.then(console.log).end(); - * }) - * - * // imagine a Weapon model exists with two saved documents: - * // { _id: 389, name: 'whip' } - * // { _id: 8921, name: 'boomerang' } - * // and this schema: - * // new Schema({ - * // name: String, - * // weapon: { type: ObjectId, ref: 'Weapon' } - * // }); - * - * var user = { name: 'Indiana Jones', weapon: 389 } - * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) { - * console.log(user.weapon.name) // whip - * }) - * - * // populate many plain objects - * var users = [{ name: 'Indiana Jones', weapon: 389 }] - * users.push({ name: 'Batman', weapon: 8921 }) - * Weapon.populate(users, { path: 'weapon' }, function (err, users) { - * users.forEach(function (user) { - * console.log('%s uses a %s', users.name, user.weapon.name) - * // Indiana Jones uses a whip - * // Batman uses a boomerang - * }); - * }); - * // Note that we didn't need to specify the Weapon model because - * // it is in the schema's ref - * - * @param {Document|Array} docs Either a single document or array of documents to populate. - * @param {Object} options A hash of key/val (path, options) used for population. - * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. - * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). - * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. - * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. - * @return {Promise} - * @api public - */ - -Model.populate = function(docs, paths, callback) { - const _this = this; - if (callback) { - callback = this.$wrapCallback(callback); - } - - // normalized paths - paths = utils.populate(paths); - - // data that should persist across subPopulate calls - const cache = {}; - - return utils.promiseOrCallback(callback, cb => { - _populate(_this, docs, paths, cache, cb); - }, this.events); -}; - -/*! - * Populate helper - * - * @param {Model} model the model to use - * @param {Document|Array} docs Either a single document or array of documents to populate. - * @param {Object} paths - * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. - * @return {Function} - * @api private - */ - -function _populate(model, docs, paths, cache, callback) { - let pending = paths.length; - - if (pending === 0) { - return callback(null, docs); - } - - // each path has its own query options and must be executed separately - let i = pending; - let path; - while (i--) { - path = paths[i]; - populate(model, docs, path, next); - } - - function next(err) { - if (err) { - return callback(err, null); - } - if (--pending) { - return; - } - callback(null, docs); - } -} - -/*! - * Populates `docs` - */ -const excludeIdReg = /\s?-_id\s?/; -const excludeIdRegGlobal = /\s?-_id\s?/g; - -function populate(model, docs, options, callback) { - // normalize single / multiple docs passed - if (!Array.isArray(docs)) { - docs = [docs]; - } - - if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) { - return callback(); - } - - const modelsMap = getModelsMapForPopulate(model, docs, options); - - if (modelsMap instanceof Error) { - return immediate(function() { - callback(modelsMap); - }); - } - - const len = modelsMap.length; - let mod; - let match; - let select; - let vals = []; - - function flatten(item) { - // no need to include undefined values in our query - return undefined !== item; - } - - let _remaining = len; - let hasOne = false; - for (let i = 0; i < len; ++i) { - mod = modelsMap[i]; - select = mod.options.select; - - if (mod.options.match) { - match = utils.object.shallowCopy(mod.options.match); - } else if (get(mod, 'options.options.match')) { - match = utils.object.shallowCopy(mod.options.options.match); - delete mod.options.options.match; - } else { - match = {}; - } - - let ids = utils.array.flatten(mod.ids, flatten); - ids = utils.array.unique(ids); - - if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) { - --_remaining; - continue; - } - - hasOne = true; - if (mod.foreignField.size === 1) { - const foreignField = Array.from(mod.foreignField)[0]; - if (foreignField !== '_id' || !match['_id']) { - match[foreignField] = { $in: ids }; - } - } else { - match.$or = []; - for (const foreignField of mod.foreignField) { - if (foreignField !== '_id' || !match['_id']) { - match.$or.push({ [foreignField]: { $in: ids } }); - } - } - } - - const assignmentOpts = {}; - assignmentOpts.sort = get(mod, 'options.options.sort', void 0); - assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0); - - if (assignmentOpts.excludeId) { - // override the exclusion from the query so we can use the _id - // for document matching during assignment. we'll delete the - // _id back off before returning the result. - if (typeof select === 'string') { - select = select.replace(excludeIdRegGlobal, ' '); - } else { - // preserve original select conditions by copying - select = utils.object.shallowCopy(select); - delete select._id; - } - } - - // If just setting count, skip everything else - if (mod.count) { - mod.model.countDocuments(match, function(err, count) { - if (err != null) { - return callback(err); - } - - for (const doc of docs) { - try { - if (doc.$__ != null) { - doc.set(mod.options.path, count); - } else { - utils.setValue(mod.options.path, count, doc); - } - } catch (err) { - return callback(err); - } - } - - callback(null); - }); - continue; - } - - if (mod.options.options && mod.options.options.limit) { - assignmentOpts.originalLimit = mod.options.options.limit; - mod.options.options.limit = mod.options.options.limit * ids.length; - } - - const subPopulate = utils.clone(mod.options.populate); - - const query = mod.model.find(match, select, mod.options.options); - - // If we're doing virtual populate and projection is inclusive and foreign - // field is not selected, automatically select it because mongoose needs it. - // If projection is exclusive and client explicitly unselected the foreign - // field, that's the client's fault. - for (const foreignField of mod.foreignField) { - if (foreignField !== '_id' && query.selectedInclusively() && - !isPathSelectedInclusive(query._fields, foreignField)) { - query.select(foreignField); - } - } - - // If we need to sub-populate, call populate recursively - if (subPopulate) { - query.populate(subPopulate); - } - - query.exec(next.bind(this, mod, assignmentOpts)); - } - - if (!hasOne) { - return callback(); - } - - function next(options, assignmentOpts, err, valsFromDb) { - if (mod.options.options && mod.options.options.limit) { - mod.options.options.limit = assignmentOpts.originalLimit; - } - - if (err) return callback(err, null); - vals = vals.concat(valsFromDb); - _assign(null, vals, options, assignmentOpts); - if (--_remaining === 0) { - callback(); - } - } - - function _assign(err, vals, mod, assignmentOpts) { - if (err) { - return callback(err, null); - } - - const options = mod.options; - const isVirtual = mod.isVirtual; - const justOne = mod.justOne; - let _val; - const lean = options.options && options.options.lean; - const len = vals.length; - const rawOrder = {}; - const rawDocs = {}; - let key; - let val; - - // Clone because `assignRawDocsToIdStructure` will mutate the array - const allIds = utils.clone(mod.allIds); - - // optimization: - // record the document positions as returned by - // the query result. - for (let i = 0; i < len; i++) { - val = vals[i]; - if (val == null) { - continue; - } - for (const foreignField of mod.foreignField) { - _val = utils.getValue(foreignField, val); - if (Array.isArray(_val)) { - _val = utils.array.flatten(_val); - const _valLength = _val.length; - for (let j = 0; j < _valLength; ++j) { - let __val = _val[j]; - if (__val instanceof Document) { - __val = __val._id; - } - key = String(__val); - if (rawDocs[key]) { - if (Array.isArray(rawDocs[key])) { - rawDocs[key].push(val); - rawOrder[key].push(i); - } else { - rawDocs[key] = [rawDocs[key], val]; - rawOrder[key] = [rawOrder[key], i]; - } - } else { - if (isVirtual && !justOne) { - rawDocs[key] = [val]; - rawOrder[key] = [i]; - } else { - rawDocs[key] = val; - rawOrder[key] = i; - } - } - } - } else { - if (_val instanceof Document) { - _val = _val._id; - } - key = String(_val); - if (rawDocs[key]) { - if (Array.isArray(rawDocs[key])) { - rawDocs[key].push(val); - rawOrder[key].push(i); - } else { - rawDocs[key] = [rawDocs[key], val]; - rawOrder[key] = [rawOrder[key], i]; - } - } else { - rawDocs[key] = val; - rawOrder[key] = i; - } - } - // flag each as result of population - if (lean) { - leanPopulateMap.set(val, mod.model); - } else { - val.$__.wasPopulated = true; - } - } - } - - assignVals({ - originalModel: model, - // If virtual, make sure to not mutate original field - rawIds: mod.isVirtual ? allIds : mod.allIds, - allIds: allIds, - foreignField: mod.foreignField, - rawDocs: rawDocs, - rawOrder: rawOrder, - docs: mod.docs, - path: options.path, - options: assignmentOpts, - justOne: mod.justOne, - isVirtual: mod.isVirtual, - allOptions: mod, - lean: lean, - virtual: mod.virtual - }); - } -} - -/*! - * Assigns documents returned from a population query back - * to the original document path. - */ - -function assignVals(o) { - // Options that aren't explicitly listed in `populateOptions` - const userOptions = get(o, 'allOptions.options.options'); - // `o.options` contains options explicitly listed in `populateOptions`, like - // `match` and `limit`. - const populateOptions = Object.assign({}, o.options, userOptions, { - justOne: o.justOne - }); - - const originalIds = [].concat(o.rawIds); - - // replace the original ids in our intermediate _ids structure - // with the documents found by query - assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, populateOptions); - - // now update the original documents being populated using the - // result structure that contains real documents. - const docs = o.docs; - const rawIds = o.rawIds; - const options = o.options; - - function setValue(val) { - return valueFilter(val, options, populateOptions); - } - - for (let i = 0; i < docs.length; ++i) { - const existingVal = utils.getValue(o.path, docs[i]); - if (existingVal == null && !getVirtual(o.originalModel.schema, o.path)) { - continue; - } - - // If we're populating a map, the existing value will be an object, so - // we need to transform again - const originalSchema = o.originalModel.schema; - let isMap = isModel(docs[i]) ? - existingVal instanceof Map : - utils.isPOJO(existingVal); - // If we pass the first check, also make sure the local field's schematype - // is map (re: gh-6460) - isMap = isMap && get(originalSchema._getSchema(o.path), '$isSchemaMap'); - if (!o.isVirtual && isMap) { - const _keys = existingVal instanceof Map ? - Array.from(existingVal.keys()) : - Object.keys(existingVal); - rawIds[i] = rawIds[i].reduce((cur, v, i) => { - // Avoid casting because that causes infinite recursion - cur.$init(_keys[i], v); - return cur; - }, new MongooseMap({}, docs[i])); - } - - if (o.isVirtual && docs[i] instanceof Model) { - docs[i].populated(o.path, o.justOne ? originalIds[0] : originalIds, o.allOptions); - // If virtual populate and doc is already init-ed, need to walk through - // the actual doc to set rather than setting `_doc` directly - mpath.set(o.path, rawIds[i], docs[i], setValue); - continue; - } - - const parts = o.path.split('.'); - let cur = docs[i]; - for (let j = 0; j < parts.length - 1; ++j) { - if (cur[parts[j]] == null) { - cur[parts[j]] = {}; - } - cur = cur[parts[j]]; - } - if (docs[i].$__) { - docs[i].populated(o.path, o.allIds[i], o.allOptions); - } - - // If lean, need to check that each individual virtual respects - // `justOne`, because you may have a populated virtual with `justOne` - // underneath an array. See gh-6867 - utils.setValue(o.path, rawIds[i], docs[i], function(v) { - if (o.justOne === true && Array.isArray(v)) { - return setValue(v[0]); - } else if (o.justOne === false && !Array.isArray(v)) { - return setValue([v]); - } - return setValue(v); - }, false); - } -} - -/*! - * Check if obj is a document - */ - -function isModel(obj) { - return get(obj, '$__') != null; -} - -function getModelsMapForPopulate(model, docs, options) { - let i; - let doc; - const len = docs.length; - const available = {}; - const map = []; - const modelNameFromQuery = options.model && options.model.modelName || options.model; - let schema; - let refPath; - let Model; - let currentOptions; - let modelNames; - let modelName; - let discriminatorKey; - let modelForFindSchema; - - const originalModel = options.model; - let isVirtual = false; - const modelSchema = model.schema; - - for (i = 0; i < len; i++) { - doc = docs[i]; - - schema = getSchemaTypes(modelSchema, doc, options.path); - const isUnderneathDocArray = schema && schema.$isUnderneathDocArray; - if (isUnderneathDocArray && get(options, 'options.sort') != null) { - return new Error('Cannot populate with `sort` on path ' + options.path + - ' because it is a subproperty of a document array'); - } - - modelNames = null; - let isRefPath = false; - if (Array.isArray(schema)) { - for (let j = 0; j < schema.length; ++j) { - let _modelNames; - try { - const res = _getModelNames(doc, schema[j]); - _modelNames = res.modelNames; - isRefPath = res.isRefPath; - } catch (error) { - return error; - } - if (!_modelNames) { - continue; - } - modelNames = modelNames || []; - for (let x = 0; x < _modelNames.length; ++x) { - if (modelNames.indexOf(_modelNames[x]) === -1) { - modelNames.push(_modelNames[x]); - } - } - } - } else { - try { - const res = _getModelNames(doc, schema); - modelNames = res.modelNames; - isRefPath = res.isRefPath; - } catch (error) { - return error; - } - - if (!modelNames) { - continue; - } - } - - const virtual = getVirtual(model.schema, options.path); - let localField; - let count = false; - if (virtual && virtual.options) { - const virtualPrefix = virtual.$nestedSchemaPath ? - virtual.$nestedSchemaPath + '.' : ''; - if (typeof virtual.options.localField === 'function') { - localField = virtualPrefix + virtual.options.localField.call(doc, doc); - } else { - localField = virtualPrefix + virtual.options.localField; - } - count = virtual.options.count; - } else { - localField = options.path; - } - let foreignField = virtual && virtual.options ? - virtual.options.foreignField : - '_id'; - - // `justOne = null` means we don't know from the schema whether the end - // result should be an array or a single doc. This can result from - // populating a POJO using `Model.populate()` - let justOne = null; - if ('justOne' in options) { - justOne = options.justOne; - } else if (virtual && virtual.options && virtual.options.ref) { - let normalizedRef; - if (typeof virtual.options.ref === 'function') { - normalizedRef = virtual.options.ref.call(doc, doc); - } else { - normalizedRef = virtual.options.ref; - } - justOne = !!virtual.options.justOne; - isVirtual = true; - if (!modelNames) { - modelNames = [].concat(normalizedRef); - } - } else if (schema && !schema[schemaMixedSymbol]) { - // Skip Mixed types because we explicitly don't do casting on those. - justOne = !schema.$isMongooseArray; - } - - if (!modelNames) { - continue; - } - - if (virtual && (!localField || !foreignField)) { - return new Error('If you are populating a virtual, you must set the ' + - 'localField and foreignField options'); - } - - options.isVirtual = isVirtual; - options.virtual = virtual; - if (typeof localField === 'function') { - localField = localField.call(doc, doc); - } - if (typeof foreignField === 'function') { - foreignField = foreignField.call(doc); - } - - const localFieldPath = modelSchema.paths[localField]; - const localFieldGetters = localFieldPath ? localFieldPath.getters : []; - let ret; - - const _populateOptions = get(options, 'options', {}); - - const getters = 'getters' in _populateOptions ? - _populateOptions.getters : - options.isVirtual && get(virtual, 'options.getters', false); - if (localFieldGetters.length > 0 && getters) { - const hydratedDoc = (doc.$__ != null) ? doc : model.hydrate(doc); - ret = localFieldPath.applyGetters(doc[localField], hydratedDoc); - } else { - ret = convertTo_id(utils.getValue(localField, doc)); - } - - const id = String(utils.getValue(foreignField, doc)); - options._docs[id] = Array.isArray(ret) ? ret.slice() : ret; - - let k = modelNames.length; - while (k--) { - modelName = modelNames[k]; - if (modelName == null) { - continue; - } - - try { - Model = originalModel && originalModel[modelSymbol] ? - originalModel : - modelName[modelSymbol] ? modelName : model.db.model(modelName); - } catch (error) { - return error; - } - - let ids = ret; - const flat = Array.isArray(ret) ? utils.array.flatten(ret) : []; - if (isRefPath && Array.isArray(ret) && flat.length === modelNames.length) { - ids = flat.filter((val, i) => modelNames[i] === modelName); - } - - if (!available[modelName]) { - currentOptions = { - model: Model - }; - - if (isVirtual && virtual.options && virtual.options.options) { - currentOptions.options = utils.clone(virtual.options.options); - } - utils.merge(currentOptions, options); - if (schema && !discriminatorKey) { - currentOptions.model = Model; - } - options.model = Model; - - available[modelName] = { - model: Model, - options: currentOptions, - docs: [doc], - ids: [ids], - allIds: [ret], - localField: new Set([localField]), - foreignField: new Set([foreignField]), - justOne: justOne, - isVirtual: isVirtual, - virtual: virtual, - count: count - }; - map.push(available[modelName]); - } else { - available[modelName].localField.add(localField); - available[modelName].foreignField.add(foreignField); - available[modelName].docs.push(doc); - available[modelName].ids.push(ids); - available[modelName].allIds.push(ret); - } - } - } - - function _getModelNames(doc, schema) { - let modelNames; - let discriminatorKey; - let isRefPath = false; - - if (schema && schema.caster) { - schema = schema.caster; - } - if (schema && schema.$isSchemaMap) { - schema = schema.$__schemaType; - } - - if (!schema && model.discriminators) { - discriminatorKey = model.schema.discriminatorMapping.key; - } - - refPath = schema && schema.options && schema.options.refPath; - - const normalizedRefPath = normalizeRefPath(refPath, doc, options.path); - - if (modelNameFromQuery) { - modelNames = [modelNameFromQuery]; // query options - } else if (normalizedRefPath) { - if (options._queryProjection != null && isPathExcluded(options._queryProjection, normalizedRefPath)) { - throw new Error('refPath `' + normalizedRefPath + - '` must not be excluded in projection, got ' + - util.inspect(options._queryProjection)); - } - modelNames = utils.getValue(normalizedRefPath, doc); - if (Array.isArray(modelNames)) { - modelNames = utils.array.flatten(modelNames); - } - - isRefPath = true; - } else { - let modelForCurrentDoc = model; - let schemaForCurrentDoc; - - if (!schema && discriminatorKey) { - modelForFindSchema = utils.getValue(discriminatorKey, doc); - - if (modelForFindSchema) { - try { - modelForCurrentDoc = model.db.model(modelForFindSchema); - } catch (error) { - return error; - } - - schemaForCurrentDoc = modelForCurrentDoc.schema._getSchema(options.path); - - if (schemaForCurrentDoc && schemaForCurrentDoc.caster) { - schemaForCurrentDoc = schemaForCurrentDoc.caster; - } - } - } else { - schemaForCurrentDoc = schema; - } - const virtual = getVirtual(modelForCurrentDoc.schema, options.path); - - let ref; - if ((ref = get(schemaForCurrentDoc, 'options.ref')) != null) { - modelNames = [ref]; - } else if ((ref = get(virtual, 'options.ref')) != null) { - if (typeof ref === 'function') { - ref = ref.call(doc, doc); - } - - // When referencing nested arrays, the ref should be an Array - // of modelNames. - if (Array.isArray(ref)) { - modelNames = ref; - } else { - modelNames = [ref]; - } - - isVirtual = true; - } else { - // We may have a discriminator, in which case we don't want to - // populate using the base model by default - modelNames = discriminatorKey ? null : [model.modelName]; - } - } - - if (!modelNames) { - return { modelNames: modelNames, isRefPath: isRefPath }; - } - - if (!Array.isArray(modelNames)) { - modelNames = [modelNames]; - } - - return { modelNames: modelNames, isRefPath: isRefPath }; - } - - return map; -} - -/*! - * Retrieve the _id of `val` if a Document or Array of Documents. - * - * @param {Array|Document|Any} val - * @return {Array|Document|Any} - */ - -function convertTo_id(val) { - if (val instanceof Model) return val._id; - - if (Array.isArray(val)) { - for (let i = 0; i < val.length; ++i) { - if (val[i] instanceof Model) { - val[i] = val[i]._id; - } - } - if (val.isMongooseArray && val._schema) { - return val._schema.cast(val, val._parent); - } - - return [].concat(val); - } - - // `populate('map')` may be an object if populating on a doc that hasn't - // been hydrated yet - if (val != null && val.constructor.name === 'Object') { - const ret = []; - for (const key of Object.keys(val)) { - ret.push(val[key]); - } - return ret; - } - // If doc has already been hydrated, e.g. `doc.populate('map').execPopulate()` - // then `val` will already be a map - if (val instanceof Map) { - return Array.from(val.values()); - } - - return val; -} - -/*! - * 1) Apply backwards compatible find/findOne behavior to sub documents - * - * find logic: - * a) filter out non-documents - * b) remove _id from sub docs when user specified - * - * findOne - * a) if no doc found, set to null - * b) remove _id from sub docs when user specified - * - * 2) Remove _ids when specified by users query. - * - * background: - * _ids are left in the query even when user excludes them so - * that population mapping can occur. - */ - -function valueFilter(val, assignmentOpts, populateOptions) { - if (Array.isArray(val)) { - // find logic - const ret = []; - const numValues = val.length; - for (let i = 0; i < numValues; ++i) { - const subdoc = val[i]; - if (!isPopulatedObject(subdoc) && (!populateOptions.retainNullValues || subdoc != null)) { - continue; - } - maybeRemoveId(subdoc, assignmentOpts); - ret.push(subdoc); - if (assignmentOpts.originalLimit && - ret.length >= assignmentOpts.originalLimit) { - break; - } - } - - // Since we don't want to have to create a new mongoosearray, make sure to - // modify the array in place - while (val.length > ret.length) { - Array.prototype.pop.apply(val, []); - } - for (let i = 0; i < ret.length; ++i) { - val[i] = ret[i]; - } - return val; - } - - // findOne - if (isPopulatedObject(val)) { - maybeRemoveId(val, assignmentOpts); - return val; - } - - if (populateOptions.justOne === true) { - return (val == null ? val : null); - } - if (populateOptions.justOne === false) { - return []; - } - return val; -} - -/*! - * Remove _id from `subdoc` if user specified "lean" query option - */ - -function maybeRemoveId(subdoc, assignmentOpts) { - if (assignmentOpts.excludeId) { - if (typeof subdoc.setValue === 'function') { - delete subdoc._doc._id; - } else { - delete subdoc._id; - } - } -} - -/*! - * Determine if `obj` is something we can set a populated path to. Can be a - * document, a lean document, or an array/map that contains docs. - */ - -function isPopulatedObject(obj) { - if (obj == null) { - return false; - } - - return Array.isArray(obj) || - obj.$isMongooseMap || - obj.$__ != null || - leanPopulateMap.has(obj); -} - -/*! - * Compiler utility. - * - * @param {String|Function} name model name or class extending Model - * @param {Schema} schema - * @param {String} collectionName - * @param {Connection} connection - * @param {Mongoose} base mongoose instance - */ - -Model.compile = function compile(name, schema, collectionName, connection, base) { - const versioningEnabled = schema.options.versionKey !== false; - - setParentPointers(schema); - - if (versioningEnabled && !schema.paths[schema.options.versionKey]) { - // add versioning to top level documents only - const o = {}; - o[schema.options.versionKey] = Number; - schema.add(o); - } - - let model; - if (typeof name === 'function' && name.prototype instanceof Model) { - model = name; - name = model.name; - schema.loadClass(model, false); - model.prototype.$isMongooseModelPrototype = true; - } else { - // generate new class - model = function model(doc, fields, skipId) { - model.hooks.execPreSync('createModel', doc); - if (!(this instanceof model)) { - return new model(doc, fields, skipId); - } - Model.call(this, doc, fields, skipId); - }; - } - - model.hooks = schema.s.hooks.clone(); - model.base = base; - model.modelName = name; - - if (!(model.prototype instanceof Model)) { - model.__proto__ = Model; - model.prototype.__proto__ = Model.prototype; - } - model.model = Model.prototype.model; - model.db = model.prototype.db = connection; - model.discriminators = model.prototype.discriminators = undefined; - model[modelSymbol] = true; - model.events = new EventEmitter(); - - model.prototype.$__setSchema(schema); - - const _userProvidedOptions = schema._userProvidedOptions || {}; - - // `bufferCommands` is true by default... - let bufferCommands = true; - // First, take the global option - if (connection.base.get('bufferCommands') != null) { - bufferCommands = connection.base.get('bufferCommands'); - } - // Connection-specific overrides the global option - if (connection.config.bufferCommands != null) { - bufferCommands = connection.config.bufferCommands; - } - // And schema options override global and connection - if (_userProvidedOptions.bufferCommands != null) { - bufferCommands = _userProvidedOptions.bufferCommands; - } - - const collectionOptions = { - bufferCommands: bufferCommands, - capped: schema.options.capped - }; - - model.prototype.collection = connection.collection( - collectionName, - collectionOptions - ); - model.prototype[modelCollectionSymbol] = model.prototype.collection; - - // apply methods and statics - applyMethods(model, schema); - applyStatics(model, schema); - applyHooks(model, schema); - - model.schema = model.prototype.schema; - model.collection = model.prototype.collection; - - // Create custom query constructor - model.Query = function() { - Query.apply(this, arguments); - }; - model.Query.prototype = Object.create(Query.prototype); - model.Query.base = Query.base; - applyQueryMiddleware(model.Query, model); - applyQueryMethods(model, schema.query); - - const kareemOptions = { - useErrorHandlers: true, - numCallbackParams: 1 - }; - model.$__insertMany = model.hooks.createWrapper('insertMany', - model.$__insertMany, model, kareemOptions); - - return model; -}; - -/*! - * Register custom query methods for this model - * - * @param {Model} model - * @param {Schema} schema - */ - -function applyQueryMethods(model, methods) { - for (const i in methods) { - model.Query.prototype[i] = methods[i]; - } -} - -/*! - * Subclass this model with `conn`, `schema`, and `collection` settings. - * - * @param {Connection} conn - * @param {Schema} [schema] - * @param {String} [collection] - * @return {Model} - */ - -Model.__subclass = function subclass(conn, schema, collection) { - // subclass model using this connection and collection name - const _this = this; - - const Model = function Model(doc, fields, skipId) { - if (!(this instanceof Model)) { - return new Model(doc, fields, skipId); - } - _this.call(this, doc, fields, skipId); - }; - - Model.__proto__ = _this; - Model.prototype.__proto__ = _this.prototype; - Model.db = Model.prototype.db = conn; - - const s = schema && typeof schema !== 'string' - ? schema - : _this.prototype.schema; - - const options = s.options || {}; - const _userProvidedOptions = s._userProvidedOptions || {}; - - if (!collection) { - collection = _this.prototype.schema.get('collection') || - utils.toCollectionName(_this.modelName, this.base.pluralize()); - } - - let bufferCommands = true; - if (s) { - if (conn.config.bufferCommands != null) { - bufferCommands = conn.config.bufferCommands; - } - if (_userProvidedOptions.bufferCommands != null) { - bufferCommands = _userProvidedOptions.bufferCommands; - } - } - const collectionOptions = { - bufferCommands: bufferCommands, - capped: s && options.capped - }; - - Model.prototype.collection = conn.collection(collection, collectionOptions); - Model.prototype[modelCollectionSymbol] = Model.prototype.collection; - Model.collection = Model.prototype.collection; - // Errors handled internally, so ignore - Model.init(() => {}); - return Model; -}; - -Model.$wrapCallback = function(callback) { - if (callback == null) { - return callback; - } - if (typeof callback !== 'function') { - throw new Error('Callback must be a function, got ' + callback); - } - const _this = this; - return function() { - try { - callback.apply(null, arguments); - } catch (error) { - _this.emit('error', error); - } - }; -}; - -/*! - * Module exports. - */ - -module.exports = exports = Model; diff --git a/node_modules/mongoose/lib/options.js b/node_modules/mongoose/lib/options.js deleted file mode 100644 index 8e9fc2941ef439097e98557e550ed4ba33a994f2..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/options.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -exports.internalToObjectOptions = { - transform: false, - virtuals: false, - getters: false, - _skipDepopulateTopLevel: true, - depopulate: true, - flattenDecimals: false -}; diff --git a/node_modules/mongoose/lib/plugins/idGetter.js b/node_modules/mongoose/lib/plugins/idGetter.js deleted file mode 100644 index f4e63561ea557c8a8e300ec56745087011acafce..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/plugins/idGetter.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function(schema) { - // ensure the documents receive an id getter unless disabled - const autoIdGetter = !schema.paths['id'] && - (!schema.options.noVirtualId && schema.options.id); - if (!autoIdGetter) { - return; - } - - schema.virtual('id').get(idGetter); -}; - -/*! - * Returns this documents _id cast to a string. - */ - -function idGetter() { - if (this._id != null) { - return String(this._id); - } - - return null; -} diff --git a/node_modules/mongoose/lib/plugins/removeSubdocs.js b/node_modules/mongoose/lib/plugins/removeSubdocs.js deleted file mode 100644 index c7b2d24769a8c4e19886dfebd3f5f09d2c622cfb..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/plugins/removeSubdocs.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const each = require('async/each'); - -/*! - * ignore - */ - -module.exports = function(schema) { - const unshift = true; - schema.s.hooks.pre('remove', false, function(next) { - if (this.ownerDocument) { - next(); - return; - } - - const _this = this; - const subdocs = this.$__getAllSubdocs(); - - if (!subdocs.length) { - next(); - return; - } - - each(subdocs, function(subdoc, cb) { - subdoc.$__remove(function(err) { - cb(err); - }); - }, function(error) { - if (error) { - return _this.schema.s.hooks.execPost('remove:error', _this, [_this], { error: error }, function(error) { - next(error); - }); - } - next(); - }); - }, null, unshift); -}; diff --git a/node_modules/mongoose/lib/plugins/saveSubdocs.js b/node_modules/mongoose/lib/plugins/saveSubdocs.js deleted file mode 100644 index dc27213683c2b2d7dfd3d5b670821ac5a35c734b..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/plugins/saveSubdocs.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -const each = require('async/each'); - -/*! - * ignore - */ - -module.exports = function(schema) { - const unshift = true; - schema.s.hooks.pre('save', false, function(next) { - if (this.ownerDocument) { - next(); - return; - } - - const _this = this; - const subdocs = this.$__getAllSubdocs(); - - if (!subdocs.length) { - next(); - return; - } - - each(subdocs, function(subdoc, cb) { - subdoc.schema.s.hooks.execPre('save', subdoc, function(err) { - cb(err); - }); - }, function(error) { - if (error) { - return _this.schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { - next(error); - }); - } - next(); - }); - }, null, unshift); - - schema.s.hooks.post('save', function(doc, next) { - if (this.ownerDocument) { - next(); - return; - } - - const _this = this; - const subdocs = this.$__getAllSubdocs(); - - if (!subdocs.length) { - next(); - return; - } - - each(subdocs, function(subdoc, cb) { - subdoc.schema.s.hooks.execPost('save', subdoc, [subdoc], function(err) { - cb(err); - }); - }, function(error) { - if (error) { - return _this.schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { - next(error); - }); - } - next(); - }); - }, null, unshift); -}; diff --git a/node_modules/mongoose/lib/plugins/sharding.js b/node_modules/mongoose/lib/plugins/sharding.js deleted file mode 100644 index b1b0cecbccd0404950880c8138352de1a87bbef5..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/plugins/sharding.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; - -const objectIdSymbol = require('../helpers/symbols').objectIdSymbol; -const utils = require('../utils'); - -/*! - * ignore - */ - -module.exports = function shardingPlugin(schema) { - schema.post('init', function() { - storeShard.call(this); - return this; - }); - schema.pre('save', function(next) { - applyWhere.call(this); - next(); - }); - schema.pre('remove', function(next) { - applyWhere.call(this); - next(); - }); - schema.post('save', function() { - storeShard.call(this); - }); -}; - -/*! - * ignore - */ - -function applyWhere() { - let paths; - let len; - - if (this.$__.shardval) { - paths = Object.keys(this.$__.shardval); - len = paths.length; - - this.$where = this.$where || {}; - for (let i = 0; i < len; ++i) { - this.$where[paths[i]] = this.$__.shardval[paths[i]]; - } - } -} - -/*! - * ignore - */ - -module.exports.storeShard = storeShard; - -/*! - * ignore - */ - -function storeShard() { - // backwards compat - const key = this.schema.options.shardKey || this.schema.options.shardkey; - if (!utils.isPOJO(key)) { - return; - } - - const orig = this.$__.shardval = {}; - const paths = Object.keys(key); - const len = paths.length; - let val; - - for (let i = 0; i < len; ++i) { - val = this.getValue(paths[i]); - if (val == null) { - orig[paths[i]] = val; - } else if (utils.isMongooseObject(val)) { - orig[paths[i]] = val.toObject({depopulate: true, _isNested: true}); - } else if (val instanceof Date || val[objectIdSymbol]) { - orig[paths[i]] = val; - } else if (typeof val.valueOf === 'function') { - orig[paths[i]] = val.valueOf(); - } else { - orig[paths[i]] = val; - } - } -} diff --git a/node_modules/mongoose/lib/plugins/validateBeforeSave.js b/node_modules/mongoose/lib/plugins/validateBeforeSave.js deleted file mode 100644 index 2d8a8acebe414906d5d8c174c7328b0e2dcdcd7b..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/plugins/validateBeforeSave.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function(schema) { - const unshift = true; - schema.pre('save', false, function(next, options) { - const _this = this; - // Nested docs have their own presave - if (this.ownerDocument) { - return next(); - } - - const hasValidateBeforeSaveOption = options && - (typeof options === 'object') && - ('validateBeforeSave' in options); - - let shouldValidate; - if (hasValidateBeforeSaveOption) { - shouldValidate = !!options.validateBeforeSave; - } else { - shouldValidate = this.schema.options.validateBeforeSave; - } - - // Validate - if (shouldValidate) { - this.validate(function(error) { - return _this.schema.s.hooks.execPost('save:error', _this, [ _this], { error: error }, function(error) { - next(error); - }); - }); - } else { - next(); - } - }, null, unshift); -}; diff --git a/node_modules/mongoose/lib/promise_provider.js b/node_modules/mongoose/lib/promise_provider.js deleted file mode 100644 index 3febf3687844de8252bbae6cd0d0913952755fa2..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/promise_provider.js +++ /dev/null @@ -1,49 +0,0 @@ -/*! - * ignore - */ - -'use strict'; - -const assert = require('assert'); -const mquery = require('mquery'); - -/** - * Helper for multiplexing promise implementations - * - * @api private - */ - -const store = { - _promise: null -}; - -/** - * Get the current promise constructor - * - * @api private - */ - -store.get = function() { - return store._promise; -}; - -/** - * Set the current promise constructor - * - * @api private - */ - -store.set = function(lib) { - assert.ok(typeof lib === 'function', - `mongoose.Promise must be a function, got ${lib}`); - store._promise = lib; - mquery.Promise = lib; -}; - -/*! - * Use native promises by default - */ - -store.set(global.Promise); - -module.exports = store; diff --git a/node_modules/mongoose/lib/query.js b/node_modules/mongoose/lib/query.js deleted file mode 100644 index 8942e0a2c332a1790f1953235a36fb0f94b42ffc..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/query.js +++ /dev/null @@ -1,4965 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const CastError = require('./error/cast'); -const DocumentNotFoundError = require('./error/notFound'); -const Kareem = require('kareem'); -const ObjectParameterError = require('./error/objectParameter'); -const QueryCursor = require('./cursor/QueryCursor'); -const ReadPreference = require('./driver').get().ReadPreference; -const applyWriteConcern = require('./helpers/schema/applyWriteConcern'); -const cast = require('./cast'); -const castArrayFilters = require('./helpers/update/castArrayFilters'); -const castUpdate = require('./helpers/query/castUpdate'); -const completeMany = require('./helpers/query/completeMany'); -const get = require('./helpers/get'); -const hasDollarKeys = require('./helpers/query/hasDollarKeys'); -const helpers = require('./queryhelpers'); -const isInclusive = require('./helpers/projection/isInclusive'); -const mquery = require('mquery'); -const selectPopulatedFields = require('./helpers/query/selectPopulatedFields'); -const setDefaultsOnInsert = require('./helpers/setDefaultsOnInsert'); -const slice = require('sliced'); -const updateValidators = require('./helpers/updateValidators'); -const util = require('util'); -const utils = require('./utils'); -const wrapThunk = require('./helpers/query/wrapThunk'); - -/** - * Query constructor used for building queries. You do not need - * to instantiate a `Query` directly. Instead use Model functions like - * [`Model.find()`](/docs/api.html#find_find). - * - * ####Example: - * - * const query = MyModel.find(); // `query` is an instance of `Query` - * query.setOptions({ lean : true }); - * query.collection(MyModel.collection); - * query.where('age').gte(21).exec(callback); - * - * // You can instantiate a query directly. There is no need to do - * // this unless you're an advanced user with a very good reason to. - * const query = new mongoose.Query(); - * - * @param {Object} [options] - * @param {Object} [model] - * @param {Object} [conditions] - * @param {Object} [collection] Mongoose collection - * @api public - */ - -function Query(conditions, options, model, collection) { - // this stuff is for dealing with custom queries created by #toConstructor - if (!this._mongooseOptions) { - this._mongooseOptions = {}; - } - options = options || {}; - - this._transforms = []; - this._hooks = new Kareem(); - this._executionCount = 0; - - // this is the case where we have a CustomQuery, we need to check if we got - // options passed in, and if we did, merge them in - const keys = Object.keys(options); - for (let i = 0; i < keys.length; ++i) { - const k = keys[i]; - this._mongooseOptions[k] = options[k]; - } - - if (collection) { - this.mongooseCollection = collection; - } - - if (model) { - this.model = model; - this.schema = model.schema; - } - - // this is needed because map reduce returns a model that can be queried, but - // all of the queries on said model should be lean - if (this.model && this.model._mapreduce) { - this.lean(); - } - - // inherit mquery - mquery.call(this, this.mongooseCollection, options); - - if (conditions) { - this.find(conditions); - } - - this.options = this.options || {}; - - // For gh-6880. mquery still needs to support `fields` by default for old - // versions of MongoDB - this.$useProjection = true; - - const collation = get(this, 'schema.options.collation', null); - if (collation != null) { - this.options.collation = collation; - } -} - -/*! - * inherit mquery - */ - -Query.prototype = new mquery; -Query.prototype.constructor = Query; -Query.base = mquery.prototype; - -/** - * Flag to opt out of using `$geoWithin`. - * - * mongoose.Query.use$geoWithin = false; - * - * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work. - * - * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ - * @default true - * @property use$geoWithin - * @memberOf Query - * @receiver Query - * @api public - */ - -Query.use$geoWithin = mquery.use$geoWithin; - -/** - * Converts this query to a customized, reusable query constructor with all arguments and options retained. - * - * ####Example - * - * // Create a query for adventure movies and read from the primary - * // node in the replica-set unless it is down, in which case we'll - * // read from a secondary node. - * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred'); - * - * // create a custom Query constructor based off these settings - * var Adventure = query.toConstructor(); - * - * // Adventure is now a subclass of mongoose.Query and works the same way but with the - * // default query parameters and options set. - * Adventure().exec(callback) - * - * // further narrow down our query results while still using the previous settings - * Adventure().where({ name: /^Life/ }).exec(callback); - * - * // since Adventure is a stand-alone constructor we can also add our own - * // helper methods and getters without impacting global queries - * Adventure.prototype.startsWith = function (prefix) { - * this.where({ name: new RegExp('^' + prefix) }) - * return this; - * } - * Object.defineProperty(Adventure.prototype, 'highlyRated', { - * get: function () { - * this.where({ rating: { $gt: 4.5 }}); - * return this; - * } - * }) - * Adventure().highlyRated.startsWith('Life').exec(callback) - * - * @return {Query} subclass-of-Query - * @api public - */ - -Query.prototype.toConstructor = function toConstructor() { - const model = this.model; - const coll = this.mongooseCollection; - - const CustomQuery = function(criteria, options) { - if (!(this instanceof CustomQuery)) { - return new CustomQuery(criteria, options); - } - this._mongooseOptions = utils.clone(p._mongooseOptions); - Query.call(this, criteria, options || null, model, coll); - }; - - util.inherits(CustomQuery, model.Query); - - // set inherited defaults - const 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, { - flattenDecimals: false - }); - p._path = this._path; - p._distinct = this._distinct; - p._collection = this._collection; - p._mongooseOptions = this._mongooseOptions; - - return CustomQuery; -}; - -/** - * Specifies a javascript function or expression to pass to MongoDBs query system. - * - * ####Example - * - * query.$where('this.comments.length === 10 || this.name.length === 5') - * - * // or - * - * query.$where(function () { - * return this.comments.length === 10 || this.name.length === 5; - * }) - * - * ####NOTE: - * - * 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.** - * - * @see $where http://docs.mongodb.org/manual/reference/operator/where/ - * @method $where - * @param {String|Function} js javascript string or function - * @return {Query} this - * @memberOf Query - * @instance - * @method $where - * @api public - */ - -/** - * 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) - * - * @method where - * @memberOf Query - * @instance - * @param {String|Object} [path] - * @param {any} [val] - * @return {Query} this - * @api public - */ - -Query.prototype.slice = function() { - if (arguments.length === 0) { - return this; - } - - this._validate('slice'); - - let path; - let val; - - if (arguments.length === 1) { - const arg = arguments[0]; - if (typeof arg === 'object' && !Array.isArray(arg)) { - const keys = Object.keys(arg); - const numKeys = keys.length; - for (let 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 (arguments.length === 2) { - if ('number' === typeof arguments[0]) { - this._ensurePath('slice'); - path = this._path; - val = slice(arguments); - } else { - path = arguments[0]; - val = arguments[1]; - } - } else if (arguments.length === 3) { - path = arguments[0]; - val = slice(arguments, 1); - } - - const p = {}; - p[path] = { $slice: val }; - this.select(p); - - return this; -}; - - -/** - * Specifies the complementary comparison value for paths specified with `where()` - * - * ####Example - * - * User.where('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @method equals - * @memberOf Query - * @instance - * @param {Object} val - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for an `$or` condition. - * - * ####Example - * - * query.or([{ color: 'red' }, { status: 'emergency' }]) - * - * @see $or http://docs.mongodb.org/manual/reference/operator/or/ - * @method or - * @memberOf Query - * @instance - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for a `$nor` condition. - * - * ####Example - * - * query.nor([{ color: 'green' }, { status: 'ok' }]) - * - * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/ - * @method nor - * @memberOf Query - * @instance - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for a `$and` condition. - * - * ####Example - * - * query.and([{ color: 'green' }, { status: 'ok' }]) - * - * @method and - * @memberOf Query - * @instance - * @see $and http://docs.mongodb.org/manual/reference/operator/and/ - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * 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 - * @instance - * @param {String} [path] - * @param {Number} val - * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/ - * @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 - * @instance - * @param {String} [path] - * @param {Number} val - * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/ - * @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 - * @instance - * @param {String} [path] - * @param {Number} val - * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/ - * @api public - */ - -/** - * Specifies a $lte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lte - * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/ - * @memberOf Query - * @instance - * @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. - * - * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/ - * @method ne - * @memberOf Query - * @instance - * @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. - * - * @see $in http://docs.mongodb.org/manual/reference/operator/in/ - * @method in - * @memberOf Query - * @instance - * @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. - * - * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/ - * @method nin - * @memberOf Query - * @instance - * @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. - * - * @see $all http://docs.mongodb.org/manual/reference/operator/all/ - * @method all - * @memberOf Query - * @instance - * @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. - * - * ####Example - * - * MyModel.where('tags').size(0).exec(function (err, docs) { - * if (err) return handleError(err); - * - * assert(Array.isArray(docs)); - * console.log('documents with 0 tags', docs); - * }) - * - * @see $size http://docs.mongodb.org/manual/reference/operator/size/ - * @method size - * @memberOf Query - * @instance - * @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. - * - * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/ - * @method regex - * @memberOf Query - * @instance - * @param {String} [path] - * @param {String|RegExp} val - * @api public - */ - -/** - * Specifies a $maxDistance query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - * @method maxDistance - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a `$mod` condition, filters documents for documents whose - * `path` property is a number that is equal to `remainder` modulo `divisor`. - * - * ####Example - * - * // All find products whose inventory is odd - * Product.find().mod('inventory', [2, 1]); - * Product.find().where('inventory').mod([2, 1]); - * // This syntax is a little strange, but supported. - * Product.find().where('inventory').mod(2, 1); - * - * @method mod - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Array} val must be of length 2, first element is `divisor`, 2nd element is `remainder`. - * @return {Query} this - * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/ - * @api public - */ - -Query.prototype.mod = function() { - let val; - let path; - - if (arguments.length === 1) { - this._ensurePath('mod'); - val = arguments[0]; - path = this._path; - } else if (arguments.length === 2 && !Array.isArray(arguments[1])) { - this._ensurePath('mod'); - val = slice(arguments); - path = this._path; - } else if (arguments.length === 3) { - val = slice(arguments, 1); - path = arguments[0]; - } else { - val = arguments[1]; - path = arguments[0]; - } - - const 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); - * - * @method exists - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/ - * @api public - */ - -/** - * 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); - * }) - * - * @method elemMatch - * @memberOf Query - * @instance - * @param {String|Object|Function} path - * @param {Object|Function} criteria - * @return {Query} this - * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/ - * @api public - */ - -/** - * Defines a `$within` or `$geoWithin` argument for geo-spatial queries. - * - * ####Example - * - * query.where(path).within().box() - * query.where(path).within().circle() - * query.where(path).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 - * - * **MUST** be used after `where()`. - * - * ####NOTE: - * - * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin). - * - * ####NOTE: - * - * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). - * - * @method within - * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ - * @see $box http://docs.mongodb.org/manual/reference/operator/box/ - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see $center http://docs.mongodb.org/manual/reference/operator/center/ - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @memberOf Query - * @instance - * @return {Query} this - * @api public - */ - -/** - * Specifies a $slice projection for an array. - * - * ####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]) - * - * @method slice - * @memberOf Query - * @instance - * @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 - * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice - * @api public - */ - -/** - * Specifies the maximum number of documents the query will return. - * - * ####Example - * - * query.limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method limit - * @memberOf Query - * @instance - * @param {Number} val - * @api public - */ - -/** - * Specifies the number of documents to skip. - * - * ####Example - * - * query.skip(100).limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method skip - * @memberOf Query - * @instance - * @param {Number} val - * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/ - * @api public - */ - -/** - * Specifies the maxScan option. - * - * ####Example - * - * query.maxScan(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method maxScan - * @memberOf Query - * @instance - * @param {Number} val - * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/ - * @api public - */ - -/** - * Specifies the batchSize option. - * - * ####Example - * - * query.batchSize(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method batchSize - * @memberOf Query - * @instance - * @param {Number} val - * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/ - * @api public - */ - -/** - * Specifies the `comment` option. - * - * ####Example - * - * query.comment('login query') - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method comment - * @memberOf Query - * @instance - * @param {Number} val - * @see comment http://docs.mongodb.org/manual/reference/operator/comment/ - * @api public - */ - -/** - * Specifies this query as a `snapshot` query. - * - * ####Example - * - * query.snapshot() // true - * query.snapshot(true) - * query.snapshot(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method snapshot - * @memberOf Query - * @instance - * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/ - * @return {Query} this - * @api public - */ - -/** - * Sets query hints. - * - * ####Example - * - * query.hint({ indexA: 1, indexB: -1}) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method hint - * @memberOf Query - * @instance - * @param {Object} val a hint object - * @return {Query} this - * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/ - * @api public - */ - -/** - * Specifies which document fields to include or exclude (also known as the query "projection") - * - * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select). - * - * A projection _must_ be either inclusive or exclusive. In other words, you must - * either list the fields to include (which excludes all others), or list the fields - * to exclude (which implies all other fields are included). The [`_id` field is the only exception because MongoDB includes it by default](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#suppress-id-field). - * - * ####Example - * - * // include a and b, exclude other fields - * query.select('a b'); - * - * // exclude c and d, include other fields - * query.select('-c -d'); - * - * // Use `+` to override schema-level `select: false` without making the - * // projection inclusive. - * const schema = new Schema({ - * foo: { type: String, select: false }, - * bar: String - * }); - * // ... - * query.select('+foo'); // Override foo's `select: false` without excluding `bar` - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * query.select({ a: 1, b: 1 }); - * query.select({ c: 0, d: 0 }); - * - * - * @method select - * @memberOf Query - * @instance - * @param {Object|String} arg - * @return {Query} this - * @see SchemaType - * @api public - */ - -Query.prototype.select = function select() { - let arg = arguments[0]; - if (!arg) return this; - let i; - let len; - - if (arguments.length !== 1) { - throw new Error('Invalid select: select only takes 1 argument'); - } - - this._validate('select'); - - const fields = this._fields || (this._fields = {}); - const userProvidedFields = this._userProvidedFields || (this._userProvidedFields = {}); - const type = typeof arg; - - if (('string' == type || Object.prototype.toString.call(arg) === '[object Arguments]') && - 'number' == typeof arg.length || Array.isArray(arg)) { - if ('string' == type) - arg = arg.split(/\s+/); - - for (i = 0, len = arg.length; i < len; ++i) { - let field = arg[i]; - if (!field) continue; - const include = '-' == field[0] ? 0 : 1; - if (include === 0) field = field.substring(1); - fields[field] = include; - userProvidedFields[field] = include; - } - return this; - } - - if (utils.isObject(arg)) { - const keys = Object.keys(arg); - for (i = 0; i < keys.length; ++i) { - fields[keys[i]] = arg[keys[i]]; - userProvidedFields[keys[i]] = arg[keys[i]]; - } - return this; - } - - throw new TypeError('Invalid select() argument. Must be string or object.'); -}; - -/** - * _DEPRECATED_ Sets the slaveOk option. - * - * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read). - * - * ####Example: - * - * query.slaveOk() // true - * query.slaveOk(true) - * query.slaveOk(false) - * - * @method slaveOk - * @memberOf Query - * @instance - * @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 slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/ - * @see read() #query_Query-read - * @return {Query} this - * @api public - */ - -/** - * Determines the MongoDB nodes from which to read. - * - * ####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 - * - * ####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 - * - * // read from secondaries with matching tags - * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) - * - * Read more about how to use read preferrences [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). - * - * @method read - * @memberOf Query - * @instance - * @param {String} pref one of the listed preference options or aliases - * @param {Array} [tags] optional tags for this query - * @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 read(pref, tags) { - // first cast into a ReadPreference object to support tags - const read = new ReadPreference(pref, tags); - this.options.readPreference = read; - return this; -}; - -/** - * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/) - * associated with this query. Sessions are how you mark a query as part of a - * [transaction](/docs/transactions.html). - * - * Calling `session(null)` removes the session from this query. - * - * ####Example: - * - * const s = await mongoose.startSession(); - * await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s); - * - * @method session - * @memberOf Query - * @instance - * @param {ClientSession} [session] from `await conn.startSession()` - * @see Connection.prototype.startSession() /docs/api.html#connection_Connection-startSession - * @see mongoose.startSession() /docs/api.html#mongoose_Mongoose-startSession - * @return {Query} this - * @api public - */ - -Query.prototype.session = function session(v) { - if (v == null) { - delete this.options.session; - } - this.options.session = v; - return this; -}; - -/** - * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, - * that must acknowledge this write before this write is considered successful. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndReplace()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the schema's [`writeConcern.w` option](/docs/guide.html#writeConcern) - * - * ####Example: - * - * // The 'majority' option means the `deleteOne()` promise won't resolve - * // until the `deleteOne()` has propagated to the majority of the replica set - * await mongoose.model('Person'). - * deleteOne({ name: 'Ned Stark' }). - * w('majority'); - * - * @method w - * @memberOf Query - * @instance - * @param {String|number} val 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option - * @return {Query} this - * @api public - */ - -Query.prototype.w = function w(val) { - if (val == null) { - delete this.options.w; - } - this.options.w = val; - return this; -}; - -/** - * Requests acknowledgement that this operation has been persisted to MongoDB's - * on-disk journal. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndReplace()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the schema's [`writeConcern.j` option](/docs/guide.html#writeConcern) - * - * ####Example: - * - * await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true); - * - * @method j - * @memberOf Query - * @instance - * @param {boolean} val - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option - * @return {Query} this - * @api public - */ - -Query.prototype.j = function j(val) { - if (val == null) { - delete this.options.j; - } - this.options.j = val; - return this; -}; - -/** - * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to - * wait for this write to propagate through the replica set before this - * operation fails. The default is `0`, which means no timeout. - * - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndReplace()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the schema's [`writeConcern.wtimeout` option](/docs/guide.html#writeConcern) - * - * ####Example: - * - * // The `deleteOne()` promise won't resolve until this `deleteOne()` has - * // propagated to at least `w = 2` members of the replica set. If it takes - * // longer than 1 second, this `deleteOne()` will fail. - * await mongoose.model('Person'). - * deleteOne({ name: 'Ned Stark' }). - * w(2). - * wtimeout(1000); - * - * @method wtimeout - * @memberOf Query - * @instance - * @param {number} ms number of milliseconds to wait - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout - * @return {Query} this - * @api public - */ - -Query.prototype.wtimeout = function wtimeout(ms) { - if (ms == null) { - delete this.options.wtimeout; - } - this.options.wtimeout = ms; - return this; -}; - -/** - * Sets the readConcern option for the query. - * - * ####Example: - * - * new Query().readConcern('local') - * new Query().readConcern('l') // same as local - * - * new Query().readConcern('available') - * new Query().readConcern('a') // same as available - * - * new Query().readConcern('majority') - * new Query().readConcern('m') // same as majority - * - * new Query().readConcern('linearizable') - * new Query().readConcern('lz') // same as linearizable - * - * new Query().readConcern('snapshot') - * new Query().readConcern('s') // same as snapshot - * - * - * ####Read Concern Level: - * - * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. - * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. - * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. - * - * Aliases - * - * l local - * a available - * m majority - * lz linearizable - * s snapshot - * - * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). - * - * @memberOf Query - * @method readConcern - * @param {String} level one of the listed read concern level or their aliases - * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ - * @return {Query} this - * @api public - */ - -/** - * Merges another Query or conditions object into this one. - * - * When a Query is passed, conditions, field selection and options are merged. - * - * @method merge - * @memberOf Query - * @instance - * @param {Query|Object} source - * @return {Query} this - */ - -/** - * Gets query options. - * - * ####Example: - * - * var query = new Query(); - * query.limit(10); - * query.setOptions({ maxTimeMS: 1000 }) - * query.getOptions(); // { limit: 10, maxTimeMS: 1000 } - * - * @return {Object} the options - * @api public - */ - -Query.prototype.getOptions = function() { - return this.options; -}; - -/** - * Sets query options. Some options only make sense for certain operations. - * - * ####Options: - * - * The following options are only for `find()`: - * - * - [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](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan) - * - [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) - * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference) - * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) - * - * The following options are only for write operations: `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`: - * - * - [upsert](https://docs.mongodb.com/manual/reference/method/db.collection.update/) - * - [writeConcern](https://docs.mongodb.com/manual/reference/method/db.collection.update/) - * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): If `timestamps` is set in the schema, set this option to `false` to skip timestamps for that particular update. Has no effect if `timestamps` is not enabled in the schema options. - * - * The following options are only for `find()`, `findOne()`, `findById()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`: - * - * - [lean](./api.html#query_Query-lean) - * - * The following options are only for all operations **except** `update()`, `updateOne()`, `updateMany()`, `remove()`, `deleteOne()`, and `deleteMany()`: - * - * - [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) - * - * The following options are for all operations: - * - * - [collation](https://docs.mongodb.com/manual/reference/collation/) - * - [session](https://docs.mongodb.com/manual/reference/server-sessions/) - * - * @param {Object} options - * @return {Query} this - * @api public - */ - -Query.prototype.setOptions = function(options, overwrite) { - // overwrite is only for internal use - if (overwrite) { - // ensure that _mongooseOptions & options are two different objects - this._mongooseOptions = (options && utils.clone(options)) || {}; - this.options = options || {}; - - if ('populate' in options) { - this.populate(this._mongooseOptions); - } - return this; - } - - if (options == null) { - return this; - } - if (typeof options !== 'object') { - throw new Error('Options must be an object, got "' + options + '"'); - } - - if (Array.isArray(options.populate)) { - const populate = options.populate; - delete options.populate; - const _numPopulate = populate.length; - for (let i = 0; i < _numPopulate; ++i) { - this.populate(populate[i]); - } - } - - if ('useFindAndModify' in options) { - this._mongooseOptions.useFindAndModify = options.useFindAndModify; - delete options.useFindAndModify; - } - if ('omitUndefined' in options) { - this._mongooseOptions.omitUndefined = options.omitUndefined; - delete options.omitUndefined; - } - - return Query.base.setOptions.call(this, options); -}; - -/** - * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/), - * which makes this query return detailed execution stats instead of the actual - * query result. This method is useful for determining what index your queries - * use. - * - * Calling `query.explain(v)` is equivalent to `query.setOption({ explain: v })` - * - * ####Example: - * - * const query = new Query(); - * const res = await query.find({ a: 1 }).explain('queryPlanner'); - * console.log(res); - * - * @param {String} [verbose] The verbosity mode. Either 'queryPlanner', 'executionStats', or 'allPlansExecution'. The default is 'queryPlanner' - * @return {Query} this - * @api public - */ - -Query.prototype.explain = function(verbose) { - if (arguments.length === 0) { - this.options.explain = true; - return this; - } - this.options.explain = verbose; - return this; -}; - -/** - * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/) - * option. This will tell the MongoDB server to abort if the query or write op - * has been running for more than `ms` milliseconds. - * - * Calling `query.maxTimeMS(v)` is equivalent to `query.setOption({ maxTimeMS: v })` - * - * ####Example: - * - * const query = new Query(); - * // Throws an error 'operation exceeded time limit' as long as there's - * // >= 1 doc in the queried collection - * const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100); - * - * @param {Number} [ms] The number of milliseconds - * @return {Query} this - * @api public - */ - -Query.prototype.maxTimeMS = function(ms) { - this.options.maxTimeMS = ms; - return this; -}; - -/** - * Returns the current query conditions as a JSON object. - * - * ####Example: - * - * var query = new Query(); - * query.find({ a: 1 }).where('b').gt(2); - * query.getQuery(); // { a: 1, b: { $gt: 2 } } - * - * @return {Object} current query conditions - * @api public - */ - -Query.prototype.getQuery = function() { - return this._conditions; -}; - -/** - * Sets the query conditions to the provided JSON object. - * - * ####Example: - * - * var query = new Query(); - * query.find({ a: 1 }) - * query.setQuery({ a: 2 }); - * query.getQuery(); // { a: 2 } - * - * @param {Object} new query conditions - * @return {undefined} - * @api public - */ - -Query.prototype.setQuery = function(val) { - this._conditions = val; -}; - -/** - * Returns the current update operations as a JSON object. - * - * ####Example: - * - * var query = new Query(); - * query.update({}, { $set: { a: 5 } }); - * query.getUpdate(); // { $set: { a: 5 } } - * - * @return {Object} current update operations - * @api public - */ - -Query.prototype.getUpdate = function() { - return this._update; -}; - -/** - * Sets the current update operation to new value. - * - * ####Example: - * - * var query = new Query(); - * query.update({}, { $set: { a: 5 } }); - * query.setUpdate({ $set: { b: 6 } }); - * query.getUpdate(); // { $set: { b: 6 } } - * - * @param {Object} new update operation - * @return {undefined} - * @api public - */ - -Query.prototype.setUpdate = function(val) { - this._update = val; -}; - -/** - * Returns fields selection for this query. - * - * @method _fieldsForExec - * @return {Object} - * @api private - * @receiver Query - */ - -Query.prototype._fieldsForExec = function() { - return utils.clone(this._fields); -}; - - -/** - * Return an update document with corrected $set operations. - * - * @method _updateForExec - * @api private - * @receiver Query - */ - -Query.prototype._updateForExec = function() { - const update = utils.clone(this._update, { - transform: false, - depopulate: true - }); - const ops = Object.keys(update); - let i = ops.length; - const ret = {}; - - while (i--) { - const 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; -}; - -/** - * Makes sure _path is set. - * - * @method _ensurePath - * @param {String} method - * @api private - * @receiver Query - */ - -/** - * Determines if `conds` can be merged using `mquery().merge()` - * - * @method canMerge - * @memberOf Query - * @instance - * @param {Object} conds - * @return {Boolean} - * @api private - */ - -/** - * Returns default options for this query. - * - * @param {Model} model - * @api private - */ - -Query.prototype._optionsForExec = function(model) { - const options = utils.clone(this.options); - - delete options.populate; - model = model || this.model; - - if (!model) { - return options; - } - - const safe = get(model, 'schema.options.safe', null); - if (!('safe' in options) && safe != null) { - setSafe(options, safe); - } - - // Apply schema-level `writeConcern` option - applyWriteConcern(model.schema, options); - - const readPreference = get(model, 'schema.options.read'); - if (!('readPreference' in options) && readPreference) { - options.readPreference = readPreference; - } - - if (options.upsert !== void 0) { - options.upsert = !!options.upsert; - } - - return options; -}; - -/*! - * ignore - */ - -const safeDeprecationWarning = 'Mongoose: the `safe` option is deprecated. ' + - 'Use write concerns instead: http://bit.ly/mongoose-w'; - -const setSafe = util.deprecate(function setSafe(options, safe) { - options.safe = safe; -}, safeDeprecationWarning); - -/** - * Sets the lean option. - * - * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied. - * - * ####Example: - * - * new Query().lean() // true - * new Query().lean(true) - * new Query().lean(false) - * - * Model.find().lean().exec(function (err, docs) { - * docs[0] instanceof mongoose.Document // false - * }); - * - * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream). - * - * @param {Boolean|Object} bool defaults to true - * @return {Query} this - * @api public - */ - -Query.prototype.lean = function(v) { - this._mongooseOptions.lean = arguments.length ? v : true; - return this; -}; - -/** - * Adds a `$set` to this query's update without changing the operation. - * This is useful for query middleware so you can add an update regardless - * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc. - * - * ####Example: - * - * // Updates `{ $set: { updatedAt: new Date() } }` - * new Query().updateOne({}, {}).set('updatedAt', new Date()); - * new Query().updateMany({}, {}).set({ updatedAt: new Date() }); - * - * @param {String|Object} path path or object of key/value pairs to set - * @param {Any} [val] the value to set - * @return {Query} this - * @api public - */ - -Query.prototype.set = function(path, val) { - if (typeof path === 'object') { - const keys = Object.keys(path); - for (const key of keys) { - this.set(key, path[key]); - } - return this; - } - - this._update = this._update || {}; - this._update.$set = this._update.$set || {}; - this._update.$set[path] = val; - return this; -}; - -/** - * Gets/sets the error flag on this query. If this flag is not null or - * undefined, the `exec()` promise will reject without executing. - * - * ####Example: - * - * Query().error(); // Get current error value - * Query().error(null); // Unset the current error - * Query().error(new Error('test')); // `exec()` will resolve with test - * Schema.pre('find', function() { - * if (!this.getQuery().userId) { - * this.error(new Error('Not allowed to query without setting userId')); - * } - * }); - * - * Note that query casting runs **after** hooks, so cast errors will override - * custom errors. - * - * ####Example: - * var TestSchema = new Schema({ num: Number }); - * var TestModel = db.model('Test', TestSchema); - * TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) { - * // `error` will be a cast error because `num` failed to cast - * }); - * - * @param {Error|null} err if set, `exec()` will fail fast before sending the query to MongoDB - * @return {Query} this - * @api public - */ - -Query.prototype.error = function error(err) { - if (arguments.length === 0) { - return this._error; - } - - this._error = err; - return this; -}; - -/*! - * ignore - */ - -Query.prototype._unsetCastError = function _unsetCastError() { - if (this._error != null && !(this._error instanceof CastError)) { - return; - } - return this.error(null); -}; - -/** - * Getter/setter around the current mongoose-specific options for this query - * Below are the current Mongoose-specific options. - * - * - `populate`: an array representing what paths will be populated. Should have one entry for each call to [`Query.prototype.populate()`](/docs/api.html#query_Query-populate) - * - `lean`: if truthy, Mongoose will not [hydrate](/docs/api.html#model_Model.hydrate) any documents that are returned from this query. See [`Query.prototype.lean()`](/docs/api.html#query_Query-lean) for more information. - * - `strict`: controls how Mongoose handles keys that aren't in the schema for updates. This option is `true` by default, which means Mongoose will silently strip any paths in the update that aren't in the schema. See the [`strict` mode docs](/docs/guide.html#strict) for more information. - * - `strictQuery`: controls how Mongoose handles keys that aren't in the schema for the query `filter`. This option is `false` by default for backwards compatibility, which means Mongoose will allow `Model.find({ foo: 'bar' })` even if `foo` is not in the schema. See the [`strictQuery` docs](/docs/guide.html#strictQuery) for more information. - * - `useFindAndModify`: used to work around the [`findAndModify()` deprecation warning](/docs/deprecations.html#-findandmodify-) - * - `omitUndefined`: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * - `nearSphere`: use `$nearSphere` instead of `near()`. See the [`Query.prototype.nearSphere()` docs](/docs/api.html#query_Query-nearSphere) - * - * Mongoose maintains a separate object for internal options because - * Mongoose sends `Query.prototype.options` to the MongoDB server, and the - * above options are not relevant for the MongoDB server. - * - * @param {Object} options if specified, overwrites the current options - * @return {Object} the options - * @api public - */ - -Query.prototype.mongooseOptions = function(v) { - if (arguments.length > 0) { - this._mongooseOptions = v; - } - return this._mongooseOptions; -}; - -/*! - * ignore - */ - -Query.prototype._castConditions = function() { - try { - this.cast(this.model); - this._unsetCastError(); - } catch (err) { - this.error(err); - } -}; - -/*! - * ignore - */ - -function _castArrayFilters(query) { - try { - castArrayFilters(query); - } catch (err) { - query.error(err); - } -} - -/** - * Thunk around find() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ -Query.prototype._find = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return null; - } - - callback = _wrapThunkCallback(this, callback); - - this._applyPaths(); - this._fields = this._castFields(this._fields); - - const fields = this._fieldsForExec(); - const mongooseOptions = this._mongooseOptions; - const _this = this; - const userProvidedFields = _this._userProvidedFields || {}; - - // Separate options to pass down to `completeMany()` in case we need to - // set a session on the document - const completeManyOptions = Object.assign({}, { - session: get(this, 'options.session', null) - }); - - const cb = (err, docs) => { - if (err) { - return callback(err); - } - - if (docs.length === 0) { - return callback(null, docs); - } - if (this.options.explain) { - return callback(null, docs); - } - - if (!mongooseOptions.populate) { - return mongooseOptions.lean ? - callback(null, docs) : - completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback); - } - - const pop = helpers.preparePopulationOptionsMQ(_this, mongooseOptions); - completeManyOptions.populated = pop; - _this.model.populate(docs, pop, function(err, docs) { - if (err) return callback(err); - return mongooseOptions.lean ? - callback(null, docs) : - completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback); - }); - }; - - const options = this._optionsForExec(); - options.projection = this._fieldsForExec(); - const filter = this._conditions; - - this._collection.find(filter, options, cb); - return null; -}); - -/** - * Find all documents that match `selector`. The result will be an array of documents. - * - * If there are too many documents in the result to fit in memory, use - * [`Query.prototype.cursor()`](api.html#query_Query-cursor) - * - * ####Example - * - * // Using async/await - * const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } }); - * - * // Using callbacks - * Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {}); - * - * @param {Object} [filter] mongodb selector. If not specified, returns all documents. - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.find = function(conditions, callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - } - - conditions = utils.toObject(conditions); - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - - prepareDiscriminatorCriteria(this); - } else if (conditions != null) { - this.error(new ObjectParameterError(conditions, 'filter', 'find')); - } - - // if we don't have a callback, then just return the query object - if (!callback) { - return Query.base.find.call(this); - } - - this._find(callback); - - 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; - } - - const opts = { overwrite: true }; - - if (source instanceof Query) { - // if source has a feature, apply it to ourselves - - if (source._conditions) { - utils.merge(this._conditions, source._conditions, opts); - } - - if (source._fields) { - this._fields || (this._fields = {}); - utils.merge(this._fields, source._fields, opts); - } - - if (source.options) { - this.options || (this.options = {}); - utils.merge(this.options, source.options, opts); - } - - if (source._update) { - this._update || (this._update = {}); - utils.mergeClone(this._update, source._update); - } - - if (source._distinct) { - this._distinct = source._distinct; - } - - utils.merge(this._mongooseOptions, source._mongooseOptions); - - return this; - } - - // plain object - utils.merge(this._conditions, source, opts); - - return this; -}; - -/** - * Adds a collation to this op (MongoDB 3.4 and up) - * - * @param {Object} value - * @return {Query} this - * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation - * @api public - */ - -Query.prototype.collation = function(value) { - if (this.options == null) { - this.options = {}; - } - this.options.collation = value; - return this; -}; - -/** - * Hydrate a single doc from `findOne()`, `findOneAndUpdate()`, etc. - * - * @api private - */ - -Query.prototype._completeOne = function(doc, res, callback) { - if (!doc) { - return callback(null, null); - } - - const model = this.model; - const projection = utils.clone(this._fields); - const userProvidedFields = this._userProvidedFields || {}; - // `populate`, `lean` - const mongooseOptions = this._mongooseOptions; - // `rawResult` - const options = this.options; - - if (options.explain) { - return callback(null, doc); - } - - if (!mongooseOptions.populate) { - return mongooseOptions.lean ? - _completeOneLean(doc, res, options, callback) : - completeOne(model, doc, res, options, projection, userProvidedFields, - null, callback); - } - - const pop = helpers.preparePopulationOptionsMQ(this, this._mongooseOptions); - model.populate(doc, pop, (err, doc) => { - if (err) { - return callback(err); - } - return mongooseOptions.lean ? - _completeOneLean(doc, res, options, callback) : - completeOne(model, doc, res, options, projection, userProvidedFields, - pop, callback); - }); -}; - -/** - * Thunk around findOne() - * - * @param {Function} [callback] - * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ - * @api private - */ - -Query.prototype._findOne = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error()) { - callback(this.error()); - return null; - } - - this._applyPaths(); - this._fields = this._castFields(this._fields); - - // don't pass in the conditions because we already merged them in - Query.base.findOne.call(this, {}, (err, doc) => { - if (err) { - callback(err); - return null; - } - - this._completeOne(doc, null, _wrapThunkCallback(this, callback)); - }); -}); - -/** - * Declares the query a findOne operation. When executed, the first found document is passed to the callback. - * - * Passing a `callback` executes the query. The result of the query is a single document. - * - * * *Note:* `conditions` is optional, and if `conditions` is null or undefined, - * mongoose will send an empty `findOne` command to MongoDB, which will return - * an arbitrary document. If you're querying by `_id`, use `Model.findById()` - * instead. - * - * This function triggers the following middleware. - * - * - `findOne()` - * - * ####Example - * - * var query = Kitten.where({ color: 'white' }); - * query.findOne(function (err, kitten) { - * if (err) return handleError(err); - * if (kitten) { - * // doc may be null if no document matched - * } - * }); - * - * @param {Object} [filter] mongodb selector - * @param {Object} [projection] optional fields to return - * @param {Object} [options] see [`setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ - * @see Query.select #query_Query-select - * @api public - */ - -Query.prototype.findOne = function(conditions, projection, options, callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = null; - projection = null; - options = null; - } else if (typeof projection === 'function') { - callback = projection; - options = null; - projection = null; - } else if (typeof options === 'function') { - callback = options; - options = null; - } - - // make sure we don't send in the whole Document to merge() - conditions = utils.toObject(conditions); - - this.op = 'findOne'; - - if (options) { - this.setOptions(options); - } - - if (projection) { - this.select(projection); - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - - prepareDiscriminatorCriteria(this); - } else if (conditions != null) { - this.error(new ObjectParameterError(conditions, 'filter', 'findOne')); - } - - if (!callback) { - // already merged in the conditions, don't need to send them in. - return Query.base.findOne.call(this); - } - - this._findOne(callback); - - return this; -}; - -/** - * Thunk around count() - * - * @param {Function} [callback] - * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ - * @api private - */ - -Query.prototype._count = wrapThunk(function(callback) { - try { - this.cast(this.model); - } catch (err) { - this.error(err); - } - - if (this.error()) { - return callback(this.error()); - } - - const conds = this._conditions; - const options = this._optionsForExec(); - - this._collection.count(conds, options, utils.tick(callback)); -}); - -/** - * Thunk around countDocuments() - * - * @param {Function} [callback] - * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments - * @api private - */ - -Query.prototype._countDocuments = wrapThunk(function(callback) { - try { - this.cast(this.model); - } catch (err) { - this.error(err); - } - - if (this.error()) { - return callback(this.error()); - } - - const conds = this._conditions; - const options = this._optionsForExec(); - - this._collection.collection.countDocuments(conds, options, utils.tick(callback)); -}); - -/** - * Thunk around estimatedDocumentCount() - * - * @param {Function} [callback] - * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount - * @api private - */ - -Query.prototype._estimatedDocumentCount = wrapThunk(function(callback) { - if (this.error()) { - return callback(this.error()); - } - - const options = this._optionsForExec(); - - this._collection.collection.estimatedDocumentCount(options, utils.tick(callback)); -}); - -/** - * Specifies this query as a `count` query. - * - * This method is deprecated. If you want to count the number of documents in - * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#query_Query-estimatedDocumentCount) - * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#query_Query-countDocuments) function instead. - * - * Passing a `callback` executes the query. - * - * This function triggers the following middleware. - * - * - `count()` - * - * ####Example: - * - * var countQuery = model.where({ 'color': 'black' }).count(); - * - * 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); - * }) - * - * @deprecated - * @param {Object} [filter] count documents that match this object - * @param {Function} [callback] optional params are (error, count) - * @return {Query} this - * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ - * @api public - */ - -Query.prototype.count = function(filter, callback) { - if (typeof filter === 'function') { - callback = filter; - filter = undefined; - } - - filter = utils.toObject(filter); - - if (mquery.canMerge(filter)) { - this.merge(filter); - } - - this.op = 'count'; - if (!callback) { - return this; - } - - this._count(callback); - - return this; -}; - -/** - * Specifies this query as a `estimatedDocumentCount()` query. Faster than - * using `countDocuments()` for large collections because - * `estimatedDocumentCount()` uses collection metadata rather than scanning - * the entire collection. - * - * `estimatedDocumentCount()` does **not** accept a filter. `Model.find({ foo: bar }).estimatedDocumentCount()` - * is equivalent to `Model.find().estimatedDocumentCount()` - * - * This function triggers the following middleware. - * - * - `estimatedDocumentCount()` - * - * ####Example: - * - * await Model.find().estimatedDocumentCount(); - * - * @param {Object} [options] passed transparently to the [MongoDB driver](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount) - * @param {Function} [callback] optional params are (error, count) - * @return {Query} this - * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount - * @api public - */ - -Query.prototype.estimatedDocumentCount = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = undefined; - } - - if (typeof options === 'object' && options != null) { - this.setOptions(options); - } - - this.op = 'estimatedDocumentCount'; - if (!callback) { - return this; - } - - this._estimatedDocumentCount(callback); - - return this; -}; - -/** - * Specifies this query as a `countDocuments()` query. Behaves like `count()`, - * except it always does a full collection scan when passed an empty filter `{}`. - * - * There are also minor differences in how `countDocuments()` handles - * [`$where` and a couple geospatial operators](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). - * versus `count()`. - * - * Passing a `callback` executes the query. - * - * This function triggers the following middleware. - * - * - `countDocuments()` - * - * ####Example: - * - * const countQuery = model.where({ 'color': 'black' }).countDocuments(); - * - * query.countDocuments({ color: 'black' }).count(callback); - * - * query.countDocuments({ color: 'black' }, callback); - * - * query.where('color', 'black').countDocuments(function(err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }); - * - * The `countDocuments()` function is similar to `count()`, but there are a - * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). - * Below are the operators that `count()` supports but `countDocuments()` does not, - * and the suggested replacement: - * - * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) - * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) - * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) - * - * @param {Object} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, count) - * @return {Query} this - * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments - * @api public - */ - -Query.prototype.countDocuments = function(conditions, callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = undefined; - } - - conditions = utils.toObject(conditions); - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - this.op = 'countDocuments'; - if (!callback) { - return this; - } - - this._countDocuments(callback); - - return this; -}; - -/** - * Declares or executes a distict() operation. - * - * Passing a `callback` executes the query. - * - * This function does not trigger any middleware. - * - * ####Example - * - * distinct(field, conditions, callback) - * distinct(field, conditions) - * distinct(field, callback) - * distinct(field) - * distinct(callback) - * distinct() - * - * @param {String} [field] - * @param {Object|Query} [filter] - * @param {Function} [callback] optional params are (error, arr) - * @return {Query} this - * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ - * @api public - */ - -Query.prototype.distinct = function(field, conditions, callback) { - if (!callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = undefined; - } else if (typeof field === 'function') { - callback = field; - field = undefined; - conditions = undefined; - } - } - - conditions = utils.toObject(conditions); - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - - prepareDiscriminatorCriteria(this); - } else if (conditions != null) { - this.error(new ObjectParameterError(conditions, 'filter', 'distinct')); - } - - if (callback != null) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return this; - } - } - - return Query.base.distinct.call(this, {}, field, callback); -}; - -/** - * 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 - * - * // sort by "field" ascending and "test" descending - * query.sort({ field: 'asc', test: -1 }); - * - * // equivalent - * query.sort('field -test'); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/ - * @api public - */ - -Query.prototype.sort = function(arg) { - if (arguments.length > 1) { - throw new Error('sort() only takes 1 Argument'); - } - - return Query.base.sort.call(this, arg); -}; - -/** - * Declare and/or execute this query as a remove() operation. `remove()` is - * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne) - * or [`deleteMany()`](#query_Query-deleteMany) instead. - * - * This function does not trigger any middleware - * - * ####Example - * - * Character.remove({ name: /Stark/ }, callback); - * - * This function calls the MongoDB driver's [`Collection#remove()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove). - * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an - * object that contains 3 properties: - * - * - `ok`: `1` if no errors occurred - * - `deletedCount`: the number of documents deleted - * - `n`: the number of documents deleted. Equal to `deletedCount`. - * - * ####Example - * - * const res = await Character.remove({ name: /Stark/ }); - * // Number of docs deleted - * res.deletedCount; - * - * ####Note - * - * Calling `remove()` creates a [Mongoose query](./queries.html), and a query - * does not execute until you either pass a callback, call [`Query#then()`](#query_Query-then), - * or call [`Query#exec()`](#query_Query-exec). - * - * // not executed - * const query = Character.remove({ name: /Stark/ }); - * - * // executed - * Character.remove({ name: /Stark/ }, callback); - * Character.remove({ name: /Stark/ }).remove(callback); - * - * // executed without a callback - * Character.exec(); - * - * @param {Object|Query} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, mongooseDeleteResult) - * @return {Query} this - * @deprecated - * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult - * @see MongoDB driver remove http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove - * @api public - */ - -Query.prototype.remove = function(filter, callback) { - if (typeof filter === 'function') { - callback = filter; - filter = null; - } - - filter = utils.toObject(filter); - - if (mquery.canMerge(filter)) { - this.merge(filter); - - prepareDiscriminatorCriteria(this); - } else if (filter != null) { - this.error(new ObjectParameterError(filter, 'filter', 'remove')); - } - - if (!callback) { - return Query.base.remove.call(this); - } - - this._remove(callback); - return this; -}; - -/*! - * ignore - */ - -Query.prototype._remove = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return this; - } - - callback = _wrapThunkCallback(this, callback); - - return Query.base.remove.call(this, helpers.handleDeleteWriteOpResult(callback)); -}); - -/** - * Declare and/or execute this query as a `deleteOne()` operation. Works like - * remove, except it deletes at most one document regardless of the `single` - * option. - * - * This function does not trigger any middleware. - * - * ####Example - * - * Character.deleteOne({ name: 'Eddard Stark' }, callback); - * Character.deleteOne({ name: 'Eddard Stark' }).then(next); - * - * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne). - * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an - * object that contains 3 properties: - * - * - `ok`: `1` if no errors occurred - * - `deletedCount`: the number of documents deleted - * - `n`: the number of documents deleted. Equal to `deletedCount`. - * - * ####Example - * - * const res = await Character.deleteOne({ name: 'Eddard Stark' }); - * // `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }` - * res.deletedCount; - * - * @param {Object|Query} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, mongooseDeleteResult) - * @return {Query} this - * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult - * @see MongoDB Driver deleteOne http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne - * @api public - */ - -Query.prototype.deleteOne = function(filter, callback) { - if (typeof filter === 'function') { - callback = filter; - filter = null; - } - - filter = utils.toObject(filter); - - if (mquery.canMerge(filter)) { - this.merge(filter); - - prepareDiscriminatorCriteria(this); - } else if (filter != null) { - this.error(new ObjectParameterError(filter, 'filter', 'deleteOne')); - } - - if (!callback) { - return Query.base.deleteOne.call(this); - } - - this._deleteOne.call(this, callback); - - return this; -}; - -/*! - * Internal thunk for `deleteOne()` - */ - -Query.prototype._deleteOne = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return this; - } - - callback = _wrapThunkCallback(this, callback); - - return Query.base.deleteOne.call(this, helpers.handleDeleteWriteOpResult(callback)); -}); - -/** - * Declare and/or execute this query as a `deleteMany()` operation. Works like - * remove, except it deletes _every_ document that matches `criteria` in the - * collection, regardless of the value of `single`. - * - * This function does not trigger any middleware - * - * ####Example - * - * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback) - * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }).then(next) - * - * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany). - * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an - * object that contains 3 properties: - * - * - `ok`: `1` if no errors occurred - * - `deletedCount`: the number of documents deleted - * - `n`: the number of documents deleted. Equal to `deletedCount`. - * - * ####Example - * - * const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); - * // `0` if no docs matched the filter, number of docs deleted otherwise - * res.deletedCount; - * - * @param {Object|Query} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, mongooseDeleteResult) - * @return {Query} this - * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult - * @see MongoDB Driver deleteMany http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany - * @api public - */ - -Query.prototype.deleteMany = function(filter, callback) { - if (typeof filter === 'function') { - callback = filter; - filter = null; - } - - filter = utils.toObject(filter); - - if (mquery.canMerge(filter)) { - this.merge(filter); - - prepareDiscriminatorCriteria(this); - } else if (filter != null) { - this.error(new ObjectParameterError(filter, 'filter', 'deleteMany')); - } - - if (!callback) { - return Query.base.deleteMany.call(this); - } - - this._deleteMany.call(this, callback); - - return this; -}; - -/*! - * Internal thunk around `deleteMany()` - */ - -Query.prototype._deleteMany = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return this; - } - - callback = _wrapThunkCallback(this, callback); - - return Query.base.deleteMany.call(this, helpers.handleDeleteWriteOpResult(callback)); -}); - -/*! - * hydrates a document - * - * @param {Model} model - * @param {Document} doc - * @param {Object} res 3rd parameter to callback - * @param {Object} fields - * @param {Query} self - * @param {Array} [pop] array of paths used in population - * @param {Function} callback - */ - -function completeOne(model, doc, res, options, fields, userProvidedFields, pop, callback) { - const opts = pop ? - {populated: pop} - : undefined; - - const casted = helpers.createModel(model, doc, fields, userProvidedFields); - try { - casted.init(doc, opts, _init); - } catch (error) { - _init(error); - } - - function _init(err) { - if (err) { - return process.nextTick(() => callback(err)); - } - - casted.$session(options.session); - - if (options.rawResult) { - res.value = casted; - return process.nextTick(() => callback(null, res)); - } - process.nextTick(() => callback(null, casted)); - } -} - -/*! - * If the model is a discriminator type and not root, then add the key & value to the criteria. - */ - -function prepareDiscriminatorCriteria(query) { - if (!query || !query.model || !query.model.schema) { - return; - } - - const schema = query.model.schema; - - if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { - query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; - } -} - -/** - * 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 if - * `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndUpdate()` - * - * ####Available options - * - * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false. - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####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 - * - * @method findOneAndUpdate - * @memberOf Query - * @instance - * @param {Object|Query} [query] - * @param {Object} [doc] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean). - * @param {Function} [callback] optional params are (error, doc), _unless_ `rawResult` is used, in which case params are (error, writeOpResult) - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @return {Query} this - * @api public - */ - -Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) { - this.op = 'findOneAndUpdate'; - this._validate(); - - switch (arguments.length) { - case 3: - if (typeof options === 'function') { - callback = options; - options = {}; - } - break; - case 2: - if (typeof doc === 'function') { - callback = doc; - doc = criteria; - criteria = undefined; - } - options = undefined; - break; - case 1: - if (typeof criteria === 'function') { - callback = criteria; - criteria = options = doc = undefined; - } else { - doc = criteria; - criteria = options = undefined; - } - } - - if (mquery.canMerge(criteria)) { - this.merge(criteria); - } - - // apply doc - if (doc) { - this._mergeUpdate(doc); - } - - if (options) { - options = utils.clone(options); - if (options.projection) { - this.select(options.projection); - delete options.projection; - } - if (options.fields) { - this.select(options.fields); - delete options.fields; - } - - this.setOptions(options); - } - - if (!callback) { - return this; - } - - this._findOneAndUpdate(callback); - - return this; -}; - -/*! - * Thunk around findOneAndUpdate() - * - * @param {Function} [callback] - * @api private - */ - -Query.prototype._findOneAndUpdate = wrapThunk(function(callback) { - if (this.error() != null) { - return callback(this.error()); - } - - 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 if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndRemove()` - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####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 - * - * @method findOneAndRemove - * @memberOf Query - * @instance - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Function} [callback] optional params are (error, document) - * @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(); - - switch (arguments.length) { - case 2: - if (typeof options === 'function') { - callback = options; - options = {}; - } - break; - case 1: - if (typeof conditions === 'function') { - callback = conditions; - conditions = undefined; - options = undefined; - } - break; - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - options && this.setOptions(options); - - if (!callback) { - return this; - } - - this._findOneAndRemove(callback); - - return this; -}; - -/** - * Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command. - * - * Finds a matching document, removes it, and passes the found document (if any) - * to the callback. Executes if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndDelete()` - * - * This function differs slightly from `Model.findOneAndRemove()` in that - * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), - * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, - * this distinction is purely pedantic. You should use `findOneAndDelete()` - * unless you have a good reason not to. - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####Examples - * - * A.where().findOneAndDelete(conditions, options, callback) // executes - * A.where().findOneAndDelete(conditions, options) // return Query - * A.where().findOneAndDelete(conditions, callback) // executes - * A.where().findOneAndDelete(conditions) // returns Query - * A.where().findOneAndDelete(callback) // executes - * A.where().findOneAndDelete() // returns Query - * - * @method findOneAndDelete - * @memberOf Query - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Query.prototype.findOneAndDelete = function(conditions, options, callback) { - this.op = 'findOneAndDelete'; - this._validate(); - - switch (arguments.length) { - case 2: - if (typeof options === 'function') { - callback = options; - options = {}; - } - break; - case 1: - if (typeof conditions === 'function') { - callback = conditions; - conditions = undefined; - options = undefined; - } - break; - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - options && this.setOptions(options); - - if (!callback) { - return this; - } - - this._findOneAndDelete(callback); - - return this; -}; - -/*! - * Thunk around findOneAndDelete() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ -Query.prototype._findOneAndDelete = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return null; - } - - const filter = this._conditions; - const options = this._optionsForExec(); - let fields = null; - - if (this._fields != null) { - options.projection = this._castFields(utils.clone(this._fields)); - fields = options.projection; - if (fields instanceof Error) { - callback(fields); - return null; - } - } - - this._collection.collection.findOneAndDelete(filter, options, _wrapThunkCallback(this, (err, res) => { - if (err) { - return callback(err); - } - - const doc = res.value; - - return this._completeOne(doc, res, callback); - })); -}); - -/** - * Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command. - * - * Finds a matching document, removes it, and passes the found document (if any) - * to the callback. Executes if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndReplace()` - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####Examples - * - * A.where().findOneAndReplace(conditions, options, callback) // executes - * A.where().findOneAndReplace(conditions, options) // return Query - * A.where().findOneAndReplace(conditions, callback) // executes - * A.where().findOneAndReplace(conditions) // returns Query - * A.where().findOneAndReplace(callback) // executes - * A.where().findOneAndReplace() // returns Query - * - * @method findOneAndReplace - * @memberOf Query - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @api public - */ - -Query.prototype.findOneAndReplace = function(conditions, options, callback) { - this.op = 'findOneAndReplace'; - this._validate(); - - switch (arguments.length) { - case 2: - if (typeof options === 'function') { - callback = options; - options = {}; - } - break; - case 1: - if (typeof conditions === 'function') { - callback = conditions; - conditions = undefined; - options = undefined; - } - break; - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - options && this.setOptions(options); - - if (!callback) { - return this; - } - - this._findOneAndReplace(callback); - - return this; -}; - -/*! - * Thunk around findOneAndReplace() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ -Query.prototype._findOneAndReplace = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return null; - } - - const filter = this._conditions; - const options = this._optionsForExec(); - let fields = null; - - if (this._fields != null) { - options.projection = this._castFields(utils.clone(this._fields)); - fields = options.projection; - if (fields instanceof Error) { - callback(fields); - return null; - } - } - - this._collection.collection.findOneAndReplace(filter, options, (err, res) => { - if (err) { - return callback(err); - } - - const doc = res.value; - - return this._completeOne(doc, res, callback); - }); -}); - -/*! - * Thunk around findOneAndRemove() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ -Query.prototype._findOneAndRemove = wrapThunk(function(callback) { - if (this.error() != null) { - callback(this.error()); - return; - } - - this._findAndModify('remove', callback); -}); - -/*! - * Get options from query opts, falling back to the base mongoose object. - */ - -function _getOption(query, option, def) { - const opts = query._optionsForExec(query.model); - - if (option in opts) { - return opts[option]; - } - if (option in query.model.base.options) { - return query.model.base.options[option]; - } - return def; -} - -/*! - * Override mquery.prototype._findAndModify to provide casting etc. - * - * @param {String} type - either "remove" or "update" - * @param {Function} callback - * @api private - */ - -Query.prototype._findAndModify = function(type, callback) { - if (typeof callback !== 'function') { - throw new Error('Expected callback in _findAndModify'); - } - - const model = this.model; - const schema = model.schema; - const _this = this; - let castedDoc = this._update; - let fields; - let doValidate; - - const castedQuery = castQuery(this); - if (castedQuery instanceof Error) { - return callback(castedQuery); - } - - _castArrayFilters(this); - - const opts = this._optionsForExec(model); - - if ('strict' in opts) { - this._mongooseOptions.strict = opts.strict; - } - - const isOverwriting = this.options.overwrite && !hasDollarKeys(castedDoc); - if (isOverwriting) { - castedDoc = new this.model(castedDoc, null, true); - } - - if (type === 'remove') { - opts.remove = true; - } else { - if (!('new' in opts)) { - opts.new = false; - } - if (!('upsert' in opts)) { - opts.upsert = false; - } - if (opts.upsert || opts['new']) { - opts.remove = false; - } - - if (isOverwriting) { - doValidate = function(callback) { - castedDoc.validate(callback); - }; - } else { - castedDoc = castDoc(this, opts.overwrite); - castedDoc = setDefaultsOnInsert(this._conditions, schema, castedDoc, opts); - if (!castedDoc) { - if (opts.upsert) { - // still need to do the upsert to empty doc - const doc = utils.clone(castedQuery); - delete doc._id; - castedDoc = {$set: doc}; - } else { - this.findOne(callback); - return this; - } - } else if (castedDoc instanceof Error) { - return callback(castedDoc); - } else { - // In order to make MongoDB 2.6 happy (see - // https://jira.mongodb.org/browse/SERVER-12266 and related issues) - // if we have an actual update document but $set is empty, junk the $set. - if (castedDoc.$set && Object.keys(castedDoc.$set).length === 0) { - delete castedDoc.$set; - } - } - - doValidate = updateValidators(this, schema, castedDoc, opts); - } - } - - this._applyPaths(); - - const options = this._mongooseOptions; - - if (this._fields) { - fields = utils.clone(this._fields); - opts.projection = this._castFields(fields); - if (opts.projection instanceof Error) { - return callback(opts.projection); - } - } - - if (opts.sort) convertSortToArray(opts); - - const cb = function(err, doc, res) { - if (err) { - return callback(err); - } - - _this._completeOne(doc, res, callback); - }; - - let _callback; - - let useFindAndModify = true; - const runValidators = _getOption(this, 'runValidators', false); - const base = _this.model && _this.model.base; - const conn = get(model, 'collection.conn', {}); - if ('useFindAndModify' in base.options) { - useFindAndModify = base.get('useFindAndModify'); - } - if ('useFindAndModify' in conn.config) { - useFindAndModify = conn.config.useFindAndModify; - } - if ('useFindAndModify' in options) { - useFindAndModify = options.useFindAndModify; - } - if (useFindAndModify === false) { - // Bypass mquery - const collection = _this._collection.collection; - if ('new' in opts) { - opts.returnOriginal = !opts['new']; - delete opts['new']; - } - - if (type === 'remove') { - collection.findOneAndDelete(castedQuery, opts, _wrapThunkCallback(_this, function(error, res) { - return cb(error, res ? res.value : res, res); - })); - - return this; - } - - // honors legacy overwrite option for backward compatibility - const updateMethod = isOverwriting ? 'findOneAndReplace' : 'findOneAndUpdate'; - - if (runValidators && doValidate) { - _callback = function(error) { - if (error) { - return callback(error); - } - if (castedDoc && castedDoc.toBSON) { - castedDoc = castedDoc.toBSON(); - } - - collection[updateMethod](castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) { - return cb(error, res ? res.value : res, res); - })); - }; - - try { - doValidate(_callback); - } catch (error) { - callback(error); - } - } else { - if (castedDoc && castedDoc.toBSON) { - castedDoc = castedDoc.toBSON(); - } - collection[updateMethod](castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) { - return cb(error, res ? res.value : res, res); - })); - } - - return this; - } - - if (runValidators && doValidate) { - _callback = function(error) { - if (error) { - return callback(error); - } - if (castedDoc && castedDoc.toBSON) { - castedDoc = castedDoc.toBSON(); - } - _this._collection.findAndModify(castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) { - return cb(error, res ? res.value : res, res); - })); - }; - - try { - doValidate(_callback); - } catch (error) { - callback(error); - } - } else { - if (castedDoc && castedDoc.toBSON) { - castedDoc = castedDoc.toBSON(); - } - this._collection.findAndModify(castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) { - return cb(error, res ? res.value : res, res); - })); - } - - return this; -}; - -/*! - * ignore - */ - -function _completeOneLean(doc, res, opts, callback) { - if (opts.rawResult) { - return callback(null, res); - } - return callback(null, doc); -} - -/*! - * Override mquery.prototype._mergeUpdate to handle mongoose objects in - * updates. - * - * @param {Object} doc - * @api private - */ - -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); - } -}; - -/*! - * The mongodb driver 1.3.23 only supports the nested array sort - * syntax. We must convert it or sorting findAndModify will not work. - */ - -function convertSortToArray(opts) { - if (Array.isArray(opts.sort)) { - return; - } - if (!utils.isObject(opts.sort)) { - return; - } - - const sort = []; - - for (const key in opts.sort) { - if (utils.object.hasOwnProperty(opts.sort, key)) { - sort.push([key, opts.sort[key]]); - } - } - - opts.sort = sort; -} - -/*! - * ignore - */ - -function _updateThunk(op, callback) { - const schema = this.model.schema; - let doValidate; - const _this = this; - - this._castConditions(); - - _castArrayFilters(this); - - if (this.error() != null) { - callback(this.error()); - return null; - } - - callback = _wrapThunkCallback(this, callback); - - const castedQuery = this._conditions; - let castedDoc; - const options = this._optionsForExec(this.model); - - ++this._executionCount; - - this._update = utils.clone(this._update, options); - const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update); - if (isOverwriting) { - castedDoc = new this.model(this._update, null, true); - } else { - castedDoc = castDoc(this, options.overwrite); - - if (castedDoc instanceof Error) { - callback(castedDoc); - return null; - } - - if (castedDoc == null || Object.keys(castedDoc).length === 0) { - callback(null, 0); - return null; - } - - castedDoc = setDefaultsOnInsert(this._conditions, this.model.schema, - castedDoc, options); - } - - const runValidators = _getOption(this, 'runValidators', false); - if (runValidators) { - if (isOverwriting) { - doValidate = function(callback) { - castedDoc.validate(callback); - }; - } else { - doValidate = updateValidators(this, schema, castedDoc, options); - } - const _callback = function(err) { - if (err) { - return callback(err); - } - - if (castedDoc.toBSON) { - castedDoc = castedDoc.toBSON(); - } - _this._collection[op](castedQuery, castedDoc, options, callback); - }; - try { - doValidate(_callback); - } catch (err) { - process.nextTick(function() { - callback(err); - }); - } - return null; - } - - if (castedDoc.toBSON) { - castedDoc = castedDoc.toBSON(); - } - - this._collection[op](castedQuery, castedDoc, options, callback); - return null; -} - -/*! - * Internal thunk for .update() - * - * @param {Function} callback - * @see Model.update #model_Model.update - * @api private - */ -Query.prototype._execUpdate = wrapThunk(function(callback) { - return _updateThunk.call(this, 'update', callback); -}); - -/*! - * Internal thunk for .updateMany() - * - * @param {Function} callback - * @see Model.update #model_Model.update - * @api private - */ -Query.prototype._updateMany = wrapThunk(function(callback) { - return _updateThunk.call(this, 'updateMany', callback); -}); - -/*! - * Internal thunk for .updateOne() - * - * @param {Function} callback - * @see Model.update #model_Model.update - * @api private - */ -Query.prototype._updateOne = wrapThunk(function(callback) { - return _updateThunk.call(this, 'updateOne', callback); -}); - -/*! - * Internal thunk for .replaceOne() - * - * @param {Function} callback - * @see Model.replaceOne #model_Model.replaceOne - * @api private - */ -Query.prototype._replaceOne = wrapThunk(function(callback) { - return _updateThunk.call(this, 'replaceOne', callback); -}); - -/** - * Declare and/or execute this query as an update() operation. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * This function triggers the following middleware. - * - * - `update()` - * - * ####Example - * - * Model.where({ _id: id }).update({ title: 'words' }) - * - * // becomes - * - * Model.where({ _id: id }).update({ $set: { title: 'words' }}) - * - * ####Valid options: - * - * - `upsert` (boolean) whether to create the doc if it doesn't match (false) - * - `multi` (boolean) whether multiple documents should be updated (false) - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `strict` (boolean) overrides the `strict` option for this update - * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false) - * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false. - * - `read` - * - `writeConcern` - * - * ####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, we must first call update() and then execute it by using the `exec()` method. - * - * var q = Model.where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).update(); // not executed - * - * q.update({ $set: { name: 'bob' }}).exec(); // executed - * - * // keys that are not $atomic ops become $set. - * // this executes the same command as the previous example. - * q.update({ name: 'bob' }).exec(); - * - * // overwriting with empty docs - * var q = Model.where({ _id: id }).setOptions({ overwrite: true }) - * q.update({ }, callback); // executes - * - * // multi update with overwrite to empty doc - * var q = Model.where({ _id: id }); - * q.setOptions({ multi: true, overwrite: true }) - * q.update({ }); - * q.update(callback); // executed - * - * // multi updates - * Model.where() - * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) - * - * // more multi updates - * Model.where() - * .setOptions({ multi: true }) - * .update({ $set: { arr: [] }}, callback) - * - * // single update by default - * Model.where({ email: 'address@example.com' }) - * .update({ $inc: { counter: 1 }}, callback) - * - * API summary - * - * update(criteria, doc, options, cb) // executes - * update(criteria, doc, options) - * update(criteria, doc, cb) // executes - * update(criteria, doc) - * update(doc, cb) // executes - * update(doc) - * update(cb) // executes - * update(true) // executes - * update() - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Function} [callback] optional, params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @api public - */ - -Query.prototype.update = function(conditions, doc, options, callback) { - if (typeof options === 'function') { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === 'function') { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === 'function') { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if (typeof conditions === 'object' && !doc && !options && !callback) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } - - return _update(this, 'update', conditions, doc, options, callback); -}; - -/** - * Declare and/or execute this query as an updateMany() operation. Same as - * `update()`, except MongoDB will update _all_ documents that match - * `criteria` (as opposed to just the first one) regardless of the value of - * the `multi` option. - * - * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` - * and `post('updateMany')` instead. - * - * This function triggers the following middleware. - * - * - `updateMany()` - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Function} [callback] optional params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @api public - */ - -Query.prototype.updateMany = function(conditions, doc, options, callback) { - if (typeof options === 'function') { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === 'function') { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === 'function') { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if (typeof conditions === 'object' && !doc && !options && !callback) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } - - return _update(this, 'updateMany', conditions, doc, options, callback); -}; - -/** - * Declare and/or execute this query as an updateOne() operation. Same as - * `update()`, except it does not support the `multi` or `overwrite` options. - * - * - MongoDB will update _only_ the first document that matches `criteria` regardless of the value of the `multi` option. - * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`. - * - * **Note** updateOne will _not_ fire update middleware. Use `pre('updateOne')` - * and `post('updateOne')` instead. - * - * This function triggers the following middleware. - * - * - `updateOne()` - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @api public - */ - -Query.prototype.updateOne = function(conditions, doc, options, callback) { - if (typeof options === 'function') { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === 'function') { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === 'function') { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if (typeof conditions === 'object' && !doc && !options && !callback) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } - - return _update(this, 'updateOne', conditions, doc, options, callback); -}; - -/** - * Declare and/or execute this query as a replaceOne() operation. Same as - * `update()`, except MongoDB will replace the existing document and will - * not accept any atomic operators (`$set`, etc.) - * - * **Note** replaceOne will _not_ fire update middleware. Use `pre('replaceOne')` - * and `post('replaceOne')` instead. - * - * This function triggers the following middleware. - * - * - `replaceOne()` - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] optional params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @api public - */ - -Query.prototype.replaceOne = function(conditions, doc, options, callback) { - if (typeof options === 'function') { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === 'function') { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === 'function') { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if (typeof conditions === 'object' && !doc && !options && !callback) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } - - this.setOptions({ overwrite: true }); - return _update(this, 'replaceOne', conditions, doc, options, callback); -}; - -/*! - * Internal helper for update, updateMany, updateOne, replaceOne - */ - -function _update(query, op, filter, doc, options, callback) { - // make sure we don't send in the whole Document to merge() - query.op = op; - filter = utils.toObject(filter); - doc = doc || {}; - - const oldCb = callback; - if (oldCb) { - if (typeof oldCb === 'function') { - callback = function(error, result) { - oldCb(error, result ? result.result : {ok: 0, n: 0, nModified: 0}); - }; - } else { - throw new Error('Invalid callback() argument.'); - } - } - - // strict is an option used in the update checking, make sure it gets set - if (options) { - if ('strict' in options) { - query._mongooseOptions.strict = options.strict; - } - } - - if (!(filter instanceof Query) && - filter != null && - filter.toString() !== '[object Object]') { - query.error(new ObjectParameterError(filter, 'filter', op)); - } else { - query.merge(filter); - } - - if (utils.isObject(options)) { - query.setOptions(options); - } - - query._mergeUpdate(doc); - - // Hooks - if (callback) { - if (op === 'update') { - query._execUpdate(callback); - return query; - } - query['_' + op](callback); - return query; - } - - return Query.base[op].call(query, filter, doc, options, callback); -} - -/** - * Runs a function `fn` and treats the return value of `fn` as the new value - * for the query to resolve to. - * - * Any functions you pass to `map()` will run **after** any post hooks. - * - * ####Example: - * - * const res = await MyModel.findOne().map(res => { - * // Sets a `loadedAt` property on the doc that tells you the time the - * // document was loaded. - * return res == null ? - * res : - * Object.assign(res, { loadedAt: new Date() }); - * }); - * - * @method map - * @memberOf Query - * @instance - * @param {Function} fn function to run to transform the query result - * @return {Query} this - */ - -Query.prototype.map = function(fn) { - this._transforms.push(fn); - return this; -}; - -/** - * Make this query throw an error if no documents match the given `filter`. - * This is handy for integrating with async/await, because `orFail()` saves you - * an extra `if` statement to check if no document was found. - * - * ####Example: - * - * // Throws if no doc returned - * await Model.findOne({ foo: 'bar' }).orFail(); - * - * // Throws if no document was updated - * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail(); - * - * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }` - * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!')); - * - * // Throws "Not found" error if no document was found - * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }). - * orFail(() => Error('Not found')); - * - * @method orFail - * @memberOf Query - * @instance - * @param {Function|Error} [err] optional error to throw if no docs match `filter`. If not specified, `orFail()` will throw a `DocumentNotFoundError` - * @return {Query} this - */ - -Query.prototype.orFail = function(err) { - this.map(res => { - switch (this.op) { - case 'find': - if (res.length === 0) { - throw _orFailError(err, this); - } - break; - case 'findOne': - if (res == null) { - throw _orFailError(err, this); - } - break; - case 'update': - case 'updateMany': - case 'updateOne': - if (get(res, 'result.nModified') === 0) { - throw _orFailError(err, this); - } - break; - case 'findOneAndDelete': - if (get(res, 'lastErrorObject.n') === 0) { - throw _orFailError(err, this); - } - break; - case 'findOneAndUpdate': - if (get(res, 'lastErrorObject.updatedExisting') === false) { - throw _orFailError(err, this); - } - break; - case 'deleteMany': - case 'deleteOne': - case 'remove': - if (res.n === 0) { - throw _orFailError(err, this); - } - break; - default: - break; - } - - return res; - }); - return this; -}; - -/*! - * Get the error to throw for `orFail()` - */ - -function _orFailError(err, query) { - if (typeof err === 'function') { - err = err.call(query); - } - - if (err == null) { - err = new DocumentNotFoundError(query.getQuery()); - } - - return err; -} - -/** - * Executes the query - * - * ####Examples: - * - * var promise = query.exec(); - * var promise = query.exec('update'); - * - * query.exec(callback); - * query.exec('find', callback); - * - * @param {String|Function} [operation] - * @param {Function} [callback] optional params depend on the function being called - * @return {Promise} - * @api public - */ - -Query.prototype.exec = function exec(op, callback) { - const _this = this; - - if (typeof op === 'function') { - callback = op; - op = null; - } else if (typeof op === 'string') { - this.op = op; - } - - if (callback != null) { - callback = this.model.$wrapCallback(callback); - } - - return utils.promiseOrCallback(callback, (cb) => { - if (!_this.op) { - cb(); - return; - } - - this._hooks.execPre('exec', this, [], (error) => { - if (error) { - return cb(error); - } - this[this.op].call(this, (error, res) => { - if (error) { - return cb(error); - } - - this._hooks.execPost('exec', this, [], {}, (error) => { - if (error) { - return cb(error); - } - - cb(null, res); - }); - }); - }); - }, this.model.events); -}; - -/*! - * ignore - */ - -function _wrapThunkCallback(query, cb) { - return function(error, res) { - if (error != null) { - return cb(error); - } - - for (const fn of query._transforms) { - try { - res = fn(res); - } catch (error) { - return cb(error); - } - } - - return cb(null, res); - }; -} - -/** - * 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) { - return this.exec().then(resolve, reject); -}; - -/** - * Executes the query returning a `Promise` which will be - * resolved with either the doc(s) or rejected with the error. - * Like `.then()`, but only takes a rejection handler. - * - * @param {Function} [reject] - * @return {Promise} - * @api public - */ - -Query.prototype.catch = function(reject) { - return this.exec().then(null, reject); -}; - -/*! - * ignore - */ - -Query.prototype._pre = function(fn) { - this._hooks.pre('exec', fn); - return this; -}; - -/*! - * ignore - */ - -Query.prototype._post = function(fn) { - this._hooks.post('exec', fn); - return this; -}; - -/*! - * Casts obj for an update command. - * - * @param {Object} obj - * @return {Object} obj after casting its values - * @api private - */ - -Query.prototype._castUpdate = function _castUpdate(obj, overwrite) { - let strict; - if ('strict' in this._mongooseOptions) { - strict = this._mongooseOptions.strict; - } else if (this.schema && this.schema.options) { - strict = this.schema.options.strict; - } else { - strict = true; - } - - let omitUndefined = false; - if ('omitUndefined' in this._mongooseOptions) { - omitUndefined = this._mongooseOptions.omitUndefined; - } - - let useNestedStrict; - if ('useNestedStrict' in this.options) { - useNestedStrict = this.options.useNestedStrict; - } - - return castUpdate(this.schema, obj, { - overwrite: overwrite, - strict: strict, - omitUndefined, - useNestedStrict: useNestedStrict - }, this, this._conditions); -}; - -/*! - * castQuery - * @api private - */ - -function castQuery(query) { - try { - return query.cast(query.model); - } catch (err) { - return err; - } -} - -/*! - * castDoc - * @api private - */ - -function castDoc(query, overwrite) { - try { - return query._castUpdate(query._update, overwrite); - } catch (err) { - return err; - } -} - -/** - * Specifies paths which should be populated with other documents. - * - * ####Example: - * - * Kitten.findOne().populate('owner').exec(function (err, kitten) { - * console.log(kitten.owner.name) // Max - * }) - * - * Kitten.find().populate({ - * path: 'owner' - * , select: 'name' - * , match: { color: 'black' } - * , options: { sort: { name: -1 }} - * }).exec(function (err, kittens) { - * console.log(kittens[0].owner.name) // Zoopa - * }) - * - * // alternatively - * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) { - * console.log(kittens[0].owner.name) // Zoopa - * }) - * - * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback. - * - * @param {Object|String} path either the path to populate or an object specifying all parameters - * @param {Object|String} [select] Field selection for the population query - * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field. - * @param {Object} [match] Conditions for the population query - * @param {Object} [options] Options for the population query (sort, etc) - * @see population ./populate.html - * @see Query#select #query_Query-select - * @see Model.populate #model_Model.populate - * @return {Query} this - * @api public - */ - -Query.prototype.populate = function() { - if (arguments.length === 0) { - return this; - } - - const res = utils.populate.apply(null, arguments); - - // Propagate readConcern and readPreference and lean from parent query, - // unless one already specified - if (this.options != null) { - const readConcern = this.options.readConcern; - const readPref = this.options.readPreference; - - for (let i = 0; i < res.length; ++i) { - if (readConcern != null && get(res[i], 'options.readConcern') == null) { - res[i].options = res[i].options || {}; - res[i].options.readConcern = readConcern; - } - if (readPref != null && get(res[i], 'options.readPreference') == null) { - res[i].options = res[i].options || {}; - res[i].options.readPreference = readPref; - } - } - } - - const opts = this._mongooseOptions; - - if (opts.lean != null) { - const lean = opts.lean; - for (let i = 0; i < res.length; ++i) { - if (get(res[i], 'options.lean') == null) { - res[i].options = res[i].options || {}; - res[i].options.lean = lean; - } - } - } - - if (!utils.isObject(opts.populate)) { - opts.populate = {}; - } - - const pop = opts.populate; - - for (let i = 0; i < res.length; ++i) { - const path = res[i].path; - if (pop[path] && pop[path].populate && res[i].populate) { - res[i].populate = pop[path].populate.concat(res[i].populate); - } - pop[res[i].path] = res[i]; - } - - return this; -}; - -/** - * Gets a list of paths to be populated by this query - * - * ####Example: - * bookSchema.pre('findOne', function() { - * let keys = this.getPopulatedPaths(); // ['author'] - * }) - * ... - * Book.findOne({}).populate('author') - * - * @return {Array} an array of strings representing populated paths - * @api public - */ - -Query.prototype.getPopulatedPaths = function getPopulatedPaths() { - const obj = this._mongooseOptions.populate || {}; - return Object.keys(obj); -}; - -/** - * Casts this query to the schema of `model` - * - * ####Note - * - * If `obj` is present, it is cast instead of this query. - * - * @param {Model} [model] the model to cast to. If not set, defaults to `this.model` - * @param {Object} [obj] - * @return {Object} - * @api public - */ - -Query.prototype.cast = function(model, obj) { - obj || (obj = this._conditions); - - model = model || this.model; - - try { - return cast(model.schema, obj, { - upsert: this.options && this.options.upsert, - strict: (this.options && 'strict' in this.options) ? - this.options.strict : - get(model, 'schema.options.strict', null), - strictQuery: (this.options && this.options.strictQuery) || - get(model, 'schema.options.strictQuery', null) - }, this); - } catch (err) { - // CastError, assign model - if (typeof err.setModel === 'function') { - err.setModel(model); - } - throw err; - } -}; - -/** - * Casts selected field arguments for field selection with mongo 2.2 - * - * query.select({ ids: { $elemMatch: { $in: [hexString] }}) - * - * @param {Object} fields - * @see https://github.com/Automattic/mongoose/issues/1091 - * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ - * @api private - */ - -Query.prototype._castFields = function _castFields(fields) { - let selected, - elemMatchKeys, - keys, - key, - out, - i; - - if (fields) { - keys = Object.keys(fields); - elemMatchKeys = []; - i = keys.length; - - // collect $elemMatch args - while (i--) { - key = keys[i]; - if (fields[key].$elemMatch) { - selected || (selected = {}); - selected[key] = fields[key]; - elemMatchKeys.push(key); - } - } - } - - if (selected) { - // they passed $elemMatch, cast em - try { - out = this.cast(this.model, selected); - } catch (err) { - return err; - } - - // apply the casted field args - i = elemMatchKeys.length; - while (i--) { - key = elemMatchKeys[i]; - fields[key] = out[key]; - } - } - - return fields; -}; - -/** - * Applies schematype selected options to this query. - * @api private - */ - -Query.prototype._applyPaths = function applyPaths() { - this._fields = this._fields || {}; - helpers.applyPaths(this._fields, this.model.schema); - - let _selectPopulatedPaths = true; - - if ('selectPopulatedPaths' in this.model.base.options) { - _selectPopulatedPaths = this.model.base.options.selectPopulatedPaths; - } - if ('selectPopulatedPaths' in this.model.schema.options) { - _selectPopulatedPaths = this.model.schema.options.selectPopulatedPaths; - } - - if (_selectPopulatedPaths) { - selectPopulatedFields(this); - } -}; - -/** - * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html). - * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function. - * - * The `.cursor()` function triggers pre find hooks, but **not** post find hooks. - * - * ####Example - * - * // There are 2 ways to use a cursor. First, as a stream: - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * on('data', function(doc) { console.log(doc); }). - * on('end', function() { console.log('Done!'); }); - * - * // Or you can use `.next()` to manually get the next doc in the stream. - * // `.next()` returns a promise, so you can use promises or callbacks. - * var cursor = Thing.find({ name: /^hello/ }).cursor(); - * cursor.next(function(error, doc) { - * console.log(doc); - * }); - * - * // Because `.next()` returns a promise, you can use co - * // to easily iterate through all documents without loading them - * // all into memory. - * co(function*() { - * const cursor = Thing.find({ name: /^hello/ }).cursor(); - * for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) { - * console.log(doc); - * } - * }); - * - * ####Valid options - * - * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`. - * - * @return {QueryCursor} - * @param {Object} [options] - * @see QueryCursor - * @api public - */ - -Query.prototype.cursor = function cursor(opts) { - this._applyPaths(); - this._fields = this._castFields(this._fields); - this.setOptions({ projection: this._fieldsForExec() }); - if (opts) { - this.setOptions(opts); - } - - try { - this.cast(this.model); - } catch (err) { - return (new QueryCursor(this, this.options))._markError(err); - } - - return new QueryCursor(this, this.options); -}; - -// the rest of these are basically to support older Mongoose syntax with mquery - -/** - * _DEPRECATED_ Alias of `maxScan` - * - * @deprecated - * @see maxScan #query_Query-maxScan - * @method maxscan - * @memberOf Query - * @instance - */ - -Query.prototype.maxscan = Query.base.maxScan; - -/** - * Sets the tailable option (for use with capped collections). - * - * ####Example - * - * query.tailable() // true - * query.tailable(true) - * query.tailable(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Boolean} bool defaults to true - * @param {Object} [opts] options to set - * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up - * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying - * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/ - * @api public - */ - -Query.prototype.tailable = function(val, opts) { - // we need to support the tailable({ awaitdata : true }) as well as the - // tailable(true, {awaitdata :true}) syntax that mquery does not support - if (val && val.constructor.name === 'Object') { - opts = val; - val = true; - } - - if (val === undefined) { - val = true; - } - - if (opts && typeof opts === 'object') { - for (const key in opts) { - if (key === 'awaitdata') { - // For backwards compatibility - this.options[key] = !!opts[key]; - } else { - this.options[key] = opts[key]; - } - } - } - - return Query.base.tailable.call(this, val); -}; - -/** - * 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]] - * }) - * - * ####NOTE: - * - * **MUST** be used after `where()`. - * - * ####NOTE: - * - * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). - * - * @method intersects - * @memberOf Query - * @instance - * @param {Object} [arg] - * @return {Query} this - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/ - * @api public - */ - -/** - * 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 }) - * - * The argument is assigned to the most recent path passed to `where()`. - * - * ####NOTE: - * - * `geometry()` **must** come after either `intersects()` or `within()`. - * - * The `object` argument must contain `type` and `coordinates` properties. - * - type {String} - * - coordinates {Array} - * - * @method geometry - * @memberOf Query - * @instance - * @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 $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @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 - * @api public - */ - -/** - * 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 }); - * - * @method near - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see $near http://docs.mongodb.org/manual/reference/operator/near/ - * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/*! - * Overwriting mquery is needed to support a couple different near() forms found in older - * versions of mongoose - * near([1,1]) - * near(1,1) - * near(field, [1,2]) - * near(field, 1, 2) - * In addition to all of the normal forms supported by mquery - */ - -Query.prototype.near = function() { - const params = []; - const sphere = this._mongooseOptions.nearSphere; - - // TODO refactor - - if (arguments.length === 1) { - if (Array.isArray(arguments[0])) { - params.push({center: arguments[0], spherical: sphere}); - } else if (typeof arguments[0] === 'string') { - // just passing a path - params.push(arguments[0]); - } else if (utils.isObject(arguments[0])) { - if (typeof arguments[0].spherical !== 'boolean') { - arguments[0].spherical = sphere; - } - params.push(arguments[0]); - } else { - throw new TypeError('invalid argument'); - } - } else if (arguments.length === 2) { - if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') { - params.push({center: [arguments[0], arguments[1]], spherical: sphere}); - } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) { - params.push(arguments[0]); - params.push({center: arguments[1], spherical: sphere}); - } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) { - params.push(arguments[0]); - if (typeof arguments[1].spherical !== 'boolean') { - arguments[1].spherical = sphere; - } - params.push(arguments[1]); - } else { - throw new TypeError('invalid argument'); - } - } else if (arguments.length === 3) { - if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number' - && typeof arguments[2] === 'number') { - params.push(arguments[0]); - params.push({center: [arguments[1], arguments[2]], spherical: sphere}); - } else { - throw new TypeError('invalid argument'); - } - } else { - throw new TypeError('invalid argument'); - } - - return Query.base.near.apply(this, params); -}; - -/** - * _DEPRECATED_ Specifies a `$nearSphere` condition - * - * ####Example - * - * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); - * - * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10], spherical: true }); - * - * @deprecated - * @see near() #query_Query-near - * @see $near http://docs.mongodb.org/manual/reference/operator/near/ - * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - */ - -Query.prototype.nearSphere = function() { - this._mongooseOptions.nearSphere = true; - this.near.apply(this, arguments); - return this; -}; - -/** - * Returns an asyncIterator for use with [`for/await/of` loops](http://bit.ly/async-iterators) - * This function *only* works for `find()` queries. - * You do not need to call this function explicitly, the JavaScript runtime - * will call it for you. - * - * ####Example - * - * for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) { - * console.log(doc.name); - * } - * - * Node.js 10.x supports async iterators natively without any flags. You can - * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). - * - * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If - * `Symbol.asyncIterator` is undefined, that means your Node.js version does not - * support async iterators. - * - * @method Symbol.asyncIterator - * @memberOf Query - * @instance - * @api public - */ - -if (Symbol.asyncIterator != null) { - Query.prototype[Symbol.asyncIterator] = function() { - return this.cursor().transformNull().map(doc => { - return doc == null ? { done: true } : { value: doc, done: false }; - }); - }; -} - -/** - * 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]) - * - * @method polygon - * @memberOf Query - * @instance - * @param {String|Array} [path] - * @param {Array|Object} [coordinatePairs...] - * @return {Query} this - * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * 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({ ll : lowerLeft, ur : upperRight }) - * - * @method box - * @memberOf Query - * @instance - * @see $box http://docs.mongodb.org/manual/reference/operator/box/ - * @see within() Query#within #query_Query-within - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @param {Object} val - * @param [Array] Upper Right Coords - * @return {Query} this - * @api public - */ - -/*! - * this is needed to support the mongoose syntax of: - * box(field, { ll : [x,y], ur : [x2,y2] }) - * box({ ll : [x,y], ur : [x2,y2] }) - */ - -Query.prototype.box = function(ll, ur) { - if (!Array.isArray(ll) && utils.isObject(ll)) { - ur = ll.ur; - ll = ll.ll; - } - return Query.base.box.call(this, ll, ur); -}; - -/** - * Specifies a $center or $centerSphere condition. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10, unique: true } - * query.where('loc').within().circle(area) - * // alternatively - * query.circle('loc', area); - * - * // spherical calculations - * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } - * query.where('loc').within().circle(area) - * // alternatively - * query.circle('loc', area); - * - * @method circle - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Object} area - * @return {Query} this - * @see $center http://docs.mongodb.org/manual/reference/operator/center/ - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * _DEPRECATED_ Alias for [circle](#query_Query-circle) - * - * **Deprecated.** Use [circle](#query_Query-circle) instead. - * - * @deprecated - * @method center - * @memberOf Query - * @instance - * @api public - */ - -Query.prototype.center = Query.base.circle; - -/** - * _DEPRECATED_ Specifies a $centerSphere condition - * - * **Deprecated.** Use [circle](#query_Query-circle) instead. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10 }; - * query.where('loc').within().centerSphere(area); - * - * @deprecated - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @api public - */ - -Query.prototype.centerSphere = function() { - if (arguments[0] && arguments[0].constructor.name === 'Object') { - arguments[0].spherical = true; - } - - if (arguments[1] && arguments[1].constructor.name === 'Object') { - arguments[1].spherical = true; - } - - Query.base.circle.apply(this, arguments); -}; - -/** - * Determines if field selection has been made. - * - * @method selected - * @memberOf Query - * @instance - * @return {Boolean} - * @api public - */ - -/** - * Determines if inclusive field selection has been made. - * - * query.selectedInclusively() // false - * query.select('name') - * query.selectedInclusively() // true - * - * @method selectedInclusively - * @memberOf Query - * @instance - * @return {Boolean} - * @api public - */ - -Query.prototype.selectedInclusively = function selectedInclusively() { - return isInclusive(this._fields); -}; - -/** - * Determines if exclusive field selection has been made. - * - * query.selectedExclusively() // false - * query.select('-name') - * query.selectedExclusively() // true - * query.selectedInclusively() // false - * - * @method selectedExclusively - * @memberOf Query - * @instance - * @return {Boolean} - * @api public - */ - -Query.prototype.selectedExclusively = function selectedExclusively() { - if (!this._fields) { - return false; - } - - const keys = Object.keys(this._fields); - if (keys.length === 0) { - return false; - } - - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (key === '_id') { - continue; - } - if (this._fields[key] === 0 || this._fields[key] === false) { - return true; - } - } - - return false; -}; - -/*! - * Export - */ - -module.exports = Query; diff --git a/node_modules/mongoose/lib/queryhelpers.js b/node_modules/mongoose/lib/queryhelpers.js deleted file mode 100644 index d130a51c44eab74d7736f07f9fd95c70a3bc1b75..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/queryhelpers.js +++ /dev/null @@ -1,307 +0,0 @@ -'use strict'; - -/*! - * Module dependencies - */ - -const get = require('./helpers/get'); -const isDefiningProjection = require('./helpers/projection/isDefiningProjection'); -const utils = require('./utils'); - -/*! - * Prepare a set of path options for query population. - * - * @param {Query} query - * @param {Object} options - * @return {Array} - */ - -exports.preparePopulationOptions = function preparePopulationOptions(query, options) { - const pop = utils.object.vals(query.options.populate); - - // lean options should trickle through all queries - if (options.lean != null) { - pop. - filter(p => get(p, 'options.lean') == null). - forEach(makeLean(options.lean)); - } - - return pop; -}; - -/*! - * Prepare a set of path options for query population. This is the MongooseQuery - * version - * - * @param {Query} query - * @param {Object} options - * @return {Array} - */ - -exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) { - const pop = utils.object.vals(query._mongooseOptions.populate); - - // lean options should trickle through all queries - if (options.lean != null) { - pop. - filter(p => get(p, 'options.lean') == null). - forEach(makeLean(options.lean)); - } - - const session = get(query, 'options.session', null); - if (session != null) { - pop.forEach(path => { - if (path.options == null) { - path.options = { session: session }; - return; - } - if (!('session' in path.options)) { - path.options.session = session; - } - }); - } - - const projection = query._fieldsForExec(); - pop.forEach(p => { - p._queryProjection = projection; - }); - - return pop; -}; - - -/*! - * returns discriminator by discriminatorMapping.value - * - * @param {Model} model - * @param {string} value - */ -function getDiscriminatorByValue(model, value) { - let discriminator = null; - if (!model.discriminators) { - return discriminator; - } - for (const name in model.discriminators) { - const it = model.discriminators[name]; - if ( - it.schema && - it.schema.discriminatorMapping && - it.schema.discriminatorMapping.value == value - ) { - discriminator = it; - break; - } - } - return discriminator; -} - -exports.getDiscriminatorByValue = getDiscriminatorByValue; - -/*! - * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise, - * it returns an instance of the given model. - * - * @param {Model} model - * @param {Object} doc - * @param {Object} fields - * - * @return {Model} - */ -exports.createModel = function createModel(model, doc, fields, userProvidedFields) { - model.hooks.execPreSync('createModel', doc); - const discriminatorMapping = model.schema ? - model.schema.discriminatorMapping : - null; - - const key = discriminatorMapping && discriminatorMapping.isRoot ? - discriminatorMapping.key : - null; - - const value = doc[key]; - if (key && value && model.discriminators) { - const discriminator = model.discriminators[value] || getDiscriminatorByValue(model, value); - if (discriminator) { - const _fields = utils.clone(userProvidedFields); - exports.applyPaths(_fields, discriminator.schema); - return new discriminator(undefined, _fields, true); - } - } - - return new model(undefined, fields, { - skipId: true, - isNew: false, - willInit: true - }); -}; - -/*! - * ignore - */ - -exports.applyPaths = function applyPaths(fields, schema) { - // determine if query is selecting or excluding fields - let exclude; - let keys; - let ki; - let field; - - if (fields) { - keys = Object.keys(fields); - ki = keys.length; - - while (ki--) { - if (keys[ki][0] === '+') { - continue; - } - field = fields[keys[ki]]; - // Skip `$meta` and `$slice` - if (!isDefiningProjection(field)) { - continue; - } - exclude = field === 0; - break; - } - } - - // if selecting, apply default schematype select:true fields - // if excluding, apply schematype select:false fields - - const selected = []; - const excluded = []; - const stack = []; - - const analyzePath = function(path, type) { - const plusPath = '+' + path; - const hasPlusPath = fields && plusPath in fields; - if (hasPlusPath) { - // forced inclusion - delete fields[plusPath]; - } - - if (typeof type.selected !== 'boolean') return; - - if (hasPlusPath) { - // forced inclusion - delete fields[plusPath]; - - // if there are other fields being included, add this one - // if no other included fields, leave this out (implied inclusion) - if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) { - fields[path] = 1; - } - - return; - } - - // check for parent exclusions - const pieces = path.split('.'); - const root = pieces[0]; - if (~excluded.indexOf(root)) { - return; - } - - // Special case: if user has included a parent path of a discriminator key, - // don't explicitly project in the discriminator key because that will - // project out everything else under the parent path - if (!exclude && get(type, 'options.$skipDiscriminatorCheck', false)) { - let cur = ''; - for (let i = 0; i < pieces.length; ++i) { - cur += (cur.length === 0 ? '' : '.') + pieces[i]; - const projection = get(fields, cur, false); - if (projection && typeof projection !== 'object') { - return; - } - } - } - - (type.selected ? selected : excluded).push(path); - }; - - analyzeSchema(schema); - - switch (exclude) { - case true: - for (let i = 0; i < excluded.length; ++i) { - fields[excluded[i]] = 0; - } - break; - case false: - if (schema && - schema.paths['_id'] && - schema.paths['_id'].options && - schema.paths['_id'].options.select === false) { - fields._id = 0; - } - for (let i = 0; i < selected.length; ++i) { - fields[selected[i]] = 1; - } - break; - case undefined: - if (fields == null) { - break; - } - // Any leftover plus paths must in the schema, so delete them (gh-7017) - for (const key of Object.keys(fields || {})) { - if (key.charAt(0) === '+') { - delete fields[key]; - } - } - - // user didn't specify fields, implies returning all fields. - // only need to apply excluded fields and delete any plus paths - for (let i = 0; i < excluded.length; ++i) { - fields[excluded[i]] = 0; - } - break; - } - - function analyzeSchema(schema, prefix) { - prefix || (prefix = ''); - - // avoid recursion - if (stack.indexOf(schema) !== -1) { - return; - } - stack.push(schema); - - schema.eachPath(function(path, type) { - if (prefix) path = prefix + '.' + path; - - analyzePath(path, type); - - // array of subdocs? - if (type.schema) { - analyzeSchema(type.schema, path); - } - }); - - stack.pop(); - } -}; - -/*! - * Set each path query option to lean - * - * @param {Object} option - */ - -function makeLean(val) { - return function(option) { - option.options || (option.options = {}); - option.options.lean = val; - }; -} - -/*! - * Handle the `WriteOpResult` from the server - */ - -exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback) { - return function _handleDeleteWriteOpResult(error, res) { - if (error) { - return callback(error); - } - return callback(null, - Object.assign({}, res.result, {deletedCount: res.deletedCount })); - }; -}; diff --git a/node_modules/mongoose/lib/schema.js b/node_modules/mongoose/lib/schema.js deleted file mode 100644 index 9d3bdb306be7ca0c84ddbe69e001df125558dab3..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema.js +++ /dev/null @@ -1,1813 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const EventEmitter = require('events').EventEmitter; -const Kareem = require('kareem'); -const SchemaType = require('./schematype'); -const VirtualType = require('./virtualtype'); -const applyTimestampsToChildren = require('./helpers/update/applyTimestampsToChildren'); -const applyTimestampsToUpdate = require('./helpers/update/applyTimestampsToUpdate'); -const get = require('./helpers/get'); -const getIndexes = require('./helpers/schema/getIndexes'); -const handleTimestampOption = require('./helpers/schema/handleTimestampOption'); -const merge = require('./helpers/schema/merge'); -const mpath = require('mpath'); -const readPref = require('./driver').get().ReadPreference; -const symbols = require('./schema/symbols'); -const util = require('util'); -const utils = require('./utils'); -const validateRef = require('./helpers/populate/validateRef'); - -let MongooseTypes; - -const queryHooks = require('./helpers/query/applyQueryMiddleware'). - middlewareFunctions; -const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions; -const hookNames = queryHooks.concat(documentHooks). - reduce((s, hook) => s.add(hook), new Set()); - -let id = 0; - -/** - * Schema constructor. - * - * ####Example: - * - * var child = new Schema({ name: String }); - * var schema = new Schema({ name: String, age: Number, children: [child] }); - * var Tree = mongoose.model('Tree', schema); - * - * // setting schema options - * new Schema({ name: String }, { _id: false, autoIndex: false }) - * - * ####Options: - * - * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option) - * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option) - * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true - * - [capped](/docs/guide.html#capped): bool - defaults to false - * - [collection](/docs/guide.html#collection): string - no default - * - [id](/docs/guide.html#id): bool - defaults to true - * - [_id](/docs/guide.html#_id): bool - defaults to true - * - `minimize`: bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true - * - [read](/docs/guide.html#read): string - * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/) - * - [shardKey](/docs/guide.html#shardKey): bool - defaults to `null` - * - [strict](/docs/guide.html#strict): bool - defaults to true - * - [toJSON](/docs/guide.html#toJSON) - object - no default - * - [toObject](/docs/guide.html#toObject) - object - no default - * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type' - * - [useNestedStrict](/docs/guide.html#useNestedStrict) - boolean - defaults to false - * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` - * - [versionKey](/docs/guide.html#versionKey): string - defaults to "__v" - * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation) - * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true` - * - * ####Note: - * - * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ - * - * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas - * @param {Object} [options] - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted after the schema is compiled into a `Model`. - * @api public - */ - -function Schema(obj, options) { - if (!(this instanceof Schema)) { - return new Schema(obj, options); - } - - this.obj = obj; - this.paths = {}; - this.aliases = {}; - this.subpaths = {}; - this.virtuals = {}; - this.singleNestedPaths = {}; - this.nested = {}; - this.inherits = {}; - this.callQueue = []; - this._indexes = []; - this.methods = {}; - this.methodOptions = {}; - this.statics = {}; - this.tree = {}; - this.query = {}; - this.childSchemas = []; - this.plugins = []; - // For internal debugging. Do not use this to try to save a schema in MDB. - this.$id = ++id; - - this.s = { - hooks: new Kareem() - }; - - this.options = this.defaultOptions(options); - - // build paths - if (Array.isArray(obj)) { - for (const definition of obj) { - this.add(definition); - } - } else if (obj) { - this.add(obj); - } - - // check if _id's value is a subdocument (gh-2276) - const _idSubDoc = obj && obj._id && utils.isObject(obj._id); - - // ensure the documents get an auto _id unless disabled - const auto_id = !this.paths['_id'] && - (!this.options.noId && this.options._id) && !_idSubDoc; - - if (auto_id) { - const _obj = {_id: {auto: true}}; - _obj._id[this.options.typeKey] = Schema.ObjectId; - this.add(_obj); - } - - this.setupTimestamp(this.options.timestamps); -} - -/*! - * Create virtual properties with alias field - */ -function aliasFields(schema, paths) { - paths = paths || Object.keys(schema.paths); - for (const path of paths) { - const options = get(schema.paths[path], 'options'); - if (options == null) { - continue; - } - - const prop = schema.paths[path].path; - const alias = options.alias; - - if (!alias) { - continue; - } - - if (typeof alias !== 'string') { - throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias); - } - - schema.aliases[alias] = prop; - - schema. - virtual(alias). - get((function(p) { - return function() { - if (typeof this.get === 'function') { - return this.get(p); - } - return this[p]; - }; - })(prop)). - set((function(p) { - return function(v) { - return this.set(p, v); - }; - })(prop)); - } -} - -/*! - * Inherit from EventEmitter. - */ -Schema.prototype = Object.create(EventEmitter.prototype); -Schema.prototype.constructor = Schema; -Schema.prototype.instanceOfSchema = true; - -/*! - * ignore - */ - -Object.defineProperty(Schema.prototype, '$schemaType', { - configurable: false, - enumerable: false, - writable: true -}); - -/** - * Array of child schemas (from document arrays and single nested subdocs) - * and their corresponding compiled models. Each element of the array is - * an object with 2 properties: `schema` and `model`. - * - * This property is typically only useful for plugin authors and advanced users. - * You do not need to interact with this property at all to use mongoose. - * - * @api public - * @property childSchemas - * @memberOf Schema - * @instance - */ - -Object.defineProperty(Schema.prototype, 'childSchemas', { - configurable: false, - enumerable: true, - writable: true -}); - -/** - * The original object passed to the schema constructor - * - * ####Example: - * - * var schema = new Schema({ a: String }).add({ b: String }); - * schema.obj; // { a: String } - * - * @api public - * @property obj - * @memberOf Schema - * @instance - */ - -Schema.prototype.obj; - -/** - * Schema as flat paths - * - * ####Example: - * { - * '_id' : SchemaType, - * , 'nested.key' : SchemaType, - * } - * - * @api private - * @property paths - * @memberOf Schema - * @instance - */ - -Schema.prototype.paths; - -/** - * Schema as a tree - * - * ####Example: - * { - * '_id' : ObjectId - * , 'nested' : { - * 'key' : String - * } - * } - * - * @api private - * @property tree - * @memberOf Schema - * @instance - */ - -Schema.prototype.tree; - -/** - * Returns a deep copy of the schema - * - * @return {Schema} the cloned schema - * @api public - * @memberOf Schema - * @instance - */ - -Schema.prototype.clone = function() { - const s = new Schema({}, this._userProvidedOptions); - s.base = this.base; - s.obj = this.obj; - s.options = utils.clone(this.options); - s.callQueue = this.callQueue.map(function(f) { return f; }); - s.methods = utils.clone(this.methods); - s.methodOptions = utils.clone(this.methodOptions); - s.statics = utils.clone(this.statics); - s.query = utils.clone(this.query); - s.plugins = Array.prototype.slice.call(this.plugins); - s._indexes = utils.clone(this._indexes); - s.s.hooks = this.s.hooks.clone(); - s._originalSchema = this._originalSchema == null ? - this._originalSchema : - this._originalSchema.clone(); - - s.tree = utils.clone(this.tree); - s.paths = utils.clone(this.paths); - s.nested = utils.clone(this.nested); - s.subpaths = utils.clone(this.subpaths); - s.childSchemas = this.childSchemas.slice(); - s.singleNestedPaths = utils.clone(this.singleNestedPaths); - - s.virtuals = utils.clone(this.virtuals); - s.$globalPluginsApplied = this.$globalPluginsApplied; - s.$isRootDiscriminator = this.$isRootDiscriminator; - - if (this.discriminatorMapping != null) { - s.discriminatorMapping = Object.assign({}, this.discriminatorMapping); - } - if (s.discriminators != null) { - s.discriminators = Object.assign({}, this.discriminators); - } - - s.aliases = Object.assign({}, this.aliases); - - // Bubble up `init` for backwards compat - s.on('init', v => this.emit('init', v)); - - return s; -}; - -/** - * Returns default options for this schema, merged with `options`. - * - * @param {Object} options - * @return {Object} - * @api private - */ - -Schema.prototype.defaultOptions = function(options) { - if (options && options.safe === false) { - options.safe = {w: 0}; - } - - if (options && options.safe && options.safe.w === 0) { - // if you turn off safe writes, then versioning goes off as well - options.versionKey = false; - } - - this._userProvidedOptions = options == null ? {} : utils.clone(options); - - const baseOptions = get(this, 'base.options', {}); - options = utils.options({ - strict: 'strict' in baseOptions ? baseOptions.strict : true, - bufferCommands: true, - capped: false, // { size, max, autoIndexId } - versionKey: '__v', - discriminatorKey: '__t', - minimize: true, - autoIndex: null, - shardKey: null, - read: null, - validateBeforeSave: true, - // the following are only applied at construction time - noId: false, // deprecated, use { _id: false } - _id: true, - noVirtualId: false, // deprecated, use { id: false } - id: true, - typeKey: 'type' - }, utils.clone(options)); - - if (options.read) { - options.read = readPref(options.read); - } - - return options; -}; - -/** - * Adds key path / schema type pairs to this schema. - * - * ####Example: - * - * const ToySchema = new Schema(); - * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); - * - * const TurboManSchema = new Schema(); - * // You can also `add()` another schema and copy over all paths, virtuals, - * // getters, setters, indexes, methods, and statics. - * TurboManSchema.add(ToySchema).add({ year: Number }); - * - * @param {Object|Schema} obj plain object with paths to add, or another schema - * @param {String} [prefix] path to prefix the newly added paths with - * @return {Schema} the Schema instance - * @api public - */ - -Schema.prototype.add = function add(obj, prefix) { - if (obj instanceof Schema) { - merge(this, obj); - return; - } - - if (obj._id === false) { - delete obj._id; - this.options._id = false; - } - - prefix = prefix || ''; - const keys = Object.keys(obj); - - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - - if (obj[key] == null) { - throw new TypeError('Invalid value for schema path `' + prefix + key + '`'); - } - - if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) { - throw new TypeError('Invalid value for schema Array path `' + prefix + key + '`'); - } - - if (utils.isPOJO(obj[key]) && - (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type))) { - if (Object.keys(obj[key]).length) { - // nested object { last: { name: String }} - this.nested[prefix + key] = true; - this.add(obj[key], prefix + key + '.'); - } else { - if (prefix) { - this.nested[prefix.substr(0, prefix.length - 1)] = true; - } - this.path(prefix + key, obj[key]); // mixed type - } - } else { - if (prefix) { - this.nested[prefix.substr(0, prefix.length - 1)] = true; - } - this.path(prefix + key, obj[key]); - } - } - - const addedKeys = Object.keys(obj). - map(key => prefix ? prefix + key : key); - aliasFields(this, addedKeys); - return this; -}; - -/** - * Reserved document keys. - * - * Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error. - * - * on, emit, _events, db, get, set, init, isNew, errors, schema, options, modelName, collection, _pres, _posts, toObject - * - * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. - * - * var schema = new Schema(..); - * schema.methods.init = function () {} // potentially breaking - */ - -Schema.reserved = Object.create(null); -Schema.prototype.reserved = Schema.reserved; -const reserved = Schema.reserved; -// Core object -reserved['prototype'] = -// EventEmitter -reserved.emit = -reserved.on = -reserved.once = -reserved.listeners = -reserved.removeListener = -// document properties and functions -reserved.collection = -reserved.db = -reserved.errors = -reserved.init = -reserved.isModified = -reserved.isNew = -reserved.get = -reserved.modelName = -reserved.save = -reserved.schema = -reserved.toObject = -reserved.validate = -reserved.remove = -reserved.populated = -// hooks.js -reserved._pres = reserved._posts = 1; - -/*! - * Document keys to print warnings for - */ - -const warnings = {}; -warnings.increment = '`increment` should not be used as a schema path name ' + - 'unless you have disabled versioning.'; - -/** - * Gets/sets schema paths. - * - * Sets a path (if arity 2) - * Gets a path (if arity 1) - * - * ####Example - * - * schema.path('name') // returns a SchemaType - * schema.path('name', Number) // changes the schemaType of `name` to Number - * - * @param {String} path - * @param {Object} constructor - * @api public - */ - -Schema.prototype.path = function(path, obj) { - if (obj === undefined) { - if (this.paths.hasOwnProperty(path)) { - return this.paths[path]; - } - if (this.subpaths.hasOwnProperty(path)) { - return this.subpaths[path]; - } - if (this.singleNestedPaths.hasOwnProperty(path)) { - return this.singleNestedPaths[path]; - } - - // Look for maps - for (const _path of Object.keys(this.paths)) { - if (!_path.includes('.$*')) { - continue; - } - const re = new RegExp('^' + _path.replace(/\.\$\*/g, '.[^.]+') + '$'); - if (re.test(path)) { - return this.paths[_path]; - } - } - - // subpaths? - return /\.\d+\.?.*$/.test(path) - ? getPositionalPath(this, path) - : undefined; - } - - // some path names conflict with document methods - if (reserved[path]) { - throw new Error('`' + path + '` may not be used as a schema pathname'); - } - - if (warnings[path]) { - console.log('WARN: ' + warnings[path]); - } - - if (typeof obj === 'object' && 'ref' in obj) { - validateRef(obj.ref, path); - } - - // update the tree - const subpaths = path.split(/\./); - const last = subpaths.pop(); - let branch = this.tree; - - subpaths.forEach(function(sub, i) { - if (!branch[sub]) { - branch[sub] = {}; - } - if (typeof branch[sub] !== 'object') { - const msg = 'Cannot set nested path `' + path + '`. ' - + 'Parent path `' - + subpaths.slice(0, i).concat([sub]).join('.') - + '` already set to type ' + branch[sub].name - + '.'; - throw new Error(msg); - } - branch = branch[sub]; - }); - - branch[last] = utils.clone(obj); - - this.paths[path] = this.interpretAsType(path, obj, this.options); - const schemaType = this.paths[path]; - - if (schemaType.$isSchemaMap) { - // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key" - // The '$' is to imply this path should never be stored in MongoDB so we - // can easily build a regexp out of this path, and '*' to imply "any key." - const mapPath = path + '.$*'; - this.paths[path + '.$*'] = this.interpretAsType(mapPath, - obj.of || { type: {} }, this.options); - schemaType.$__schemaType = this.paths[path + '.$*']; - } - - if (schemaType.$isSingleNested) { - for (const key in schemaType.schema.paths) { - this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key]; - } - for (const key in schemaType.schema.singleNestedPaths) { - this.singleNestedPaths[path + '.' + key] = - schemaType.schema.singleNestedPaths[key]; - } - - Object.defineProperty(schemaType.schema, 'base', { - configurable: true, - enumerable: false, - writable: false, - value: this.base - }); - - schemaType.caster.base = this.base; - this.childSchemas.push({ - schema: schemaType.schema, - model: schemaType.caster - }); - } else if (schemaType.$isMongooseDocumentArray) { - Object.defineProperty(schemaType.schema, 'base', { - configurable: true, - enumerable: false, - writable: false, - value: this.base - }); - - schemaType.casterConstructor.base = this.base; - this.childSchemas.push({ - schema: schemaType.schema, - model: schemaType.casterConstructor - }); - } - - return this; -}; - -/** - * The Mongoose instance this schema is associated with - * - * @property base - * @api private - */ - -Object.defineProperty(Schema.prototype, 'base', { - configurable: true, - enumerable: false, - writable: true, - value: null -}); - -/** - * Converts type arguments into Mongoose Types. - * - * @param {String} path - * @param {Object} obj constructor - * @api private - */ - -Schema.prototype.interpretAsType = function(path, obj, options) { - if (obj instanceof SchemaType) { - return obj; - } - - // If this schema has an associated Mongoose object, use the Mongoose object's - // copy of SchemaTypes re: gh-7158 gh-6933 - const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types; - - if (obj.constructor) { - const constructorName = utils.getFunctionName(obj.constructor); - if (constructorName !== 'Object') { - const oldObj = obj; - obj = {}; - obj[options.typeKey] = oldObj; - } - } - - // Get the type making sure to allow keys named "type" - // and default to mixed if not specified. - // { type: { type: String, default: 'freshcut' } } - let type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type) - ? obj[options.typeKey] - : {}; - let name; - - if (utils.isPOJO(type) || type === 'mixed') { - return new MongooseTypes.Mixed(path, obj); - } - - if (Array.isArray(type) || Array === type || type === 'array') { - // if it was specified through { type } look for `cast` - let cast = (Array === type || type === 'array') - ? obj.cast - : type[0]; - - if (cast && cast.instanceOfSchema) { - return new MongooseTypes.DocumentArray(path, cast, obj); - } - if (cast && - cast[options.typeKey] && - cast[options.typeKey].instanceOfSchema) { - return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast); - } - - if (Array.isArray(cast)) { - return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj); - } - - if (typeof cast === 'string') { - cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; - } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type)) - && utils.isPOJO(cast)) { - if (Object.keys(cast).length) { - // The `minimize` and `typeKey` options propagate to child schemas - // declared inline, like `{ arr: [{ val: { $type: String } }] }`. - // See gh-3560 - const childSchemaOptions = {minimize: options.minimize}; - if (options.typeKey) { - childSchemaOptions.typeKey = options.typeKey; - } - //propagate 'strict' option to child schema - if (options.hasOwnProperty('strict')) { - childSchemaOptions.strict = options.strict; - } - const childSchema = new Schema(cast, childSchemaOptions); - childSchema.$implicitlyCreated = true; - return new MongooseTypes.DocumentArray(path, childSchema, obj); - } else { - // Special case: empty object becomes mixed - return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj); - } - } - - if (cast) { - type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type) - ? cast[options.typeKey] - : cast; - - name = typeof type === 'string' - ? type - : type.schemaName || utils.getFunctionName(type); - - if (!(name in MongooseTypes)) { - throw new TypeError('Invalid schema configuration: ' + - `\`${name}\` is not a valid type within the array \`${path}\`.` + - 'See http://bit.ly/mongoose-schematypes for a list of valid schema types.'); - } - } - - return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options); - } - - if (type && type.instanceOfSchema) { - return new MongooseTypes.Embedded(type, path, obj); - } - - if (Buffer.isBuffer(type)) { - name = 'Buffer'; - } else if (typeof type === 'function' || typeof type === 'object') { - name = type.schemaName || utils.getFunctionName(type); - } else { - name = type == null ? '' + type : type.toString(); - } - - if (name) { - name = name.charAt(0).toUpperCase() + name.substring(1); - } - // Special case re: gh-7049 because the bson `ObjectID` class' capitalization - // doesn't line up with Mongoose's. - if (name === 'ObjectID') { - name = 'ObjectId'; - } - - if (MongooseTypes[name] == null) { - throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` + - `a valid type at path \`${path}\`. See ` + - 'http://bit.ly/mongoose-schematypes for a list of valid schema types.'); - } - - return new MongooseTypes[name](path, obj); -}; - -/** - * Iterates the schemas paths similar to Array#forEach. - * - * The callback is passed the pathname and schemaType as arguments on each iteration. - * - * @param {Function} fn callback function - * @return {Schema} this - * @api public - */ - -Schema.prototype.eachPath = function(fn) { - const keys = Object.keys(this.paths); - const len = keys.length; - - for (let i = 0; i < len; ++i) { - fn(keys[i], this.paths[keys[i]]); - } - - return this; -}; - -/** - * Returns an Array of path strings that are required by this schema. - * - * @api public - * @param {Boolean} invalidate refresh the cache - * @return {Array} - */ - -Schema.prototype.requiredPaths = function requiredPaths(invalidate) { - if (this._requiredpaths && !invalidate) { - return this._requiredpaths; - } - - const paths = Object.keys(this.paths); - let i = paths.length; - const ret = []; - - while (i--) { - const path = paths[i]; - if (this.paths[path].isRequired) { - ret.push(path); - } - } - this._requiredpaths = ret; - return this._requiredpaths; -}; - -/** - * Returns indexes from fields and schema-level indexes (cached). - * - * @api private - * @return {Array} - */ - -Schema.prototype.indexedPaths = function indexedPaths() { - if (this._indexedpaths) { - return this._indexedpaths; - } - this._indexedpaths = this.indexes(); - return this._indexedpaths; -}; - -/** - * Returns the pathType of `path` for this schema. - * - * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. - * - * @param {String} path - * @return {String} - * @api public - */ - -Schema.prototype.pathType = function(path) { - if (path in this.paths) { - return 'real'; - } - if (path in this.virtuals) { - return 'virtual'; - } - if (path in this.nested) { - return 'nested'; - } - if (path in this.subpaths) { - return 'real'; - } - if (path in this.singleNestedPaths) { - return 'real'; - } - - // Look for maps - for (const _path of Object.keys(this.paths)) { - if (!_path.includes('.$*')) { - continue; - } - const re = new RegExp('^' + _path.replace(/\.\$\*/g, '.[^.]+') + '$'); - if (re.test(path)) { - return 'real'; - } - } - - if (/\.\d+\.|\.\d+$/.test(path)) { - return getPositionalPathType(this, path); - } - return 'adhocOrUndefined'; -}; - -/** - * Returns true iff this path is a child of a mixed schema. - * - * @param {String} path - * @return {Boolean} - * @api private - */ - -Schema.prototype.hasMixedParent = function(path) { - const subpaths = path.split(/\./g); - path = ''; - for (let i = 0; i < subpaths.length; ++i) { - path = i > 0 ? path + '.' + subpaths[i] : subpaths[i]; - if (path in this.paths && - this.paths[path] instanceof MongooseTypes.Mixed) { - return true; - } - } - - return false; -}; - -/** - * Setup updatedAt and createdAt timestamps to documents if enabled - * - * @param {Boolean|Object} timestamps timestamps options - * @api private - */ -Schema.prototype.setupTimestamp = function(timestamps) { - const childHasTimestamp = this.childSchemas.find(withTimestamp); - - function withTimestamp(s) { - const ts = s.schema.options.timestamps; - return !!ts; - } - - if (!timestamps && !childHasTimestamp) { - return; - } - - const createdAt = handleTimestampOption(timestamps, 'createdAt'); - const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - const schemaAdditions = {}; - - this.$timestamps = { createdAt: createdAt, updatedAt: updatedAt }; - - if (updatedAt && !this.paths[updatedAt]) { - schemaAdditions[updatedAt] = Date; - } - - if (createdAt && !this.paths[createdAt]) { - schemaAdditions[createdAt] = Date; - } - - this.add(schemaAdditions); - - this.pre('save', function(next) { - if (get(this, '$__.saveOptions.timestamps') === false) { - return next(); - } - - const defaultTimestamp = (this.ownerDocument ? this.ownerDocument() : this). - constructor.base.now(); - const auto_id = this._id && this._id.auto; - - if (createdAt && !this.get(createdAt) && this.isSelected(createdAt)) { - this.set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp); - } - - if (updatedAt && (this.isNew || this.isModified())) { - let ts = defaultTimestamp; - if (this.isNew) { - if (createdAt != null) { - ts = this.getValue(createdAt); - } else if (auto_id) { - ts = this._id.getTimestamp(); - } - } - this.set(updatedAt, ts); - } - - next(); - }); - - this.methods.initializeTimestamps = function() { - if (createdAt && !this.get(createdAt)) { - this.set(createdAt, new Date()); - } - if (updatedAt && !this.get(updatedAt)) { - this.set(updatedAt, new Date()); - } - return this; - }; - - _setTimestampsOnUpdate[symbols.builtInMiddleware] = true; - - this.pre('findOneAndUpdate', _setTimestampsOnUpdate); - this.pre('replaceOne', _setTimestampsOnUpdate); - this.pre('update', _setTimestampsOnUpdate); - this.pre('updateOne', _setTimestampsOnUpdate); - this.pre('updateMany', _setTimestampsOnUpdate); - - function _setTimestampsOnUpdate(next) { - const now = this.model.base.now(); - applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(), - this.options, this.schema); - applyTimestampsToChildren(now, this.getUpdate(), this.model.schema); - next(); - } -}; - -/*! - * ignore - */ - -function getPositionalPathType(self, path) { - const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); - if (subpaths.length < 2) { - return self.paths.hasOwnProperty(subpaths[0]) ? self.paths[subpaths[0]] : null; - } - - let val = self.path(subpaths[0]); - let isNested = false; - if (!val) { - return val; - } - - const last = subpaths.length - 1; - - for (let i = 1; i < subpaths.length; ++i) { - isNested = false; - const subpath = subpaths[i]; - - if (i === last && val && !/\D/.test(subpath)) { - if (val.$isMongooseDocumentArray) { - const oldVal = val; - val = new SchemaType(subpath, { - required: get(val, 'schemaOptions.required', false) - }); - val.cast = function(value, doc, init) { - return oldVal.cast(value, doc, init)[0]; - }; - val.$isMongooseDocumentArrayElement = true; - val.caster = oldVal.caster; - val.schema = oldVal.schema; - } else if (val instanceof MongooseTypes.Array) { - // StringSchema, NumberSchema, etc - val = val.caster; - } else { - val = undefined; - } - break; - } - - // ignore if its just a position segment: path.0.subpath - if (!/\D/.test(subpath)) { - continue; - } - - if (!(val && val.schema)) { - val = undefined; - break; - } - - const type = val.schema.pathType(subpath); - isNested = (type === 'nested'); - val = val.schema.path(subpath); - } - - self.subpaths[path] = val; - if (val) { - return 'real'; - } - if (isNested) { - return 'nested'; - } - return 'adhocOrUndefined'; -} - - -/*! - * ignore - */ - -function getPositionalPath(self, path) { - getPositionalPathType(self, path); - return self.subpaths[path]; -} - -/** - * Adds a method call to the queue. - * - * @param {String} name name of the document method to call later - * @param {Array} args arguments to pass to the method - * @api public - */ - -Schema.prototype.queue = function(name, args) { - this.callQueue.push([name, args]); - return this; -}; - -/** - * Defines a pre hook for the document. - * - * ####Example - * - * var toySchema = new Schema({ name: String, created: Date }); - * - * toySchema.pre('save', function(next) { - * if (!this.created) this.created = new Date; - * next(); - * }); - * - * toySchema.pre('validate', function(next) { - * if (this.name !== 'Woody') this.name = 'Woody'; - * next(); - * }); - * - * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`. - * toySchema.pre(/^find/, function(next) { - * console.log(this.getQuery()); - * }); - * - * @param {String|RegExp} method or regular expression to match method name - * @param {Object} [options] - * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. - * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. - * @param {Function} callback - * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 - * @api public - */ - -Schema.prototype.pre = function(name) { - if (name instanceof RegExp) { - const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const fn of hookNames) { - if (name.test(fn)) { - this.pre.apply(this, [fn].concat(remainingArgs)); - } - } - return this; - } - this.s.hooks.pre.apply(this.s.hooks, arguments); - return this; -}; - -/** - * Defines a post hook for the document - * - * var schema = new Schema(..); - * schema.post('save', function (doc) { - * console.log('this fired after a document was saved'); - * }); - * - * schema.post('find', function(docs) { - * console.log('this fired after you ran a find query'); - * }); - * - * schema.post(/Many$/, function(res) { - * console.log('this fired after you ran `updateMany()` or `deleteMany()`); - * }); - * - * var Model = mongoose.model('Model', schema); - * - * var m = new Model(..); - * m.save(function(err) { - * console.log('this fires after the `post` hook'); - * }); - * - * m.find(function(err, docs) { - * console.log('this fires after the post find hook'); - * }); - * - * @param {String|RegExp} method or regular expression to match method name - * @param {Object} [options] - * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. - * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. - * @param {Function} fn callback - * @see middleware http://mongoosejs.com/docs/middleware.html - * @see kareem http://npmjs.org/package/kareem - * @api public - */ - -Schema.prototype.post = function(name) { - if (name instanceof RegExp) { - const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const fn of hookNames) { - if (name.test(fn)) { - this.post.apply(this, [fn].concat(remainingArgs)); - } - } - return this; - } - this.s.hooks.post.apply(this.s.hooks, arguments); - return this; -}; - -/** - * Registers a plugin for this schema. - * - * @param {Function} plugin callback - * @param {Object} [opts] - * @see plugins - * @api public - */ - -Schema.prototype.plugin = function(fn, opts) { - if (typeof fn !== 'function') { - throw new Error('First param to `schema.plugin()` must be a function, ' + - 'got "' + (typeof fn) + '"'); - } - - if (opts && - opts.deduplicate) { - for (let i = 0; i < this.plugins.length; ++i) { - if (this.plugins[i].fn === fn) { - return this; - } - } - } - this.plugins.push({ fn: fn, opts: opts }); - - fn(this, opts); - return this; -}; - -/** - * Adds an instance method to documents constructed from Models compiled from this schema. - * - * ####Example - * - * var schema = kittySchema = new Schema(..); - * - * schema.method('meow', function () { - * console.log('meeeeeoooooooooooow'); - * }) - * - * var Kitty = mongoose.model('Kitty', schema); - * - * var fizz = new Kitty; - * fizz.meow(); // meeeeeooooooooooooow - * - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. - * - * schema.method({ - * purr: function () {} - * , scratch: function () {} - * }); - * - * // later - * fizz.purr(); - * fizz.scratch(); - * - * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](./guide.html#methods) - * - * @param {String|Object} method name - * @param {Function} [fn] - * @api public - */ - -Schema.prototype.method = function(name, fn, options) { - if (typeof name !== 'string') { - for (const i in name) { - this.methods[i] = name[i]; - this.methodOptions[i] = utils.clone(options); - } - } else { - this.methods[name] = fn; - this.methodOptions[name] = utils.clone(options); - } - return this; -}; - -/** - * Adds static "class" methods to Models compiled from this schema. - * - * ####Example - * - * var schema = new Schema(..); - * schema.static('findByName', function (name, callback) { - * return this.find({ name: name }, callback); - * }); - * - * var Drink = mongoose.model('Drink', schema); - * Drink.findByName('sanpellegrino', function (err, drinks) { - * // - * }); - * - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. - * - * @param {String|Object} name - * @param {Function} [fn] - * @api public - */ - -Schema.prototype.static = function(name, fn) { - if (typeof name !== 'string') { - for (const i in name) { - this.statics[i] = name[i]; - } - } else { - this.statics[name] = fn; - } - return this; -}; - -/** - * Defines an index (most likely compound) for this schema. - * - * ####Example - * - * schema.index({ first: 1, last: -1 }) - * - * @param {Object} fields - * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex) - * @param {String} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link. - * @api public - */ - -Schema.prototype.index = function(fields, options) { - fields || (fields = {}); - options || (options = {}); - - if (options.expires) { - utils.expires(options); - } - - this._indexes.push([fields, options]); - return this; -}; - -/** - * Sets/gets a schema option. - * - * ####Example - * - * schema.set('strict'); // 'true' by default - * schema.set('strict', false); // Sets 'strict' to false - * schema.set('strict'); // 'false' - * - * @param {String} key option name - * @param {Object} [value] if not passed, the current option value is returned - * @see Schema ./ - * @api public - */ - -Schema.prototype.set = function(key, value, _tags) { - if (arguments.length === 1) { - return this.options[key]; - } - - switch (key) { - case 'read': - this.options[key] = readPref(value, _tags); - this._userProvidedOptions[key] = this.options[key]; - break; - case 'safe': - setSafe(this.options, value); - this._userProvidedOptions[key] = this.options[key]; - break; - case 'timestamps': - this.setupTimestamp(value); - this.options[key] = value; - this._userProvidedOptions[key] = this.options[key]; - break; - default: - this.options[key] = value; - this._userProvidedOptions[key] = this.options[key]; - break; - } - - return this; -}; - -/*! - * ignore - */ - -const safeDeprecationWarning = 'Mongoose: The `safe` option for schemas is ' + - 'deprecated. Use the `writeConcern` option instead: ' + - 'http://bit.ly/mongoose-write-concern'; - -const setSafe = util.deprecate(function setSafe(options, value) { - options.safe = value === false ? - {w: 0} : - value; -}, safeDeprecationWarning); - -/** - * Gets a schema option. - * - * @param {String} key option name - * @api public - */ - -Schema.prototype.get = function(key) { - return this.options[key]; -}; - -/** - * The allowed index types - * - * @receiver Schema - * @static indexTypes - * @api public - */ - -const indexTypes = '2d 2dsphere hashed text'.split(' '); - -Object.defineProperty(Schema, 'indexTypes', { - get: function() { - return indexTypes; - }, - set: function() { - throw new Error('Cannot overwrite Schema.indexTypes'); - } -}); - -/** - * Returns a list of indexes that this schema declares, via `schema.index()` - * or by `index: true` in a path's options. - * - * @api public - */ - -Schema.prototype.indexes = function() { - return getIndexes(this); -}; - -/** - * Creates a virtual type with the given name. - * - * @param {String} name - * @param {Object} [options] - * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](populate.html#populate-virtuals). - * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. - * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. - * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If truthy, will be a single doc or `null`. Otherwise, the populate virtual will be an array. - * @param {Boolean} [options.count=false] Only works with populate virtuals. If truthy, this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`. - * @return {VirtualType} - */ - -Schema.prototype.virtual = function(name, options) { - if (options && options.ref) { - if (!options.localField) { - throw new Error('Reference virtuals require `localField` option'); - } - - if (!options.foreignField) { - throw new Error('Reference virtuals require `foreignField` option'); - } - - this.pre('init', function(obj) { - if (mpath.has(name, obj)) { - const _v = mpath.get(name, obj); - if (!this.$$populatedVirtuals) { - this.$$populatedVirtuals = {}; - } - - if (options.justOne || options.count) { - this.$$populatedVirtuals[name] = Array.isArray(_v) ? - _v[0] : - _v; - } else { - this.$$populatedVirtuals[name] = Array.isArray(_v) ? - _v : - _v == null ? [] : [_v]; - } - - mpath.unset(name, obj); - } - }); - - const virtual = this.virtual(name); - virtual.options = options; - return virtual. - get(function() { - if (!this.$$populatedVirtuals) { - this.$$populatedVirtuals = {}; - } - if (name in this.$$populatedVirtuals) { - return this.$$populatedVirtuals[name]; - } - return null; - }). - set(function(_v) { - if (!this.$$populatedVirtuals) { - this.$$populatedVirtuals = {}; - } - - if (options.justOne || options.count) { - this.$$populatedVirtuals[name] = Array.isArray(_v) ? - _v[0] : - _v; - - if (typeof this.$$populatedVirtuals[name] !== 'object') { - this.$$populatedVirtuals[name] = options.count ? _v : null; - } - } else { - this.$$populatedVirtuals[name] = Array.isArray(_v) ? - _v : - _v == null ? [] : [_v]; - - this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) { - return doc && typeof doc === 'object'; - }); - } - }); - } - - const virtuals = this.virtuals; - const parts = name.split('.'); - - if (this.pathType(name) === 'real') { - throw new Error('Virtual path "' + name + '"' + - ' conflicts with a real path in the schema'); - } - - virtuals[name] = parts.reduce(function(mem, part, i) { - mem[part] || (mem[part] = (i === parts.length - 1) - ? new VirtualType(options, name) - : {}); - return mem[part]; - }, this.tree); - - return virtuals[name]; -}; - -/** - * Returns the virtual type with the given `name`. - * - * @param {String} name - * @return {VirtualType} - */ - -Schema.prototype.virtualpath = function(name) { - return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null; -}; - -/** - * Removes the given `path` (or [`paths`]). - * - * @param {String|Array} path - * @return {Schema} the Schema instance - * @api public - */ -Schema.prototype.remove = function(path) { - if (typeof path === 'string') { - path = [path]; - } - if (Array.isArray(path)) { - path.forEach(function(name) { - if (this.path(name)) { - delete this.paths[name]; - - const pieces = name.split('.'); - const last = pieces.pop(); - let branch = this.tree; - for (let i = 0; i < pieces.length; ++i) { - branch = branch[pieces[i]]; - } - delete branch[last]; - } - }, this); - } - return this; -}; - -/** - * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static), - * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions) - * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals), - * [statics](http://mongoosejs.com/docs/guide.html#statics), and - * [methods](http://mongoosejs.com/docs/guide.html#methods). - * - * ####Example: - * - * ```javascript - * const md5 = require('md5'); - * const userSchema = new Schema({ email: String }); - * class UserClass { - * // `gravatarImage` becomes a virtual - * get gravatarImage() { - * const hash = md5(this.email.toLowerCase()); - * return `https://www.gravatar.com/avatar/${hash}`; - * } - * - * // `getProfileUrl()` becomes a document method - * getProfileUrl() { - * return `https://mysite.com/${this.email}`; - * } - * - * // `findByEmail()` becomes a static - * static findByEmail(email) { - * return this.findOne({ email }); - * } - * } - * - * // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method, - * // and a `findByEmail()` static - * userSchema.loadClass(UserClass); - * ``` - * - * @param {Function} model - * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics - */ -Schema.prototype.loadClass = function(model, virtualsOnly) { - if (model === Object.prototype || - model === Function.prototype || - model.prototype.hasOwnProperty('$isMongooseModelPrototype')) { - return this; - } - - this.loadClass(Object.getPrototypeOf(model)); - - // Add static methods - if (!virtualsOnly) { - Object.getOwnPropertyNames(model).forEach(function(name) { - if (name.match(/^(length|name|prototype)$/)) { - return; - } - const method = Object.getOwnPropertyDescriptor(model, name); - if (typeof method.value === 'function') { - this.static(name, method.value); - } - }, this); - } - - // Add methods and virtuals - Object.getOwnPropertyNames(model.prototype).forEach(function(name) { - if (name.match(/^(constructor)$/)) { - return; - } - const method = Object.getOwnPropertyDescriptor(model.prototype, name); - if (!virtualsOnly) { - if (typeof method.value === 'function') { - this.method(name, method.value); - } - } - if (typeof method.get === 'function') { - this.virtual(name).get(method.get); - } - if (typeof method.set === 'function') { - this.virtual(name).set(method.set); - } - }, this); - - return this; -}; - -/*! - * ignore - */ - -Schema.prototype._getSchema = function(path) { - const _this = this; - const pathschema = _this.path(path); - const resultPath = []; - - if (pathschema) { - pathschema.$fullPath = path; - return pathschema; - } - - function search(parts, schema) { - let p = parts.length + 1; - let foundschema; - let trypath; - - while (p--) { - trypath = parts.slice(0, p).join('.'); - foundschema = schema.path(trypath); - if (foundschema) { - resultPath.push(trypath); - - if (foundschema.caster) { - // array of Mixed? - if (foundschema.caster instanceof MongooseTypes.Mixed) { - foundschema.caster.$fullPath = resultPath.join('.'); - return foundschema.caster; - } - - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length && foundschema.schema) { - let ret; - if (parts[p] === '$' || isArrayFilter(parts[p])) { - if (p + 1 === parts.length) { - // comments.$ - return foundschema; - } - // comments.$.comments.$.title - ret = search(parts.slice(p + 1), foundschema.schema); - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - return ret; - } - // this is the last path of the selector - ret = search(parts.slice(p), foundschema.schema); - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - return ret; - } - } - - foundschema.$fullPath = resultPath.join('.'); - - return foundschema; - } - } - } - - // look for arrays - const parts = path.split('.'); - for (let i = 0; i < parts.length; ++i) { - if (parts[i] === '$' || isArrayFilter(parts[i])) { - // Re: gh-5628, because `schema.path()` doesn't take $ into account. - parts[i] = '0'; - } - } - return search(parts, _this); -}; - -/*! - * ignore - */ - -Schema.prototype._getPathType = function(path) { - const _this = this; - const pathschema = _this.path(path); - - if (pathschema) { - return 'real'; - } - - function search(parts, schema) { - let p = parts.length + 1, - foundschema, - trypath; - - while (p--) { - trypath = parts.slice(0, p).join('.'); - foundschema = schema.path(trypath); - if (foundschema) { - if (foundschema.caster) { - // array of Mixed? - if (foundschema.caster instanceof MongooseTypes.Mixed) { - return { schema: foundschema, pathType: 'mixed' }; - } - - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length && foundschema.schema) { - if (parts[p] === '$' || isArrayFilter(parts[p])) { - if (p === parts.length - 1) { - return { schema: foundschema, pathType: 'nested' }; - } - // comments.$.comments.$.title - return search(parts.slice(p + 1), foundschema.schema); - } - // this is the last path of the selector - return search(parts.slice(p), foundschema.schema); - } - return { - schema: foundschema, - pathType: foundschema.$isSingleNested ? 'nested' : 'array' - }; - } - return { schema: foundschema, pathType: 'real' }; - } else if (p === parts.length && schema.nested[trypath]) { - return { schema: schema, pathType: 'nested' }; - } - } - return { schema: foundschema || schema, pathType: 'undefined' }; - } - - // look for arrays - return search(path.split('.'), _this); -}; - -/*! - * ignore - */ - -function isArrayFilter(piece) { - return piece.indexOf('$[') === 0 && - piece.lastIndexOf(']') === piece.length - 1; -} - -/*! - * Module exports. - */ - -module.exports = exports = Schema; - -// require down here because of reference issues - -/** - * The various built-in Mongoose Schema Types. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var ObjectId = mongoose.Schema.Types.ObjectId; - * - * ####Types: - * - * - [String](#schema-string-js) - * - [Number](#schema-number-js) - * - [Boolean](#schema-boolean-js) | Bool - * - [Array](#schema-array-js) - * - [Buffer](#schema-buffer-js) - * - [Date](#schema-date-js) - * - [ObjectId](#schema-objectid-js) | Oid - * - [Mixed](#schema-mixed-js) - * - * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. - * - * var Mixed = mongoose.Schema.Types.Mixed; - * new mongoose.Schema({ _user: Mixed }) - * - * @api public - */ - -Schema.Types = MongooseTypes = require('./schema/index'); - -/*! - * ignore - */ - -exports.ObjectId = MongooseTypes.ObjectId; diff --git a/node_modules/mongoose/lib/schema/array.js b/node_modules/mongoose/lib/schema/array.js deleted file mode 100644 index f2aeb14853299e62cce96500d244d4e6a13f6d7e..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/array.js +++ /dev/null @@ -1,426 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const $exists = require('./operators/exists'); -const $type = require('./operators/type'); -const MongooseError = require('../error/mongooseError'); -const SchemaType = require('../schematype'); -const CastError = SchemaType.CastError; -const Types = { - Array: SchemaArray, - Boolean: require('./boolean'), - Date: require('./date'), - Number: require('./number'), - String: require('./string'), - ObjectId: require('./objectid'), - Buffer: require('./buffer'), - Map: require('./map') -}; -const Mixed = require('./mixed'); -const cast = require('../cast'); -const get = require('../helpers/get'); -const util = require('util'); -const utils = require('../utils'); -const castToNumber = require('./operators/helpers').castToNumber; -const geospatial = require('./operators/geospatial'); -const getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue; - -let MongooseArray; -let EmbeddedDoc; - -/** - * Array SchemaType constructor - * - * @param {String} key - * @param {SchemaType} cast - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaArray(key, cast, options, schemaOptions) { - // lazy load - EmbeddedDoc || (EmbeddedDoc = require('../types').Embedded); - - let typeKey = 'type'; - if (schemaOptions && schemaOptions.typeKey) { - typeKey = schemaOptions.typeKey; - } - - if (cast) { - let castOptions = {}; - - if (utils.isPOJO(cast)) { - if (cast[typeKey]) { - // support { type: Woot } - castOptions = utils.clone(cast); // do not alter user arguments - delete castOptions[typeKey]; - cast = cast[typeKey]; - } else { - cast = Mixed; - } - } - - if (cast === Object) { - cast = Mixed; - } - - // support { type: 'String' } - const name = typeof cast === 'string' - ? cast - : utils.getFunctionName(cast); - - const caster = name in Types - ? Types[name] - : cast; - - this.casterConstructor = caster; - - if (typeof caster === 'function' && - !caster.$isArraySubdocument && - !caster.$isSchemaMap) { - this.caster = new caster(null, castOptions); - } else { - this.caster = caster; - } - - if (!(this.caster instanceof EmbeddedDoc)) { - this.caster.path = key; - } - } - - this.$isMongooseArray = true; - - SchemaType.call(this, key, options, 'Array'); - - let defaultArr; - let fn; - - if (this.defaultValue != null) { - defaultArr = this.defaultValue; - fn = typeof defaultArr === 'function'; - } - - if (!('defaultValue' in this) || this.defaultValue !== void 0) { - const defaultFn = function() { - let arr = []; - if (fn) { - arr = defaultArr.call(this); - } else if (defaultArr != null) { - arr = arr.concat(defaultArr); - } - // Leave it up to `cast()` to convert the array - return arr; - }; - defaultFn.$runBeforeSetters = true; - this.default(defaultFn); - } -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaArray.schemaName = 'Array'; - -/** - * Options for all arrays. - * - * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. - * - * @static options - * @api public - */ - -SchemaArray.options = { castNonArrays: true }; - -/*! - * Inherits from SchemaType. - */ -SchemaArray.prototype = Object.create(SchemaType.prototype); -SchemaArray.prototype.constructor = SchemaArray; - -/** - * Adds an enum validator if this is an array of strings. Equivalent to - * `SchemaString.prototype.enum()` - * - * @param {String|Object} [args...] enumeration values - * @return {SchemaType} this - */ - -SchemaArray.prototype.enum = function() { - const instance = get(this, 'caster.instance'); - if (instance !== 'String') { - throw new Error('`enum` can only be set on an array of strings, not ' + instance); - } - this.caster.enum.apply(this.caster, arguments); - return this; -}; - -/** - * Overrides the getters application for the population special-case - * - * @param {Object} value - * @param {Object} scope - * @api private - */ - -SchemaArray.prototype.applyGetters = function(value, scope) { - if (this.caster.options && this.caster.options.ref) { - // means the object id was populated - return value; - } - - return SchemaType.prototype.applyGetters.call(this, value, scope); -}; - -/** - * Casts values for set(). - * - * @param {Object} value - * @param {Document} doc document that triggers the casting - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - -SchemaArray.prototype.cast = function(value, doc, init) { - // lazy load - MongooseArray || (MongooseArray = require('../types').Array); - - let i; - let l; - - if (Array.isArray(value)) { - if (!value.length && doc) { - const indexes = doc.schema.indexedPaths(); - - for (i = 0, l = indexes.length; i < l; ++i) { - const pathIndex = indexes[i][0][this.path]; - if (pathIndex === '2dsphere' || pathIndex === '2d') { - return; - } - } - } - - if (!(value && value.isMongooseArray)) { - value = new MongooseArray(value, this.path, doc); - } else if (value && value.isMongooseArray) { - // We need to create a new array, otherwise change tracking will - // update the old doc (gh-4449) - value = new MongooseArray(value, this.path, doc); - } - - if (this.caster && this.casterConstructor !== Mixed) { - try { - for (i = 0, l = value.length; i < l; i++) { - value[i] = this.caster.cast(value[i], doc, init); - } - } catch (e) { - // rethrow - throw new CastError('[' + e.kind + ']', util.inspect(value), this.path, e); - } - } - - return value; - } - - if (init || SchemaArray.options.castNonArrays) { - // gh-2442: if we're loading this from the db and its not an array, mark - // the whole array as modified. - if (!!doc && !!init) { - doc.markModified(this.path); - } - return this.cast([value], doc, init); - } - - throw new CastError('Array', util.inspect(value), this.path); -}; - -/*! - * Ignore - */ - -SchemaArray.prototype.discriminator = function(name, schema) { - let arr = this; // eslint-disable-line consistent-this - while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) { - arr = arr.casterConstructor; - if (arr == null || typeof arr === 'function') { - throw new MongooseError('You can only add an embedded discriminator on ' + - 'a document array, ' + this.path + ' is a plain array'); - } - } - return arr.discriminator(name, schema); -}; - -/** - * Casts values for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaArray.prototype.castForQuery = function($conditional, value) { - let handler; - let val; - - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - - if (!handler) { - throw new Error('Can\'t use ' + $conditional + ' with Array.'); - } - - val = handler.call(this, value); - } else { - val = $conditional; - let Constructor = this.casterConstructor; - - if (val && - Constructor.discriminators && - Constructor.schema && - Constructor.schema.options && - Constructor.schema.options.discriminatorKey) { - if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' && - Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) { - Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, val[Constructor.schema.options.discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - const proto = this.casterConstructor.prototype; - let method = proto && (proto.castForQuery || proto.cast); - if (!method && Constructor.castForQuery) { - method = Constructor.castForQuery; - } - const caster = this.caster; - - if (Array.isArray(val)) { - this.setters.reverse().forEach(setter => { - val = setter.call(this, val, this); - }); - val = val.map(function(v) { - if (utils.isObject(v) && v.$elemMatch) { - return v; - } - if (method) { - v = method.call(caster, v); - return v; - } - if (v != null) { - v = new Constructor(v); - return v; - } - return v; - }); - } else if (method) { - val = method.call(caster, val); - } else if (val != null) { - val = new Constructor(val); - } - } - - return val; -}; - -function cast$all(val) { - if (!Array.isArray(val)) { - val = [val]; - } - - val = val.map(function(v) { - if (utils.isObject(v)) { - const o = {}; - o[this.path] = v; - return cast(this.casterConstructor.schema, o)[this.path]; - } - return v; - }, this); - - return this.castForQuery(val); -} - -function cast$elemMatch(val) { - const keys = Object.keys(val); - const numKeys = keys.length; - for (let i = 0; i < numKeys; ++i) { - const key = keys[i]; - const value = val[key]; - if (key.indexOf('$') === 0 && value) { - val[key] = this.castForQuery(key, value); - } - } - - // Is this an embedded discriminator and is the discriminator key set? - // If so, use the discriminator schema. See gh-7449 - const discriminatorKey = get(this, - 'casterConstructor.schema.options.discriminatorKey'); - const discriminators = get(this, 'casterConstructor.schema.discriminators', {}); - if (discriminatorKey != null && - val[discriminatorKey] != null && - discriminators[val[discriminatorKey]] != null) { - return cast(discriminators[val[discriminatorKey]], val); - } - - return cast(this.casterConstructor.schema, val); -} - -const handle = SchemaArray.prototype.$conditionalHandlers = {}; - -handle.$all = cast$all; -handle.$options = String; -handle.$elemMatch = cast$elemMatch; -handle.$geoIntersects = geospatial.cast$geoIntersects; -handle.$or = handle.$and = function(val) { - if (!Array.isArray(val)) { - throw new TypeError('conditional $or/$and require array'); - } - - const ret = []; - for (let i = 0; i < val.length; ++i) { - ret.push(cast(this.casterConstructor.schema, val[i])); - } - - return ret; -}; - -handle.$near = -handle.$nearSphere = geospatial.cast$near; - -handle.$within = -handle.$geoWithin = geospatial.cast$within; - -handle.$size = -handle.$minDistance = -handle.$maxDistance = castToNumber; - -handle.$exists = $exists; -handle.$type = $type; - -handle.$eq = -handle.$gt = -handle.$gte = -handle.$lt = -handle.$lte = -handle.$ne = -handle.$nin = -handle.$regex = SchemaArray.prototype.castForQuery; - -// `$in` is special because you can also include an empty array in the query -// like `$in: [1, []]`, see gh-5913 -handle.$in = SchemaType.prototype.$conditionalHandlers.$in; - -/*! - * Module exports. - */ - -module.exports = SchemaArray; diff --git a/node_modules/mongoose/lib/schema/boolean.js b/node_modules/mongoose/lib/schema/boolean.js deleted file mode 100644 index 4b2b3fa52a528ce37af9629c6a250da90c9ddb84..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/boolean.js +++ /dev/null @@ -1,205 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const CastError = require('../error/cast'); -const SchemaType = require('../schematype'); -const castBoolean = require('../cast/boolean'); -const utils = require('../utils'); - -/** - * Boolean SchemaType constructor. - * - * @param {String} path - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaBoolean(path, options) { - SchemaType.call(this, path, options, 'Boolean'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaBoolean.schemaName = 'Boolean'; - -/*! - * Inherits from SchemaType. - */ -SchemaBoolean.prototype = Object.create(SchemaType.prototype); -SchemaBoolean.prototype.constructor = SchemaBoolean; - -/*! - * ignore - */ - -SchemaBoolean._cast = castBoolean; - -/** - * Get/set the function used to cast arbitrary values to booleans. - * - * ####Example: - * - * // Make Mongoose cast empty string '' to false. - * const original = mongoose.Schema.Boolean.cast(); - * mongoose.Schema.Boolean.cast(v => { - * if (v === '') { - * return false; - * } - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Schema.Boolean.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - -SchemaBoolean.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (v != null && typeof v !== 'boolean') { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/*! - * ignore - */ - -SchemaBoolean._checkRequired = v => v === true || v === false; - -/** - * Override the function the required validator uses to check whether a boolean - * passes the `required` check. - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaBoolean.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. For a boolean - * to satisfy a required validator, it must be strictly equal to true or to - * false. - * - * @param {Any} value - * @return {Boolean} - * @api public - */ - -SchemaBoolean.prototype.checkRequired = function(value) { - return this.constructor._checkRequired(value); -}; - -/** - * Configure which values get casted to `true`. - * - * ####Example: - * - * const M = mongoose.model('Test', new Schema({ b: Boolean })); - * new M({ b: 'affirmative' }).b; // undefined - * mongoose.Schema.Boolean.convertToTrue.add('affirmative'); - * new M({ b: 'affirmative' }).b; // true - * - * @property convertToTrue - * @type Set - * @api public - */ - -Object.defineProperty(SchemaBoolean, 'convertToTrue', { - get: () => castBoolean.convertToTrue, - set: v => { castBoolean.convertToTrue = v; } -}); - -/** - * Configure which values get casted to `false`. - * - * ####Example: - * - * const M = mongoose.model('Test', new Schema({ b: Boolean })); - * new M({ b: 'nay' }).b; // undefined - * mongoose.Schema.Types.Boolean.convertToFalse.add('nay'); - * new M({ b: 'nay' }).b; // false - * - * @property convertToFalse - * @type Set - * @api public - */ - -Object.defineProperty(SchemaBoolean, 'convertToFalse', { - get: () => castBoolean.convertToFalse, - set: v => { castBoolean.convertToFalse = v; } -}); - -/** - * Casts to boolean - * - * @param {Object} value - * @param {Object} model - this value is optional - * @api private - */ - -SchemaBoolean.prototype.cast = function(value) { - try { - return this.constructor.cast()(value); - } catch (error) { - throw new CastError('Boolean', value, this.path); - } -}; - -SchemaBoolean.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, {}); - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} val - * @api private - */ - -SchemaBoolean.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = SchemaBoolean.$conditionalHandlers[$conditional]; - - if (handler) { - return handler.call(this, val); - } - - return this._castForQuery(val); - } - - return this._castForQuery($conditional); -}; - -/*! - * Module exports. - */ - -module.exports = SchemaBoolean; diff --git a/node_modules/mongoose/lib/schema/buffer.js b/node_modules/mongoose/lib/schema/buffer.js deleted file mode 100644 index 8bf6bc52bf2c19bd21b5978751c3144507dd9b5f..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/buffer.js +++ /dev/null @@ -1,250 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const handleBitwiseOperator = require('./operators/bitwise'); -const utils = require('../utils'); - -const MongooseBuffer = require('../types/buffer'); -const SchemaType = require('../schematype'); - -const Binary = MongooseBuffer.Binary; -const CastError = SchemaType.CastError; -let Document; - -/** - * Buffer SchemaType constructor - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaBuffer(key, options) { - SchemaType.call(this, key, options, 'Buffer'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaBuffer.schemaName = 'Buffer'; - -/*! - * Inherits from SchemaType. - */ -SchemaBuffer.prototype = Object.create(SchemaType.prototype); -SchemaBuffer.prototype.constructor = SchemaBuffer; - -/*! - * ignore - */ - -SchemaBuffer._checkRequired = v => !!(v && v.length); - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ buf: { type: Buffer, required: true } }); - * new M({ buf: Buffer.from('') }).validateSync(); // validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaBuffer.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. To satisfy a - * required validator, a buffer must not be null or undefined and have - * non-zero length. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -SchemaBuffer.prototype.checkRequired = function(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - return this.constructor._checkRequired(value); -}; - -/** - * Casts contents - * - * @param {Object} value - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api private - */ - -SchemaBuffer.prototype.cast = function(value, doc, init) { - let ret; - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (value === null || value === undefined) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (Buffer.isBuffer(value)) { - return value; - } else if (!utils.isObject(value)) { - throw new CastError('buffer', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - // documents - if (value && value._id) { - value = value._id; - } - - if (value && value.isMongooseBuffer) { - return value; - } - - if (Buffer.isBuffer(value)) { - if (!value || !value.isMongooseBuffer) { - value = new MongooseBuffer(value, [this.path, doc]); - if (this.options.subtype != null) { - value._subtype = this.options.subtype; - } - } - return value; - } - - if (value instanceof Binary) { - ret = new MongooseBuffer(value.value(true), [this.path, doc]); - if (typeof value.sub_type !== 'number') { - throw new CastError('buffer', value, this.path); - } - ret._subtype = value.sub_type; - return ret; - } - - if (value === null) { - return value; - } - - - const type = typeof value; - if ( - type === 'string' || type === 'number' || Array.isArray(value) || - (type === 'object' && value.type === 'Buffer' && Array.isArray(value.data)) // gh-6863 - ) { - if (type === 'number') { - value = [value]; - } - ret = new MongooseBuffer(value, [this.path, doc]); - if (this.options.subtype != null) { - ret._subtype = this.options.subtype; - } - return ret; - } - - throw new CastError('buffer', value, this.path); -}; - -/** - * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/) - * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html). - * - * ####Example: - * - * var s = new Schema({ uuid: { type: Buffer, subtype: 4 }); - * var M = db.model('M', s); - * var m = new M({ uuid: 'test string' }); - * m.uuid._subtype; // 4 - * - * @param {Number} subtype the default subtype - * @return {SchemaType} this - * @api public - */ - -SchemaBuffer.prototype.subtype = function(subtype) { - this.options.subtype = subtype; - return this; -}; - -/*! - * ignore - */ -function handleSingle(val) { - return this.castForQuery(val); -} - -SchemaBuffer.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $bitsAllClear: handleBitwiseOperator, - $bitsAnyClear: handleBitwiseOperator, - $bitsAllSet: handleBitwiseOperator, - $bitsAnySet: handleBitwiseOperator, - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle - }); - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaBuffer.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error('Can\'t use ' + $conditional + ' with Buffer.'); - } - return handler.call(this, val); - } - val = $conditional; - const casted = this._castForQuery(val); - return casted ? casted.toObject({ transform: false, virtuals: false }) : casted; -}; - -/*! - * Module exports. - */ - -module.exports = SchemaBuffer; diff --git a/node_modules/mongoose/lib/schema/date.js b/node_modules/mongoose/lib/schema/date.js deleted file mode 100644 index 6e06cb7e4cd1dd50b5ffad9585ec7154e653b0d9..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/date.js +++ /dev/null @@ -1,346 +0,0 @@ -/*! - * Module requirements. - */ - -'use strict'; - -const MongooseError = require('../error'); -const castDate = require('../cast/date'); -const utils = require('../utils'); - -const SchemaType = require('../schematype'); - -const CastError = SchemaType.CastError; - -/** - * Date SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaDate(key, options) { - SchemaType.call(this, key, options, 'Date'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaDate.schemaName = 'Date'; - -/*! - * Inherits from SchemaType. - */ -SchemaDate.prototype = Object.create(SchemaType.prototype); -SchemaDate.prototype.constructor = SchemaDate; - -/*! - * ignore - */ - -SchemaDate._cast = castDate; - -/** - * Get/set the function used to cast arbitrary values to dates. - * - * ####Example: - * - * // Mongoose converts empty string '' into `null` for date types. You - * // can create a custom caster to disable it. - * const original = mongoose.Schema.Types.Date.cast(); - * mongoose.Schema.Types.Date.cast(v => { - * assert.ok(v !== ''); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Schema.Types.Date.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - -SchemaDate.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (v != null && !(v instanceof Date)) { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/** - * Declares a TTL index (rounded to the nearest second) for _Date_ types only. - * - * This sets the `expireAfterSeconds` index option available in MongoDB >= 2.1.2. - * This index type is only compatible with Date types. - * - * ####Example: - * - * // expire in 24 hours - * new Schema({ createdAt: { type: Date, expires: 60*60*24 }}); - * - * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: - * - * ####Example: - * - * // expire in 24 hours - * new Schema({ createdAt: { type: Date, expires: '24h' }}); - * - * // expire in 1.5 hours - * new Schema({ createdAt: { type: Date, expires: '1.5h' }}); - * - * // expire in 7 days - * var schema = new Schema({ createdAt: Date }); - * schema.path('createdAt').expires('7d'); - * - * @param {Number|String} when - * @added 3.0.0 - * @return {SchemaType} this - * @api public - */ - -SchemaDate.prototype.expires = function(when) { - if (!this._index || this._index.constructor.name !== 'Object') { - this._index = {}; - } - - this._index.expires = when; - utils.expires(this._index); - return this; -}; - -/*! - * ignore - */ - -SchemaDate._checkRequired = v => v instanceof Date; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ str: { type: String, required: true } }); - * new M({ str: '' }).validateSync(); // `null`, validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaDate.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. To satisfy - * a required validator, the given value must be an instance of `Date`. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -SchemaDate.prototype.checkRequired = function(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - return this.constructor._checkRequired(value); -}; - -/** - * Sets a minimum date validator. - * - * ####Example: - * - * var s = new Schema({ d: { type: Date, min: Date('1970-01-01') }) - * var M = db.model('M', s) - * var m = new M({ d: Date('1969-12-31') }) - * m.save(function (err) { - * console.error(err) // validator error - * m.d = Date('2014-12-08'); - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MIN} token which will be replaced with the invalid value - * var min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; - * var schema = new Schema({ d: { type: Date, min: min }) - * var M = mongoose.model('M', schema); - * var s= new M({ d: Date('1969-12-31') }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01). - * }) - * - * @param {Date} value minimum date - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaDate.prototype.min = function(value, message) { - if (this.minValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.minValidator; - }, this); - } - - if (value) { - let msg = message || MongooseError.messages.Date.min; - msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString())); - const _this = this; - this.validators.push({ - validator: this.minValidator = function(val) { - const min = (value === Date.now ? value() : _this.cast(value)); - return val === null || val.valueOf() >= min.valueOf(); - }, - message: msg, - type: 'min', - min: value - }); - } - - return this; -}; - -/** - * Sets a maximum date validator. - * - * ####Example: - * - * var s = new Schema({ d: { type: Date, max: Date('2014-01-01') }) - * var M = db.model('M', s) - * var m = new M({ d: Date('2014-12-08') }) - * m.save(function (err) { - * console.error(err) // validator error - * m.d = Date('2013-12-31'); - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAX} token which will be replaced with the invalid value - * var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; - * var schema = new Schema({ d: { type: Date, max: max }) - * var M = mongoose.model('M', schema); - * var s= new M({ d: Date('2014-12-08') }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01). - * }) - * - * @param {Date} maximum date - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaDate.prototype.max = function(value, message) { - if (this.maxValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.maxValidator; - }, this); - } - - if (value) { - let msg = message || MongooseError.messages.Date.max; - msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString())); - const _this = this; - this.validators.push({ - validator: this.maxValidator = function(val) { - const max = (value === Date.now ? value() : _this.cast(value)); - return val === null || val.valueOf() <= max.valueOf(); - }, - message: msg, - type: 'max', - max: value - }); - } - - return this; -}; - -/** - * Casts to date - * - * @param {Object} value to cast - * @api private - */ - -SchemaDate.prototype.cast = function(value) { - const _castDate = this.constructor.cast(); - try { - return _castDate(value); - } catch (error) { - throw new CastError('date', value, this.path); - } -}; - -/*! - * Date Query casting. - * - * @api private - */ - -function handleSingle(val) { - return this.cast(val); -} - -SchemaDate.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle - }); - - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaDate.prototype.castForQuery = function($conditional, val) { - if (arguments.length !== 2) { - return this._castForQuery($conditional); - } - - const handler = this.$conditionalHandlers[$conditional]; - - if (!handler) { - throw new Error('Can\'t use ' + $conditional + ' with Date.'); - } - - return handler.call(this, val); -}; - -/*! - * Module exports. - */ - -module.exports = SchemaDate; diff --git a/node_modules/mongoose/lib/schema/decimal128.js b/node_modules/mongoose/lib/schema/decimal128.js deleted file mode 100644 index 0338905ffe8c96c94e9a9058e10910756b0db473..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/decimal128.js +++ /dev/null @@ -1,201 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const SchemaType = require('../schematype'); -const CastError = SchemaType.CastError; -const Decimal128Type = require('../types/decimal128'); -const castDecimal128 = require('../cast/decimal128'); -const utils = require('../utils'); - -let Document; - -/** - * Decimal128 SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function Decimal128(key, options) { - SchemaType.call(this, key, options, 'Decimal128'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -Decimal128.schemaName = 'Decimal128'; - -/*! - * Inherits from SchemaType. - */ -Decimal128.prototype = Object.create(SchemaType.prototype); -Decimal128.prototype.constructor = Decimal128; - -/*! - * ignore - */ - -Decimal128._cast = castDecimal128; - -/** - * Get/set the function used to cast arbitrary values to decimals. - * - * ####Example: - * - * // Make Mongoose only refuse to cast numbers as decimal128 - * const original = mongoose.Schema.Types.Decimal128.cast(); - * mongoose.Decimal128.cast(v => { - * assert.ok(typeof v !== 'number'); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Decimal128.cast(false); - * - * @param {Function} [caster] - * @return {Function} - * @function get - * @static - * @api public - */ - -Decimal128.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (v != null && !(v instanceof Decimal128Type)) { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/*! - * ignore - */ - -Decimal128._checkRequired = v => v instanceof Decimal128Type; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -Decimal128.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -Decimal128.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - return this.constructor._checkRequired(value); -}; - -/** - * Casts to Decimal128 - * - * @param {Object} value - * @param {Object} doc - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - -Decimal128.prototype.cast = function(value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (value === null || value === undefined) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (value instanceof Decimal128Type) { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('Decimal128', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - let ret = value; - if (!doc.$__.populated || - !doc.$__.populated[path] || - !doc.$__.populated[path].options || - !doc.$__.populated[path].options.options || - !doc.$__.populated[path].options.options.lean) { - ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - } - - return ret; - } - - const _castDecimal128 = this.constructor.cast(); - try { - return _castDecimal128(value); - } catch (error) { - throw new CastError('Decimal128', value, this.path); - } -}; - -/*! - * ignore - */ - -function handleSingle(val) { - return this.cast(val); -} - -Decimal128.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle - }); - -/*! - * Module exports. - */ - -module.exports = Decimal128; diff --git a/node_modules/mongoose/lib/schema/documentarray.js b/node_modules/mongoose/lib/schema/documentarray.js deleted file mode 100644 index d874ff228e0571c5713ce0b3c551f4cebd36bf21..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/documentarray.js +++ /dev/null @@ -1,474 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const ArrayType = require('./array'); -const CastError = require('../error/cast'); -const EventEmitter = require('events').EventEmitter; -const SchemaType = require('../schematype'); -const discriminator = require('../helpers/model/discriminator'); -const util = require('util'); -const utils = require('../utils'); -const getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue; - -let MongooseDocumentArray; -let Subdocument; - -/** - * SubdocsArray SchemaType constructor - * - * @param {String} key - * @param {Schema} schema - * @param {Object} options - * @inherits SchemaArray - * @api public - */ - -function DocumentArray(key, schema, options, schemaOptions) { - const EmbeddedDocument = _createConstructor(schema, options); - EmbeddedDocument.prototype.$basePath = key; - - ArrayType.call(this, key, EmbeddedDocument, options); - - this.schema = schema; - this.schemaOptions = schemaOptions || {}; - this.$isMongooseDocumentArray = true; - this.Constructor = EmbeddedDocument; - - EmbeddedDocument.base = schema.base; - - const fn = this.defaultValue; - - if (!('defaultValue' in this) || fn !== void 0) { - this.default(function() { - let arr = fn.call(this); - if (!Array.isArray(arr)) { - arr = [arr]; - } - // Leave it up to `cast()` to convert this to a documentarray - return arr; - }); - } -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -DocumentArray.schemaName = 'DocumentArray'; - -/** - * Options for all document arrays. - * - * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. - * - * @static options - * @api public - */ - -DocumentArray.options = { castNonArrays: true }; - -/*! - * Inherits from ArrayType. - */ -DocumentArray.prototype = Object.create(ArrayType.prototype); -DocumentArray.prototype.constructor = DocumentArray; - -/*! - * Ignore - */ - -function _createConstructor(schema, options) { - Subdocument || (Subdocument = require('../types/embedded')); - - // compile an embedded document for this schema - function EmbeddedDocument() { - Subdocument.apply(this, arguments); - - this.$session(this.ownerDocument().$session()); - } - - EmbeddedDocument.prototype = Object.create(Subdocument.prototype); - EmbeddedDocument.prototype.$__setSchema(schema); - EmbeddedDocument.schema = schema; - EmbeddedDocument.prototype.constructor = EmbeddedDocument; - EmbeddedDocument.$isArraySubdocument = true; - EmbeddedDocument.events = new EventEmitter(); - - // apply methods - for (const i in schema.methods) { - EmbeddedDocument.prototype[i] = schema.methods[i]; - } - - // apply statics - for (const i in schema.statics) { - EmbeddedDocument[i] = schema.statics[i]; - } - - for (const i in EventEmitter.prototype) { - EmbeddedDocument[i] = EventEmitter.prototype[i]; - } - - EmbeddedDocument.options = options; - - return EmbeddedDocument; -} - -/*! - * Ignore - */ - -DocumentArray.prototype.discriminator = function(name, schema) { - if (typeof name === 'function') { - name = utils.getFunctionName(name); - } - - schema = discriminator(this.casterConstructor, name, schema); - - const EmbeddedDocument = _createConstructor(schema); - EmbeddedDocument.baseCasterConstructor = this.casterConstructor; - - try { - Object.defineProperty(EmbeddedDocument, 'name', { - value: name - }); - } catch (error) { - // Ignore error, only happens on old versions of node - } - - this.casterConstructor.discriminators[name] = EmbeddedDocument; - - return this.casterConstructor.discriminators[name]; -}; - -/** - * Performs local validations first, then validations on each embedded doc - * - * @api private - */ - -DocumentArray.prototype.doValidate = function(array, fn, scope, options) { - // lazy load - MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); - - const _this = this; - try { - SchemaType.prototype.doValidate.call(this, array, cb, scope); - } catch (err) { - err.$isArrayValidatorError = true; - return fn(err); - } - - function cb(err) { - if (err) { - err.$isArrayValidatorError = true; - return fn(err); - } - - let count = array && array.length; - let error; - - if (!count) { - return fn(); - } - if (options && options.updateValidator) { - return fn(); - } - if (!array.isMongooseDocumentArray) { - array = new MongooseDocumentArray(array, _this.path, scope); - } - - // handle sparse arrays, do not use array.forEach which does not - // iterate over sparse elements yet reports array.length including - // them :( - - function callback(err) { - if (err != null) { - error = err; - if (error.name !== 'ValidationError') { - error.$isArrayValidatorError = true; - } - } - --count || fn(error); - } - - for (let i = 0, len = count; i < len; ++i) { - // sidestep sparse entries - let doc = array[i]; - if (doc == null) { - --count || fn(error); - continue; - } - - // If you set the array index directly, the doc might not yet be - // a full fledged mongoose subdoc, so make it into one. - if (!(doc instanceof Subdocument)) { - doc = array[i] = new _this.casterConstructor(doc, array, undefined, - undefined, i); - } - - doc.$__validate(callback); - } - } -}; - -/** - * Performs local validations first, then validations on each embedded doc. - * - * ####Note: - * - * This method ignores the asynchronous validators. - * - * @return {MongooseError|undefined} - * @api private - */ - -DocumentArray.prototype.doValidateSync = function(array, scope) { - const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); - if (schemaTypeError != null) { - schemaTypeError.$isArrayValidatorError = true; - return schemaTypeError; - } - - const count = array && array.length; - let resultError = null; - - if (!count) { - return; - } - - // handle sparse arrays, do not use array.forEach which does not - // iterate over sparse elements yet reports array.length including - // them :( - - for (let i = 0, len = count; i < len; ++i) { - // sidestep sparse entries - let doc = array[i]; - if (!doc) { - continue; - } - - // If you set the array index directly, the doc might not yet be - // a full fledged mongoose subdoc, so make it into one. - if (!(doc instanceof Subdocument)) { - doc = array[i] = new this.casterConstructor(doc, array, undefined, - undefined, i); - } - - const subdocValidateError = doc.validateSync(); - - if (subdocValidateError && resultError == null) { - resultError = subdocValidateError; - } - } - - return resultError; -}; - -/*! - * ignore - */ - -DocumentArray.prototype.getDefault = function(scope) { - let ret = typeof this.defaultValue === 'function' - ? this.defaultValue.call(scope) - : this.defaultValue; - - if (ret == null) { - return ret; - } - - // lazy load - MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); - - if (!Array.isArray(ret)) { - ret = [ret]; - } - - ret = new MongooseDocumentArray(ret, this.path, scope); - const _parent = ret._parent; - ret._parent = null; - - for (let i = 0; i < ret.length; ++i) { - ret[i] = new this.Constructor(ret[i], ret, undefined, - undefined, i); - } - - ret._parent = _parent; - - return ret; -}; - -/** - * Casts contents - * - * @param {Object} value - * @param {Document} document that triggers the casting - * @api private - */ - -DocumentArray.prototype.cast = function(value, doc, init, prev, options) { - // lazy load - MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); - - let selected; - let subdoc; - let i; - const _opts = { transform: false, virtuals: false }; - - if (!Array.isArray(value)) { - if (!init && !DocumentArray.options.castNonArrays) { - throw new CastError('DocumentArray', util.inspect(value), this.path); - } - // gh-2442 mark whole array as modified if we're initializing a doc from - // the db and the path isn't an array in the document - if (!!doc && init) { - doc.markModified(this.path); - } - return this.cast([value], doc, init, prev); - } - - if (!(value && value.isMongooseDocumentArray) && - (!options || !options.skipDocumentArrayCast)) { - value = new MongooseDocumentArray(value, this.path, doc); - _clearListeners(prev); - } else if (value && value.isMongooseDocumentArray) { - // We need to create a new array, otherwise change tracking will - // update the old doc (gh-4449) - value = new MongooseDocumentArray(value, this.path, doc); - } - - i = value.length; - - while (i--) { - if (!value[i]) { - continue; - } - - let Constructor = this.casterConstructor; - if (Constructor.discriminators && - Constructor.schema && - Constructor.schema.options && - typeof value[i][Constructor.schema.options.discriminatorKey] === 'string') { - if (Constructor.discriminators[value[i][Constructor.schema.options.discriminatorKey]]) { - Constructor = Constructor.discriminators[value[i][Constructor.schema.options.discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, value[i][Constructor.schema.options.discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - // Check if the document has a different schema (re gh-3701) - if ((value[i].$__) && - value[i].schema !== Constructor.schema) { - value[i] = value[i].toObject({ transform: false, virtuals: false }); - } - if (!(value[i] instanceof Subdocument) && value[i]) { - if (init) { - if (doc) { - selected || (selected = scopePaths(this, doc.$__.selected, init)); - } else { - selected = true; - } - - subdoc = new Constructor(null, value, true, selected, i); - value[i] = subdoc.init(value[i]); - } else { - if (prev && (subdoc = prev.id(value[i]._id))) { - subdoc = prev.id(value[i]._id); - } - - if (prev && subdoc && utils.deepEqual(subdoc.toObject(_opts), value[i])) { - // handle resetting doc with existing id and same data - subdoc.set(value[i]); - // if set() is hooked it will have no return value - // see gh-746 - value[i] = subdoc; - } else { - try { - subdoc = new Constructor(value[i], value, undefined, - undefined, i); - // if set() is hooked it will have no return value - // see gh-746 - value[i] = subdoc; - } catch (error) { - // Make sure we don't leave listeners dangling because `value` - // won't get back up to the schema type. See gh-6723 - _clearListeners(value); - const valueInErrorMessage = util.inspect(value[i]); - throw new CastError('embedded', valueInErrorMessage, - value._path, error); - } - } - } - } - } - - return value; -}; - -/*! - * Removes listeners from parent - */ - -function _clearListeners(arr) { - if (arr == null || arr._parent == null) { - return; - } - - for (const key in arr._handlers) { - arr._parent.removeListener(key, arr._handlers[key]); - } -} - -/*! - * Scopes paths selected in a query to this array. - * Necessary for proper default application of subdocument values. - * - * @param {DocumentArray} array - the array to scope `fields` paths - * @param {Object|undefined} fields - the root fields selected in the query - * @param {Boolean|undefined} init - if we are being created part of a query result - */ - -function scopePaths(array, fields, init) { - if (!(init && fields)) { - return undefined; - } - - const path = array.path + '.'; - const keys = Object.keys(fields); - let i = keys.length; - const selected = {}; - let hasKeys; - let key; - let sub; - - while (i--) { - key = keys[i]; - if (key.indexOf(path) === 0) { - sub = key.substring(path.length); - if (sub === '$') { - continue; - } - if (sub.indexOf('$.') === 0) { - sub = sub.substr(2); - } - hasKeys || (hasKeys = true); - selected[sub] = fields[key]; - } - } - - return hasKeys && selected || undefined; -} - -/*! - * Module exports. - */ - -module.exports = DocumentArray; diff --git a/node_modules/mongoose/lib/schema/embedded.js b/node_modules/mongoose/lib/schema/embedded.js deleted file mode 100644 index ab08fd88ca592f3c699e9e67597fd2471d05ec15..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/embedded.js +++ /dev/null @@ -1,320 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const CastError = require('../error/cast'); -const EventEmitter = require('events').EventEmitter; -const ObjectExpectedError = require('../error/objectExpected'); -const SchemaType = require('../schematype'); -const $exists = require('./operators/exists'); -const castToNumber = require('./operators/helpers').castToNumber; -const discriminator = require('../helpers/model/discriminator'); -const geospatial = require('./operators/geospatial'); -const get = require('../helpers/get'); -const getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue; -const internalToObjectOptions = require('../options').internalToObjectOptions; - -let Subdocument; - -module.exports = Embedded; - -/** - * Sub-schema schematype constructor - * - * @param {Schema} schema - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function Embedded(schema, path, options) { - this.caster = _createConstructor(schema); - this.caster.path = path; - this.caster.prototype.$basePath = path; - this.schema = schema; - this.$isSingleNested = true; - SchemaType.call(this, path, options, 'Embedded'); -} - -/*! - * ignore - */ - -Embedded.prototype = Object.create(SchemaType.prototype); - -/*! - * ignore - */ - -function _createConstructor(schema) { - // lazy load - Subdocument || (Subdocument = require('../types/subdocument')); - - const _embedded = function SingleNested(value, path, parent) { - const _this = this; - - this.$parent = parent; - Subdocument.apply(this, arguments); - - this.$session(this.ownerDocument().$session()); - - if (parent) { - parent.on('save', function() { - _this.emit('save', _this); - _this.constructor.emit('save', _this); - }); - - parent.on('isNew', function(val) { - _this.isNew = val; - _this.emit('isNew', val); - _this.constructor.emit('isNew', val); - }); - } - }; - _embedded.prototype = Object.create(Subdocument.prototype); - _embedded.prototype.$__setSchema(schema); - _embedded.prototype.constructor = _embedded; - _embedded.schema = schema; - _embedded.$isSingleNested = true; - _embedded.events = new EventEmitter(); - _embedded.prototype.toBSON = function() { - return this.toObject(internalToObjectOptions); - }; - - // apply methods - for (const i in schema.methods) { - _embedded.prototype[i] = schema.methods[i]; - } - - // apply statics - for (const i in schema.statics) { - _embedded[i] = schema.statics[i]; - } - - for (const i in EventEmitter.prototype) { - _embedded[i] = EventEmitter.prototype[i]; - } - - return _embedded; -} - -/*! - * Special case for when users use a common location schema to represent - * locations for use with $geoWithin. - * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/ - * - * @param {Object} val - * @api private - */ - -Embedded.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) { - return { $geometry: this.castForQuery(val.$geometry) }; -}; - -/*! - * ignore - */ - -Embedded.prototype.$conditionalHandlers.$near = -Embedded.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near; - -Embedded.prototype.$conditionalHandlers.$within = -Embedded.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within; - -Embedded.prototype.$conditionalHandlers.$geoIntersects = - geospatial.cast$geoIntersects; - -Embedded.prototype.$conditionalHandlers.$minDistance = castToNumber; -Embedded.prototype.$conditionalHandlers.$maxDistance = castToNumber; - -Embedded.prototype.$conditionalHandlers.$exists = $exists; - -/** - * Casts contents - * - * @param {Object} value - * @api private - */ - -Embedded.prototype.cast = function(val, doc, init, priorVal) { - if (val && val.$isSingleNested) { - return val; - } - - if (val != null && (typeof val !== 'object' || Array.isArray(val))) { - throw new ObjectExpectedError(this.path, val); - } - - let Constructor = this.caster; - const discriminatorKey = Constructor.schema.options.discriminatorKey; - if (val != null && - Constructor.discriminators && - typeof val[discriminatorKey] === 'string') { - if (Constructor.discriminators[val[discriminatorKey]]) { - Constructor = Constructor.discriminators[val[discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, val[discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - let subdoc; - - // Only pull relevant selected paths and pull out the base path - const parentSelected = get(doc, '$__.selected', {}); - const path = this.path; - const selected = Object.keys(parentSelected).reduce((obj, key) => { - if (key.startsWith(path + '.')) { - obj[key.substr(path.length + 1)] = parentSelected[key]; - } - return obj; - }, {}); - - if (init) { - subdoc = new Constructor(void 0, selected, doc); - subdoc.init(val); - } else { - if (Object.keys(val).length === 0) { - return new Constructor({}, selected, doc); - } - - return new Constructor(val, selected, doc, undefined, { priorDoc: priorVal }); - } - - return subdoc; -}; - -/** - * Casts contents for query - * - * @param {string} [$conditional] optional query operator (like `$eq` or `$in`) - * @param {any} value - * @api private - */ - -Embedded.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error('Can\'t use ' + $conditional); - } - return handler.call(this, val); - } - val = $conditional; - if (val == null) { - return val; - } - - if (this.options.runSetters) { - val = this._applySetters(val); - } - - let Constructor = this.caster; - const discriminatorKey = Constructor.schema.options.discriminatorKey; - if (val != null && - Constructor.discriminators && - typeof val[discriminatorKey] === 'string') { - if (Constructor.discriminators[val[discriminatorKey]]) { - Constructor = Constructor.discriminators[val[discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, val[discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - try { - val = new Constructor(val); - } catch (error) { - // Make sure we always wrap in a CastError (gh-6803) - if (!(error instanceof CastError)) { - throw new CastError('Embedded', val, this.path, error); - } - throw error; - } - return val; -}; - -/** - * Async validation on this single nested doc. - * - * @api private - */ - -Embedded.prototype.doValidate = function(value, fn, scope, options) { - let Constructor = this.caster; - const discriminatorKey = Constructor.schema.options.discriminatorKey; - if (value != null && - Constructor.discriminators && - typeof value[discriminatorKey] === 'string') { - if (Constructor.discriminators[value[discriminatorKey]]) { - Constructor = Constructor.discriminators[value[discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, value[discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - if (options && options.skipSchemaValidators) { - if (!(value instanceof Constructor)) { - value = new Constructor(value, null, scope); - } - - return value.validate(fn); - } - - SchemaType.prototype.doValidate.call(this, value, function(error) { - if (error) { - return fn(error); - } - if (!value) { - return fn(null); - } - - value.validate(fn); - }, scope); -}; - -/** - * Synchronously validate this single nested doc - * - * @api private - */ - -Embedded.prototype.doValidateSync = function(value, scope, options) { - if (!options || !options.skipSchemaValidators) { - const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope); - if (schemaTypeError) { - return schemaTypeError; - } - } - if (!value) { - return; - } - return value.validateSync(); -}; - -/** - * Adds a discriminator to this property - * - * @param {String} name - * @param {Schema} schema fields to add to the schema for instances of this sub-class - * @api public - */ - -Embedded.prototype.discriminator = function(name, schema) { - discriminator(this.caster, name, schema); - - this.caster.discriminators[name] = _createConstructor(schema); - - return this.caster.discriminators[name]; -}; diff --git a/node_modules/mongoose/lib/schema/index.js b/node_modules/mongoose/lib/schema/index.js deleted file mode 100644 index 183a6e98461aeb433fbc25ae73cffc51cc684ce5..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/index.js +++ /dev/null @@ -1,36 +0,0 @@ - -/*! - * Module exports. - */ - -'use strict'; - -exports.String = require('./string'); - -exports.Number = require('./number'); - -exports.Boolean = require('./boolean'); - -exports.DocumentArray = require('./documentarray'); - -exports.Embedded = require('./embedded'); - -exports.Array = require('./array'); - -exports.Buffer = require('./buffer'); - -exports.Date = require('./date'); - -exports.ObjectId = require('./objectid'); - -exports.Mixed = require('./mixed'); - -exports.Decimal128 = exports.Decimal = require('./decimal128'); - -exports.Map = require('./map'); - -// alias - -exports.Oid = exports.ObjectId; -exports.Object = exports.Mixed; -exports.Bool = exports.Boolean; diff --git a/node_modules/mongoose/lib/schema/map.js b/node_modules/mongoose/lib/schema/map.js deleted file mode 100644 index f50ac4de7b696f0773427ab2a02241e0d2f514f4..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/map.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -const MongooseMap = require('../types/map'); -const SchemaType = require('../schematype'); - -/*! - * ignore - */ - -class Map extends SchemaType { - constructor(key, options) { - super(key, options, 'Map'); - this.$isSchemaMap = true; - } - - cast(val, doc, init) { - if (val instanceof MongooseMap) { - return val; - } - - if (init) { - const map = new MongooseMap({}, this.path, doc, this.$__schemaType); - - for (const key of Object.keys(val)) { - map.$init(key, this.$__schemaType.cast(val[key], doc, true)); - } - - return map; - } - - return new MongooseMap(val, this.path, doc, this.$__schemaType); - } -} - -module.exports = Map; diff --git a/node_modules/mongoose/lib/schema/mixed.js b/node_modules/mongoose/lib/schema/mixed.js deleted file mode 100644 index 672cc51916799aeb76678d0d0599e4ee975a8b43..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/mixed.js +++ /dev/null @@ -1,105 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const SchemaType = require('../schematype'); -const symbols = require('./symbols'); -const utils = require('../utils'); - -/** - * Mixed SchemaType constructor. - * - * @param {String} path - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function Mixed(path, options) { - if (options && options.default) { - const def = options.default; - if (Array.isArray(def) && def.length === 0) { - // make sure empty array defaults are handled - options.default = Array; - } else if (!options.shared && utils.isObject(def) && Object.keys(def).length === 0) { - // prevent odd "shared" objects between documents - options.default = function() { - return {}; - }; - } - } - - SchemaType.call(this, path, options, 'Mixed'); - - this[symbols.schemaMixedSymbol] = true; -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -Mixed.schemaName = 'Mixed'; - -/*! - * Inherits from SchemaType. - */ -Mixed.prototype = Object.create(SchemaType.prototype); -Mixed.prototype.constructor = Mixed; - -/** - * Attaches a getter for all Mixed paths. - * - * ####Example: - * - * // Hide the 'hidden' path - * mongoose.Schema.Mixed.get(v => Object.assign({}, v, { hidden: null })); - * - * const Model = mongoose.model('Test', new Schema({ test: {} })); - * new Model({ test: { hidden: 'Secret!' } }).test.hidden; // null - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - -Mixed.get = SchemaType.get; - -/** - * Casts `val` for Mixed. - * - * _this is a no-op_ - * - * @param {Object} value to cast - * @api private - */ - -Mixed.prototype.cast = function(val) { - return val; -}; - -/** - * Casts contents for queries. - * - * @param {String} $cond - * @param {any} [val] - * @api private - */ - -Mixed.prototype.castForQuery = function($cond, val) { - if (arguments.length === 2) { - return val; - } - return $cond; -}; - -/*! - * Module exports. - */ - -module.exports = Mixed; diff --git a/node_modules/mongoose/lib/schema/number.js b/node_modules/mongoose/lib/schema/number.js deleted file mode 100644 index 49dc63119e4655970fe4bba1499e3af01a54c24f..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/number.js +++ /dev/null @@ -1,361 +0,0 @@ -'use strict'; - -/*! - * Module requirements. - */ - -const MongooseError = require('../error'); -const SchemaType = require('../schematype'); -const castNumber = require('../cast/number'); -const handleBitwiseOperator = require('./operators/bitwise'); -const utils = require('../utils'); - -const CastError = SchemaType.CastError; -let Document; - -/** - * Number SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaNumber(key, options) { - SchemaType.call(this, key, options, 'Number'); -} - -/** - * Attaches a getter for all Number instances. - * - * ####Example: - * - * // Make all numbers round down - * mongoose.Number.get(function(v) { return Math.floor(v); }); - * - * const Model = mongoose.model('Test', new Schema({ test: Number })); - * new Model({ test: 3.14 }).test; // 3 - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - -SchemaNumber.get = SchemaType.get; - -/*! - * ignore - */ - -SchemaNumber._cast = castNumber; - -/** - * Get/set the function used to cast arbitrary values to numbers. - * - * ####Example: - * - * // Make Mongoose cast empty strings '' to 0 for paths declared as numbers - * const original = mongoose.Number.cast(); - * mongoose.Number.cast(v => { - * if (v === '') { return 0; } - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Number.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - -SchemaNumber.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (typeof v !== 'number') { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaNumber.schemaName = 'Number'; - -/*! - * Inherits from SchemaType. - */ -SchemaNumber.prototype = Object.create(SchemaType.prototype); -SchemaNumber.prototype.constructor = SchemaNumber; - -/*! - * ignore - */ - -SchemaNumber._checkRequired = v => typeof v === 'number' || v instanceof Number; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaNumber.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - return this.constructor._checkRequired(value); -}; - -/** - * Sets a minimum number validator. - * - * ####Example: - * - * var s = new Schema({ n: { type: Number, min: 10 }) - * var M = db.model('M', s) - * var m = new M({ n: 9 }) - * m.save(function (err) { - * console.error(err) // validator error - * m.n = 10; - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MIN} token which will be replaced with the invalid value - * var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; - * var schema = new Schema({ n: { type: Number, min: min }) - * var M = mongoose.model('Measurement', schema); - * var s= new M({ n: 4 }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). - * }) - * - * @param {Number} value minimum number - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaNumber.prototype.min = function(value, message) { - if (this.minValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.minValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.Number.min; - msg = msg.replace(/{MIN}/, value); - this.validators.push({ - validator: this.minValidator = function(v) { - return v == null || v >= value; - }, - message: msg, - type: 'min', - min: value - }); - } - - return this; -}; - -/** - * Sets a maximum number validator. - * - * ####Example: - * - * var s = new Schema({ n: { type: Number, max: 10 }) - * var M = db.model('M', s) - * var m = new M({ n: 11 }) - * m.save(function (err) { - * console.error(err) // validator error - * m.n = 10; - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAX} token which will be replaced with the invalid value - * var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; - * var schema = new Schema({ n: { type: Number, max: max }) - * var M = mongoose.model('Measurement', schema); - * var s= new M({ n: 4 }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). - * }) - * - * @param {Number} maximum number - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaNumber.prototype.max = function(value, message) { - if (this.maxValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.maxValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.Number.max; - msg = msg.replace(/{MAX}/, value); - this.validators.push({ - validator: this.maxValidator = function(v) { - return v == null || v <= value; - }, - message: msg, - type: 'max', - max: value - }); - } - - return this; -}; - -/** - * Casts to number - * - * @param {Object} value value to cast - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api private - */ - -SchemaNumber.prototype.cast = function(value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (value === null || value === undefined) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (typeof value === 'number') { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('number', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - const ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - const val = value && typeof value._id !== 'undefined' ? - value._id : // documents - value; - - try { - return this.constructor.cast()(val); - } catch (err) { - throw new CastError('number', val, this.path); - } -}; - -/*! - * ignore - */ - -function handleSingle(val) { - return this.cast(val); -} - -function handleArray(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.cast(val)]; - } - return val.map(function(m) { - return _this.cast(m); - }); -} - -SchemaNumber.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $bitsAllClear: handleBitwiseOperator, - $bitsAnyClear: handleBitwiseOperator, - $bitsAllSet: handleBitwiseOperator, - $bitsAnySet: handleBitwiseOperator, - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle, - $mod: handleArray - }); - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaNumber.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new CastError('Can\'t use ' + $conditional + ' with Number.'); - } - return handler.call(this, val); - } - val = this._castForQuery($conditional); - return val; -}; - -/*! - * Module exports. - */ - -module.exports = SchemaNumber; diff --git a/node_modules/mongoose/lib/schema/objectid.js b/node_modules/mongoose/lib/schema/objectid.js deleted file mode 100644 index efe1eee7f7199cf7288395d965394f3b0fe8c227..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/objectid.js +++ /dev/null @@ -1,282 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const castObjectId = require('../cast/objectid'); -const SchemaType = require('../schematype'); -const oid = require('../types/objectid'); -const utils = require('../utils'); - -const CastError = SchemaType.CastError; -let Document; - -/** - * ObjectId SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function ObjectId(key, options) { - const isKeyHexStr = typeof key === 'string' && key.length === 24 && /^[a-f0-9]+$/i.test(key); - const suppressWarning = options && options.suppressWarning; - if ((isKeyHexStr || typeof key === 'undefined') && !suppressWarning) { - console.warn('mongoose: To create a new ObjectId please try ' + - '`Mongoose.Types.ObjectId` instead of using ' + - '`Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if ' + - 'you\'re trying to create a hex char path in your schema.'); - console.trace(); - } - SchemaType.call(this, key, options, 'ObjectID'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -ObjectId.schemaName = 'ObjectId'; - -/*! - * Inherits from SchemaType. - */ -ObjectId.prototype = Object.create(SchemaType.prototype); -ObjectId.prototype.constructor = ObjectId; - -/** - * Attaches a getter for all ObjectId instances - * - * ####Example: - * - * // Always convert to string when getting an ObjectId - * mongoose.ObjectId.get(v => v.toString()); - * - * const Model = mongoose.model('Test', new Schema({})); - * typeof (new Model({})._id); // 'string' - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - -ObjectId.get = SchemaType.get; - -/** - * Adds an auto-generated ObjectId default if turnOn is true. - * @param {Boolean} turnOn auto generated ObjectId defaults - * @api public - * @return {SchemaType} this - */ - -ObjectId.prototype.auto = function(turnOn) { - if (turnOn) { - this.default(defaultId); - this.set(resetId); - } - - return this; -}; - -/*! - * ignore - */ - -ObjectId._checkRequired = v => v instanceof oid; - -/*! - * ignore - */ - -ObjectId._cast = castObjectId; - -/** - * Get/set the function used to cast arbitrary values to objectids. - * - * ####Example: - * - * // Make Mongoose only try to cast length 24 strings. By default, any 12 - * // char string is a valid ObjectId. - * const original = mongoose.ObjectId.cast(); - * mongoose.ObjectId.cast(v => { - * assert.ok(typeof v !== 'string' || v.length === 24); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.ObjectId.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - -ObjectId.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (!(v instanceof oid)) { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ str: { type: String, required: true } }); - * new M({ str: '' }).validateSync(); // `null`, validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -ObjectId.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -ObjectId.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - return this.constructor._checkRequired(value); -}; - -/** - * Casts to ObjectId - * - * @param {Object} value - * @param {Object} doc - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - -ObjectId.prototype.cast = function(value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (value === null || value === undefined) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (value instanceof oid) { - return value; - } else if ((value.constructor.name || '').toLowerCase() === 'objectid') { - return new oid(value.toHexString()); - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('ObjectId', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - let ret = value; - if (!doc.$__.populated || - !doc.$__.populated[path] || - !doc.$__.populated[path].options || - !doc.$__.populated[path].options.options || - !doc.$__.populated[path].options.options.lean) { - ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - } - - return ret; - } - - try { - return this.constructor.cast()(value); - } catch (error) { - throw new CastError('ObjectId', value, this.path); - } -}; - -/*! - * ignore - */ - -function handleSingle(val) { - return this.cast(val); -} - -ObjectId.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle - }); - -/*! - * ignore - */ - -function defaultId() { - return new oid(); -} - -defaultId.$runBeforeSetters = true; - -function resetId(v) { - Document || (Document = require('./../document')); - - if (this instanceof Document) { - if (v === void 0) { - const _v = new oid; - this.$__._id = _v; - return _v; - } - - this.$__._id = v; - } - - return v; -} - -/*! - * Module exports. - */ - -module.exports = ObjectId; diff --git a/node_modules/mongoose/lib/schema/operators/bitwise.js b/node_modules/mongoose/lib/schema/operators/bitwise.js deleted file mode 100644 index 07e18cd0cbfa6ee17f4a4b1255ca354e6b6f2678..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/operators/bitwise.js +++ /dev/null @@ -1,38 +0,0 @@ -/*! - * Module requirements. - */ - -'use strict'; - -const CastError = require('../../error/cast'); - -/*! - * ignore - */ - -function handleBitwiseOperator(val) { - const _this = this; - if (Array.isArray(val)) { - return val.map(function(v) { - return _castNumber(_this.path, v); - }); - } else if (Buffer.isBuffer(val)) { - return val; - } - // Assume trying to cast to number - return _castNumber(_this.path, val); -} - -/*! - * ignore - */ - -function _castNumber(path, num) { - const v = Number(num); - if (isNaN(v)) { - throw new CastError('number', num, path); - } - return v; -} - -module.exports = handleBitwiseOperator; diff --git a/node_modules/mongoose/lib/schema/operators/exists.js b/node_modules/mongoose/lib/schema/operators/exists.js deleted file mode 100644 index 916b4cbf6ffbd50d91f501bb07fbfb5c4aff270d..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/operators/exists.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -const castBoolean = require('../../cast/boolean'); - -/*! - * ignore - */ - -module.exports = function(val) { - const path = this != null ? this.path : null; - return castBoolean(val, path); -}; diff --git a/node_modules/mongoose/lib/schema/operators/geospatial.js b/node_modules/mongoose/lib/schema/operators/geospatial.js deleted file mode 100644 index 73e38f81c9c12b8479d94b1f920b3751f8c8a54f..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/operators/geospatial.js +++ /dev/null @@ -1,102 +0,0 @@ -/*! - * Module requirements. - */ - -'use strict'; - -const castArraysOfNumbers = require('./helpers').castArraysOfNumbers; -const castToNumber = require('./helpers').castToNumber; - -/*! - * ignore - */ - -exports.cast$geoIntersects = cast$geoIntersects; -exports.cast$near = cast$near; -exports.cast$within = cast$within; - -function cast$near(val) { - const SchemaArray = require('../array'); - - if (Array.isArray(val)) { - castArraysOfNumbers(val, this); - return val; - } - - _castMinMaxDistance(this, val); - - if (val && val.$geometry) { - return cast$geometry(val, this); - } - - return SchemaArray.prototype.castForQuery.call(this, val); -} - -function cast$geometry(val, self) { - switch (val.$geometry.type) { - case 'Polygon': - case 'LineString': - case 'Point': - castArraysOfNumbers(val.$geometry.coordinates, self); - break; - default: - // ignore unknowns - break; - } - - _castMinMaxDistance(self, val); - - return val; -} - -function cast$within(val) { - _castMinMaxDistance(this, val); - - if (val.$box || val.$polygon) { - const type = val.$box ? '$box' : '$polygon'; - val[type].forEach(arr => { - if (!Array.isArray(arr)) { - const msg = 'Invalid $within $box argument. ' - + 'Expected an array, received ' + arr; - throw new TypeError(msg); - } - arr.forEach((v, i) => { - arr[i] = castToNumber.call(this, v); - }); - }); - } else if (val.$center || val.$centerSphere) { - const type = val.$center ? '$center' : '$centerSphere'; - val[type].forEach((item, i) => { - if (Array.isArray(item)) { - item.forEach((v, j) => { - item[j] = castToNumber.call(this, v); - }); - } else { - val[type][i] = castToNumber.call(this, item); - } - }); - } else if (val.$geometry) { - cast$geometry(val, this); - } - - return val; -} - -function cast$geoIntersects(val) { - const geo = val.$geometry; - if (!geo) { - return; - } - - cast$geometry(val, this); - return val; -} - -function _castMinMaxDistance(self, val) { - if (val.$maxDistance) { - val.$maxDistance = castToNumber.call(self, val.$maxDistance); - } - if (val.$minDistance) { - val.$minDistance = castToNumber.call(self, val.$minDistance); - } -} diff --git a/node_modules/mongoose/lib/schema/operators/helpers.js b/node_modules/mongoose/lib/schema/operators/helpers.js deleted file mode 100644 index a17951cd72e36447286a2059f1c2f8280670bc1d..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/operators/helpers.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -/*! - * Module requirements. - */ - -const SchemaNumber = require('../number'); - -/*! - * @ignore - */ - -exports.castToNumber = castToNumber; -exports.castArraysOfNumbers = castArraysOfNumbers; - -/*! - * @ignore - */ - -function castToNumber(val) { - return SchemaNumber.cast()(val); -} - -function castArraysOfNumbers(arr, self) { - arr.forEach(function(v, i) { - if (Array.isArray(v)) { - castArraysOfNumbers(v, self); - } else { - arr[i] = castToNumber.call(self, v); - } - }); -} diff --git a/node_modules/mongoose/lib/schema/operators/text.js b/node_modules/mongoose/lib/schema/operators/text.js deleted file mode 100644 index 4b959168dd933ec4a58ff3c21d199974622237c0..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/operators/text.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const CastError = require('../../error/cast'); -const castBoolean = require('../../cast/boolean'); -const castString = require('../../cast/string'); - -/*! - * Casts val to an object suitable for `$text`. Throws an error if the object - * can't be casted. - * - * @param {Any} val value to cast - * @param {String} [path] path to associate with any errors that occured - * @return {Object} casted object - * @see https://docs.mongodb.com/manual/reference/operator/query/text/ - * @api private - */ - -module.exports = function(val, path) { - if (val == null || typeof val !== 'object') { - throw new CastError('$text', val, path); - } - - if (val.$search != null) { - val.$search = castString(val.$search, path + '.$search'); - } - if (val.$language != null) { - val.$language = castString(val.$language, path + '.$language'); - } - if (val.$caseSensitive != null) { - val.$caseSensitive = castBoolean(val.$caseSensitive, - path + '.$castSensitive'); - } - if (val.$diacriticSensitive != null) { - val.$diacriticSensitive = castBoolean(val.$diacriticSensitive, - path + '.$diacriticSensitive'); - } - - return val; -}; diff --git a/node_modules/mongoose/lib/schema/operators/type.js b/node_modules/mongoose/lib/schema/operators/type.js deleted file mode 100644 index c8e391ac2ae45aefc475b385685f277a4b5ad57f..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/operators/type.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function(val) { - if (typeof val !== 'number' && typeof val !== 'string') { - throw new Error('$type parameter must be number or string'); - } - - return val; -}; diff --git a/node_modules/mongoose/lib/schema/string.js b/node_modules/mongoose/lib/schema/string.js deleted file mode 100644 index b93e824edd002757386cdddac7c24f5be5ebd365..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/string.js +++ /dev/null @@ -1,604 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const SchemaType = require('../schematype'); -const CastError = SchemaType.CastError; -const MongooseError = require('../error'); -const castString = require('../cast/string'); -const utils = require('../utils'); - -let Document; - -/** - * String SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaString(key, options) { - this.enumValues = []; - this.regExp = null; - SchemaType.call(this, key, options, 'String'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaString.schemaName = 'String'; - -/*! - * Inherits from SchemaType. - */ -SchemaString.prototype = Object.create(SchemaType.prototype); -SchemaString.prototype.constructor = SchemaString; - -/*! - * ignore - */ - -SchemaString._cast = castString; - -/** - * Get/set the function used to cast arbitrary values to strings. - * - * ####Example: - * - * // Throw an error if you pass in an object. Normally, Mongoose allows - * // objects with custom `toString()` functions. - * const original = mongoose.Schema.Types.String.cast(); - * mongoose.Schema.Types.String.cast(v => { - * assert.ok(v == null || typeof v !== 'object'); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Schema.Types.String.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - -SchemaString.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (v != null && typeof v !== 'string') { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/** - * Attaches a getter for all String instances. - * - * ####Example: - * - * // Make all numbers round down - * mongoose.Schema.String.get(v => v.toLowerCase()); - * - * const Model = mongoose.model('Test', new Schema({ test: String })); - * new Model({ test: 'FOO' }).test; // 'foo' - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - -SchemaString.get = SchemaType.get; - -/*! - * ignore - */ - -SchemaString._checkRequired = v => (v instanceof String || typeof v === 'string') && v.length; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ str: { type: String, required: true } }); - * new M({ str: '' }).validateSync(); // `null`, validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaString.checkRequired = SchemaType.checkRequired; - -/** - * Adds an enum validator - * - * ####Example: - * - * var states = ['opening', 'open', 'closing', 'closed'] - * var s = new Schema({ state: { type: String, enum: states }}) - * var M = db.model('M', s) - * var m = new M({ state: 'invalid' }) - * m.save(function (err) { - * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. - * m.state = 'open' - * m.save(callback) // success - * }) - * - * // or with custom error messages - * var enum = { - * values: ['opening', 'open', 'closing', 'closed'], - * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' - * } - * var s = new Schema({ state: { type: String, enum: enum }) - * var M = db.model('M', s) - * var m = new M({ state: 'invalid' }) - * m.save(function (err) { - * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` - * m.state = 'open' - * m.save(callback) // success - * }) - * - * @param {String|Object} [args...] enumeration values - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.enum = function() { - if (this.enumValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.enumValidator; - }, this); - this.enumValidator = false; - } - - if (arguments[0] === void 0 || arguments[0] === false) { - return this; - } - - let values; - let errorMessage; - - if (utils.isObject(arguments[0])) { - values = arguments[0].values; - errorMessage = arguments[0].message; - } else { - values = arguments; - errorMessage = MongooseError.messages.String.enum; - } - - for (let i = 0; i < values.length; i++) { - if (undefined !== values[i]) { - this.enumValues.push(this.cast(values[i])); - } - } - - const vals = this.enumValues; - this.enumValidator = function(v) { - return undefined === v || ~vals.indexOf(v); - }; - this.validators.push({ - validator: this.enumValidator, - message: errorMessage, - type: 'enum', - enumValues: vals - }); - - return this; -}; - -/** - * Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). - * - * ####Example: - * - * var s = new Schema({ email: { type: String, lowercase: true }}) - * var M = db.model('M', s); - * var m = new M({ email: 'SomeEmail@example.COM' }); - * console.log(m.email) // someemail@example.com - * M.find({ email: 'SomeEmail@example.com' }); // Queries by 'someemail@example.com' - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.lowercase = function(shouldApply) { - if (arguments.length > 0 && !shouldApply) { - return this; - } - return this.set(function(v, self) { - if (typeof v !== 'string') { - v = self.cast(v); - } - if (v) { - return v.toLowerCase(); - } - return v; - }); -}; - -/** - * Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). - * - * ####Example: - * - * var s = new Schema({ caps: { type: String, uppercase: true }}) - * var M = db.model('M', s); - * var m = new M({ caps: 'an example' }); - * console.log(m.caps) // AN EXAMPLE - * M.find({ caps: 'an example' }) // Matches documents where caps = 'AN EXAMPLE' - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.uppercase = function(shouldApply) { - if (arguments.length > 0 && !shouldApply) { - return this; - } - return this.set(function(v, self) { - if (typeof v !== 'string') { - v = self.cast(v); - } - if (v) { - return v.toUpperCase(); - } - return v; - }); -}; - -/** - * Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). - * - * The string value will be trimmed when set. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, trim: true }}) - * var M = db.model('M', s) - * var string = ' some name ' - * console.log(string.length) // 11 - * var m = new M({ name: string }) - * console.log(m.name.length) // 9 - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.trim = function(shouldTrim) { - if (arguments.length > 0 && !shouldTrim) { - return this; - } - return this.set(function(v, self) { - if (typeof v !== 'string') { - v = self.cast(v); - } - if (v) { - return v.trim(); - } - return v; - }); -}; - -/** - * Sets a minimum length validator. - * - * ####Example: - * - * var schema = new Schema({ postalCode: { type: String, minlength: 5 }) - * var Address = db.model('Address', schema) - * var address = new Address({ postalCode: '9512' }) - * address.save(function (err) { - * console.error(err) // validator error - * address.postalCode = '95125'; - * address.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length - * var minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).']; - * var schema = new Schema({ postalCode: { type: String, minlength: minlength }) - * var Address = mongoose.model('Address', schema); - * var address = new Address({ postalCode: '9512' }); - * address.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5). - * }) - * - * @param {Number} value minimum string length - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.minlength = function(value, message) { - if (this.minlengthValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.minlengthValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.String.minlength; - msg = msg.replace(/{MINLENGTH}/, value); - this.validators.push({ - validator: this.minlengthValidator = function(v) { - return v === null || v.length >= value; - }, - message: msg, - type: 'minlength', - minlength: value - }); - } - - return this; -}; - -/** - * Sets a maximum length validator. - * - * ####Example: - * - * var schema = new Schema({ postalCode: { type: String, maxlength: 9 }) - * var Address = db.model('Address', schema) - * var address = new Address({ postalCode: '9512512345' }) - * address.save(function (err) { - * console.error(err) // validator error - * address.postalCode = '95125'; - * address.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length - * var maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).']; - * var schema = new Schema({ postalCode: { type: String, maxlength: maxlength }) - * var Address = mongoose.model('Address', schema); - * var address = new Address({ postalCode: '9512512345' }); - * address.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9). - * }) - * - * @param {Number} value maximum string length - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.maxlength = function(value, message) { - if (this.maxlengthValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.maxlengthValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.String.maxlength; - msg = msg.replace(/{MAXLENGTH}/, value); - this.validators.push({ - validator: this.maxlengthValidator = function(v) { - return v === null || v.length <= value; - }, - message: msg, - type: 'maxlength', - maxlength: value - }); - } - - return this; -}; - -/** - * Sets a regexp validator. - * - * Any value that does not pass `regExp`.test(val) will fail validation. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, match: /^a/ }}) - * var M = db.model('M', s) - * var m = new M({ name: 'I am invalid' }) - * m.validate(function (err) { - * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)." - * m.name = 'apples' - * m.validate(function (err) { - * assert.ok(err) // success - * }) - * }) - * - * // using a custom error message - * var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; - * var s = new Schema({ file: { type: String, match: match }}) - * var M = db.model('M', s); - * var m = new M({ file: 'invalid' }); - * m.validate(function (err) { - * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)" - * }) - * - * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also. - * - * var s = new Schema({ name: { type: String, match: /^a/, required: true }}) - * - * @param {RegExp} regExp regular expression to test against - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.match = function match(regExp, message) { - // yes, we allow multiple match validators - - const msg = message || MongooseError.messages.String.match; - - const matchValidator = function(v) { - if (!regExp) { - return false; - } - - const ret = ((v != null && v !== '') - ? regExp.test(v) - : true); - return ret; - }; - - this.validators.push({ - validator: matchValidator, - message: msg, - type: 'regexp', - regexp: regExp - }); - return this; -}; - -/** - * Check if the given value satisfies the `required` validator. The value is - * considered valid if it is a string (that is, not `null` or `undefined`) and - * has positive length. The `required` validator **will** fail for empty - * strings. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -SchemaString.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - return this.constructor._checkRequired(value, doc); -}; - -/** - * Casts to String - * - * @api private - */ - -SchemaString.prototype.cast = function(value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (value === null || value === undefined) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (typeof value === 'string') { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('string', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - const ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - try { - return this.constructor.cast()(value); - } catch (error) { - throw new CastError('string', value, this.path); - } -}; - -/*! - * ignore - */ - -function handleSingle(val) { - return this.castForQuery(val); -} - -function handleArray(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.castForQuery(val)]; - } - return val.map(function(m) { - return _this.castForQuery(m); - }); -} - -SchemaString.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $all: handleArray, - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle, - $options: handleSingle, - $regex: handleSingle, - $not: handleSingle - }); - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [val] - * @api private - */ - -SchemaString.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error('Can\'t use ' + $conditional + ' with String.'); - } - return handler.call(this, val); - } - val = $conditional; - if (Object.prototype.toString.call(val) === '[object RegExp]') { - return val; - } - - return this._castForQuery(val); -}; - -/*! - * Module exports. - */ - -module.exports = SchemaString; diff --git a/node_modules/mongoose/lib/schema/symbols.js b/node_modules/mongoose/lib/schema/symbols.js deleted file mode 100644 index 08d1d27ed60abb23a3732c5fe8cefc4dfc1254e4..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schema/symbols.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -exports.schemaMixedSymbol = Symbol.for('mongoose:schema_mixed'); - -exports.builtInMiddleware = Symbol.for('mongoose:built-in-middleware'); \ No newline at end of file diff --git a/node_modules/mongoose/lib/schematype.js b/node_modules/mongoose/lib/schematype.js deleted file mode 100644 index a85ade2fb9ac3ffcdcca648793ad5b1ac1f6c729..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/schematype.js +++ /dev/null @@ -1,1295 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./error'); -const $exists = require('./schema/operators/exists'); -const $type = require('./schema/operators/type'); -const get = require('./helpers/get'); -const immediate = require('./helpers/immediate'); -const utils = require('./utils'); -const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol; - -const CastError = MongooseError.CastError; -const ValidatorError = MongooseError.ValidatorError; - -/** - * SchemaType constructor. Do **not** instantiate `SchemaType` directly. - * Mongoose converts your schema paths into SchemaTypes automatically. - * - * ####Example: - * - * const schema = new Schema({ name: String }); - * schema.path('name') instanceof SchemaType; // true - * - * @param {String} path - * @param {Object} [options] - * @param {String} [instance] - * @api public - */ - -function SchemaType(path, options, instance) { - this.path = path; - this.instance = instance; - this.validators = []; - this.getters = this.constructor.hasOwnProperty('getters') ? - this.constructor.getters.slice() : - []; - this.setters = []; - this.options = options; - this._index = null; - this.selected; - - for (const prop in options) { - if (this[prop] && typeof this[prop] === 'function') { - // { unique: true, index: true } - if (prop === 'index' && this._index) { - continue; - } - - const val = options[prop]; - // Special case so we don't screw up array defaults, see gh-5780 - if (prop === 'default') { - this.default(val); - continue; - } - - const opts = Array.isArray(val) ? val : [val]; - - this[prop].apply(this, opts); - } - } - - Object.defineProperty(this, '$$context', { - enumerable: false, - configurable: false, - writable: true, - value: null - }); -} - -/** - * Get/set the function used to cast arbitrary values to this type. - * - * ####Example: - * - * // Disallow `null` for numbers, and don't try to cast any values to - * // numbers, so even strings like '123' will cause a CastError. - * mongoose.Number.cast(function(v) { - * assert.ok(v === undefined || typeof v === 'number'); - * return v; - * }); - * - * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed - * @return {Function} - * @static - * @receiver SchemaType - * @function cast - * @api public - */ - -SchemaType.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => v; - } - this._cast = caster; - - return this._cast; -}; - -/** - * Attaches a getter for all instances of this schema type. - * - * ####Example: - * - * // Make all numbers round down - * mongoose.Number.get(function(v) { return Math.floor(v); }); - * - * @param {Function} getter - * @return {this} - * @static - * @receiver SchemaType - * @function get - * @api public - */ - -SchemaType.get = function(getter) { - this.getters = this.hasOwnProperty('getters') ? this.getters : []; - this.getters.push(getter); -}; - -/** - * Sets a default value for this SchemaType. - * - * ####Example: - * - * var schema = new Schema({ n: { type: Number, default: 10 }) - * var M = db.model('M', schema) - * var m = new M; - * console.log(m.n) // 10 - * - * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. - * - * ####Example: - * - * // values are cast: - * var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }}) - * var M = db.model('M', schema) - * var m = new M; - * console.log(m.aNumber) // 4.815162342 - * - * // default unique objects for Mixed types: - * var schema = new Schema({ mixed: Schema.Types.Mixed }); - * schema.path('mixed').default(function () { - * return {}; - * }); - * - * // if we don't use a function to return object literals for Mixed defaults, - * // each document will receive a reference to the same object literal creating - * // a "shared" object instance: - * var schema = new Schema({ mixed: Schema.Types.Mixed }); - * schema.path('mixed').default({}); - * var M = db.model('M', schema); - * var m1 = new M; - * m1.mixed.added = 1; - * console.log(m1.mixed); // { added: 1 } - * var m2 = new M; - * console.log(m2.mixed); // { added: 1 } - * - * @param {Function|any} val the default value - * @return {defaultValue} - * @api public - */ - -SchemaType.prototype.default = function(val) { - if (arguments.length === 1) { - if (val === void 0) { - this.defaultValue = void 0; - return void 0; - } - this.defaultValue = val; - return this.defaultValue; - } else if (arguments.length > 1) { - this.defaultValue = utils.args(arguments); - } - return this.defaultValue; -}; - -/** - * Declares the index options for this schematype. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, index: true }) - * var s = new Schema({ loc: { type: [Number], index: 'hashed' }) - * var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) - * var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) - * var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) - * Schema.path('my.path').index(true); - * Schema.path('my.date').index({ expires: 60 }); - * Schema.path('my.path').index({ unique: true, sparse: true }); - * - * ####NOTE: - * - * _Indexes are created [in the background](https://docs.mongodb.com/manual/core/index-creation/#index-creation-background) - * by default. If `background` is set to `false`, MongoDB will not execute any - * read/write operations you send until the index build. - * Specify `background: false` to override Mongoose's default._ - * - * @param {Object|Boolean|String} options - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.index = function(options) { - this._index = options; - utils.expires(this._index); - return this; -}; - -/** - * Declares an unique index. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, unique: true }}); - * Schema.path('name').index({ unique: true }); - * - * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ - * - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.unique = function(bool) { - if (this._index === false) { - if (!bool) { - return; - } - throw new Error('Path "' + this.path + '" may not have `index` set to ' + - 'false and `unique` set to true'); - } - if (this._index == null || this._index === true) { - this._index = {}; - } else if (typeof this._index === 'string') { - this._index = {type: this._index}; - } - - this._index.unique = bool; - return this; -}; - -/** - * Declares a full text index. - * - * ###Example: - * - * var s = new Schema({name : {type: String, text : true }) - * Schema.path('name').index({text : true}); - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.text = function(bool) { - if (this._index === null || this._index === undefined || - typeof this._index === 'boolean') { - this._index = {}; - } else if (typeof this._index === 'string') { - this._index = {type: this._index}; - } - - this._index.text = bool; - return this; -}; - -/** - * Declares a sparse index. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, sparse: true }) - * Schema.path('name').index({ sparse: true }); - * - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.sparse = function(bool) { - if (this._index === null || this._index === undefined || - typeof this._index === 'boolean') { - this._index = {}; - } else if (typeof this._index === 'string') { - this._index = {type: this._index}; - } - - this._index.sparse = bool; - return this; -}; - -/** - * Adds a setter to this schematype. - * - * ####Example: - * - * function capitalize (val) { - * if (typeof val !== 'string') val = ''; - * return val.charAt(0).toUpperCase() + val.substring(1); - * } - * - * // defining within the schema - * var s = new Schema({ name: { type: String, set: capitalize }}); - * - * // or with the SchemaType - * var s = new Schema({ name: String }) - * s.path('name').set(capitalize); - * - * Setters allow you to transform the data before it gets to the raw mongodb - * document or query. - * - * Suppose you are implementing user registration for a website. Users provide - * an email and password, which gets saved to mongodb. The email is a string - * that you will want to normalize to lower case, in order to avoid one email - * having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. - * - * You can set up email lower case normalization easily via a Mongoose setter. - * - * function toLower(v) { - * return v.toLowerCase(); - * } - * - * var UserSchema = new Schema({ - * email: { type: String, set: toLower } - * }); - * - * var User = db.model('User', UserSchema); - * - * var user = new User({email: 'AVENUE@Q.COM'}); - * console.log(user.email); // 'avenue@q.com' - * - * // or - * var user = new User(); - * user.email = 'Avenue@Q.com'; - * console.log(user.email); // 'avenue@q.com' - * User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com' - * - * As you can see above, setters allow you to transform the data before it - * stored in MongoDB, or before executing a query. - * - * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ - * - * new Schema({ email: { type: String, lowercase: true }}) - * - * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. - * - * function inspector (val, schematype) { - * if (schematype.options.required) { - * return schematype.path + ' is required'; - * } else { - * return val; - * } - * } - * - * var VirusSchema = new Schema({ - * name: { type: String, required: true, set: inspector }, - * taxonomy: { type: String, set: inspector } - * }) - * - * var Virus = db.model('Virus', VirusSchema); - * var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); - * - * console.log(v.name); // name is required - * console.log(v.taxonomy); // Parvovirinae - * - * You can also use setters to modify other properties on the document. If - * you're setting a property `name` on a document, the setter will run with - * `this` as the document. Be careful, in mongoose 5 setters will also run - * when querying by `name` with `this` as the query. - * - * ```javascript - * const nameSchema = new Schema({ name: String, keywords: [String] }); - * nameSchema.path('name').set(function(v) { - * // Need to check if `this` is a document, because in mongoose 5 - * // setters will also run on queries, in which case `this` will be a - * // mongoose query object. - * if (this instanceof Document && v != null) { - * this.keywords = v.split(' '); - * } - * return v; - * }); - * ``` - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.set = function(fn) { - if (typeof fn !== 'function') { - throw new TypeError('A setter must be a function.'); - } - this.setters.push(fn); - return this; -}; - -/** - * Adds a getter to this schematype. - * - * ####Example: - * - * function dob (val) { - * if (!val) return val; - * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); - * } - * - * // defining within the schema - * var s = new Schema({ born: { type: Date, get: dob }) - * - * // or by retreiving its SchemaType - * var s = new Schema({ born: Date }) - * s.path('born').get(dob) - * - * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. - * - * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: - * - * function obfuscate (cc) { - * return '****-****-****-' + cc.slice(cc.length-4, cc.length); - * } - * - * var AccountSchema = new Schema({ - * creditCardNumber: { type: String, get: obfuscate } - * }); - * - * var Account = db.model('Account', AccountSchema); - * - * Account.findById(id, function (err, found) { - * console.log(found.creditCardNumber); // '****-****-****-1234' - * }); - * - * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. - * - * function inspector (val, schematype) { - * if (schematype.options.required) { - * return schematype.path + ' is required'; - * } else { - * return schematype.path + ' is not'; - * } - * } - * - * var VirusSchema = new Schema({ - * name: { type: String, required: true, get: inspector }, - * taxonomy: { type: String, get: inspector } - * }) - * - * var Virus = db.model('Virus', VirusSchema); - * - * Virus.findById(id, function (err, virus) { - * console.log(virus.name); // name is required - * console.log(virus.taxonomy); // taxonomy is not - * }) - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.get = function(fn) { - if (typeof fn !== 'function') { - throw new TypeError('A getter must be a function.'); - } - this.getters.push(fn); - return this; -}; - -/** - * Adds validator(s) for this document path. - * - * Validators always receive the value to validate as their first argument and - * must return `Boolean`. Returning `false` or throwing an error means - * validation failed. - * - * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. - * - * ####Examples: - * - * // make sure every value is equal to "something" - * function validator (val) { - * return val == 'something'; - * } - * new Schema({ name: { type: String, validate: validator }}); - * - * // with a custom error message - * - * var custom = [validator, 'Uh oh, {PATH} does not equal "something".'] - * new Schema({ name: { type: String, validate: custom }}); - * - * // adding many validators at a time - * - * var many = [ - * { validator: validator, msg: 'uh oh' } - * , { validator: anotherValidator, msg: 'failed' } - * ] - * new Schema({ name: { type: String, validate: many }}); - * - * // or utilizing SchemaType methods directly: - * - * var schema = new Schema({ name: 'string' }); - * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); - * - * ####Error message templates: - * - * From the examples above, you may have noticed that error messages support - * basic templating. There are a few other template keywords besides `{PATH}` - * and `{VALUE}` too. To find out more, details are available - * [here](#error_messages_MongooseError.messages). - * - * If Mongoose's built-in error message templating isn't enough, Mongoose - * supports setting the `message` property to a function. - * - * schema.path('name').validate({ - * validator: function() { return v.length > 5; }, - * // `errors['name']` will be "name must have length 5, got 'foo'" - * message: function(props) { - * return `${props.path} must have length 5, got '${props.value}'`; - * } - * }); - * - * To bypass Mongoose's error messages and just copy the error message that - * the validator throws, do this: - * - * schema.path('name').validate({ - * validator: function() { throw new Error('Oops!'); }, - * // `errors['name']` will be "Oops!" - * message: function(props) { return props.reason.message; } - * }); - * - * ####Asynchronous validation: - * - * Mongoose supports validators that return a promise. A validator that returns - * a promise is called an _async validator_. Async validators run in - * parallel, and `validate()` will wait until all async validators have settled. - * - * schema.path('name').validate({ - * validator: function (value) { - * return new Promise(function (resolve, reject) { - * resolve(false); // validation failed - * }); - * } - * }); - * - * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. - * - * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). - * - * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. - * - * var conn = mongoose.createConnection(..); - * conn.on('error', handleError); - * - * var Product = conn.model('Product', yourSchema); - * var dvd = new Product(..); - * dvd.save(); // emits error on the `conn` above - * - * If you want to handle these errors at the Model level, add an `error` - * listener to your Model as shown below. - * - * // registering an error listener on the Model lets us handle errors more locally - * Product.on('error', handleError); - * - * @param {RegExp|Function|Object} obj validator function, or hash describing options - * @param {Function} [obj.validator] validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns falsy (except `undefined`) or throws an error, validation fails. - * @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string - * @param {Boolean} [obj.propsParameter=false] If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators. - * @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string - * @param {String} [type] optional validator type - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.validate = function(obj, message, type) { - if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') { - let properties; - if (message instanceof Object && !type) { - properties = utils.clone(message); - if (!properties.message) { - properties.message = properties.msg; - } - properties.validator = obj; - properties.type = properties.type || 'user defined'; - } else { - if (!message) { - message = MongooseError.messages.general.default; - } - if (!type) { - type = 'user defined'; - } - properties = {message: message, type: type, validator: obj}; - } - this.validators.push(properties); - return this; - } - - let i; - let length; - let arg; - - for (i = 0, length = arguments.length; i < length; i++) { - arg = arguments[i]; - if (!utils.isPOJO(arg)) { - const msg = 'Invalid validator. Received (' + typeof arg + ') ' - + arg - + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; - - throw new Error(msg); - } - this.validate(arg.validator, arg); - } - - return this; -}; - -/** - * Adds a required validator to this SchemaType. The validator gets added - * to the front of this SchemaType's validators array using `unshift()`. - * - * ####Example: - * - * var s = new Schema({ born: { type: Date, required: true }) - * - * // or with custom error message - * - * var s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) - * - * // or with a function - * - * var s = new Schema({ - * userId: ObjectId, - * username: { - * type: String, - * required: function() { return this.userId != null; } - * } - * }) - * - * // or with a function and a custom message - * var s = new Schema({ - * userId: ObjectId, - * username: { - * type: String, - * required: [ - * function() { return this.userId != null; }, - * 'username is required if id is specified' - * ] - * } - * }) - * - * // or through the path API - * - * Schema.path('name').required(true); - * - * // with custom error messaging - * - * Schema.path('name').required(true, 'grrr :( '); - * - * // or make a path conditionally required based on a function - * var isOver18 = function() { return this.age >= 18; }; - * Schema.path('voterRegistrationId').required(isOver18); - * - * The required validator uses the SchemaType's `checkRequired` function to - * determine whether a given value satisfies the required validator. By default, - * a value satisfies the required validator if `val != null` (that is, if - * the value is not null nor undefined). However, most built-in mongoose schema - * types override the default `checkRequired` function: - * - * @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object - * @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean - * @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties. - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @see SchemaArray#checkRequired #schema_array_SchemaArray.checkRequired - * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired - * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer.schemaName - * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min - * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto - * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired - * @api public - */ - -SchemaType.prototype.required = function(required, message) { - let customOptions = {}; - if (typeof required === 'object') { - customOptions = required; - message = customOptions.message || message; - required = required.isRequired; - } - - if (required === false) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.requiredValidator; - }, this); - - this.isRequired = false; - delete this.originalRequiredValue; - return this; - } - - const _this = this; - this.isRequired = true; - - this.requiredValidator = function(v) { - const cachedRequired = get(this, '$__.cachedRequired'); - - // no validation when this path wasn't selected in the query. - if (cachedRequired != null && !this.isSelected(_this.path) && !this.isModified(_this.path)) { - return true; - } - - // `$cachedRequired` gets set in `_evaluateRequiredFunctions()` so we - // don't call required functions multiple times in one validate call - // See gh-6801 - if (cachedRequired != null && _this.path in cachedRequired) { - const res = cachedRequired[_this.path] ? - _this.checkRequired(v, this) : - true; - delete cachedRequired[_this.path]; - return res; - } else if (typeof required === 'function') { - return required.apply(this) ? _this.checkRequired(v, this) : true; - } - - return _this.checkRequired(v, this); - }; - this.originalRequiredValue = required; - - if (typeof required === 'string') { - message = required; - required = undefined; - } - - const msg = message || MongooseError.messages.general.required; - this.validators.unshift(Object.assign({}, customOptions, { - validator: this.requiredValidator, - message: msg, - type: 'required' - })); - - return this; -}; - -/** - * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html) - * looks at to determine the foreign collection it should query. - * - * ####Example: - * const userSchema = new Schema({ name: String }); - * const User = mongoose.model('User', userSchema); - * - * const postSchema = new Schema({ user: mongoose.ObjectId }); - * postSchema.path('user').ref('User'); // By model name - * postSchema.path('user').ref(User); // Can pass the model as well - * - * // Or you can just declare the `ref` inline in your schema - * const postSchema2 = new Schema({ - * user: { type: mongoose.ObjectId, ref: User } - * }); - * - * @param {String|Model|Function} ref either a model name, a [Model](https://mongoosejs.com/docs/models.html), or a function that returns a model name or model. - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.ref = function(ref) { - this.options.ref = ref; - return this; -}; - -/** - * Gets the default value - * - * @param {Object} scope the scope which callback are executed - * @param {Boolean} init - * @api private - */ - -SchemaType.prototype.getDefault = function(scope, init) { - let ret = typeof this.defaultValue === 'function' - ? this.defaultValue.call(scope) - : this.defaultValue; - - if (ret !== null && ret !== undefined) { - if (typeof ret === 'object' && (!this.options || !this.options.shared)) { - ret = utils.clone(ret); - } - - const casted = this.cast(ret, scope, init); - if (casted && casted.$isSingleNested) { - casted.$parent = scope; - } - return casted; - } - return ret; -}; - -/*! - * Applies setters without casting - * - * @api private - */ - -SchemaType.prototype._applySetters = function(value, scope, init, priorVal) { - let v = value; - const setters = this.setters; - let len = setters.length; - const caster = this.caster; - - while (len--) { - v = setters[len].call(scope, v, this); - } - - if (Array.isArray(v) && caster && caster.setters) { - const newVal = []; - for (let i = 0; i < v.length; i++) { - newVal.push(caster.applySetters(v[i], scope, init, priorVal)); - } - v = newVal; - } - - return v; -}; - -/** - * Applies setters - * - * @param {Object} value - * @param {Object} scope - * @param {Boolean} init - * @api private - */ - -SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) { - let v = this._applySetters(value, scope, init, priorVal, options); - - if (v == null) { - return v; - } - - // do not cast until all setters are applied #665 - v = this.cast(v, scope, init, priorVal, options); - - return v; -}; - -/** - * Applies getters to a value - * - * @param {Object} value - * @param {Object} scope - * @api private - */ - -SchemaType.prototype.applyGetters = function(value, scope) { - let v = value; - const getters = this.getters; - const len = getters.length; - - if (len === 0) { - return v; - } - - for (let i = 0; i < len; ++i) { - v = getters[i].call(scope, v, this); - } - - return v; -}; - -/** - * Sets default `select()` behavior for this path. - * - * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. - * - * ####Example: - * - * T = db.model('T', new Schema({ x: { type: String, select: true }})); - * T.find(..); // field x will always be selected .. - * // .. unless overridden; - * T.find().select('-x').exec(callback); - * - * @param {Boolean} val - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.select = function select(val) { - this.selected = !!val; - return this; -}; - -/** - * Performs a validation of `value` using the validators declared for this SchemaType. - * - * @param {any} value - * @param {Function} callback - * @param {Object} scope - * @api private - */ - -SchemaType.prototype.doValidate = function(value, fn, scope) { - let err = false; - const path = this.path; - let count = this.validators.length; - - if (!count) { - return fn(null); - } - - const validate = function(ok, validatorProperties) { - if (err) { - return; - } - if (ok === undefined || ok) { - if (--count <= 0) { - immediate(function() { - fn(null); - }); - } - } else { - const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; - err = new ErrorConstructor(validatorProperties); - err[validatorErrorSymbol] = true; - immediate(function() { - fn(err); - }); - } - }; - - const _this = this; - this.validators.forEach(function(v) { - if (err) { - return; - } - - const validator = v.validator; - let ok; - - const validatorProperties = utils.clone(v); - validatorProperties.path = path; - validatorProperties.value = value; - - if (validator instanceof RegExp) { - validate(validator.test(value), validatorProperties); - } else if (typeof validator === 'function') { - if (value === undefined && validator !== _this.requiredValidator) { - validate(true, validatorProperties); - return; - } - if (validatorProperties.isAsync) { - asyncValidate(validator, scope, value, validatorProperties, validate); - } else { - try { - if (validatorProperties.propsParameter) { - ok = validator.call(scope, value, validatorProperties); - } else { - ok = validator.call(scope, value); - } - } catch (error) { - ok = false; - validatorProperties.reason = error; - if (error.message) { - validatorProperties.message = error.message; - } - } - if (ok != null && typeof ok.then === 'function') { - ok.then( - function(ok) { validate(ok, validatorProperties); }, - function(error) { - validatorProperties.reason = error; - ok = false; - validate(ok, validatorProperties); - }); - } else { - validate(ok, validatorProperties); - } - } - } - }); -}; - -/*! - * Handle async validators - */ - -function asyncValidate(validator, scope, value, props, cb) { - let called = false; - const returnVal = validator.call(scope, value, function(ok, customMsg) { - if (called) { - return; - } - called = true; - if (customMsg) { - props.message = customMsg; - } - cb(ok, props); - }); - if (typeof returnVal === 'boolean') { - called = true; - cb(returnVal, props); - } else if (returnVal && typeof returnVal.then === 'function') { - // Promise - returnVal.then( - function(ok) { - if (called) { - return; - } - called = true; - cb(ok, props); - }, - function(error) { - if (called) { - return; - } - called = true; - - props.reason = error; - cb(false, props); - }); - } -} - -/** - * Performs a validation of `value` using the validators declared for this SchemaType. - * - * ####Note: - * - * This method ignores the asynchronous validators. - * - * @param {any} value - * @param {Object} scope - * @return {MongooseError|undefined} - * @api private - */ - -SchemaType.prototype.doValidateSync = function(value, scope) { - let err = null; - const path = this.path; - const count = this.validators.length; - - if (!count) { - return null; - } - - const validate = function(ok, validatorProperties) { - if (err) { - return; - } - if (ok !== undefined && !ok) { - const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; - err = new ErrorConstructor(validatorProperties); - err[validatorErrorSymbol] = true; - } - }; - - let validators = this.validators; - if (value === void 0) { - if (this.validators.length > 0 && this.validators[0].type === 'required') { - validators = [this.validators[0]]; - } else { - return null; - } - } - - validators.forEach(function(v) { - if (err) { - return; - } - - const validator = v.validator; - const validatorProperties = utils.clone(v); - validatorProperties.path = path; - validatorProperties.value = value; - let ok; - - // Skip any explicit async validators. Validators that return a promise - // will still run, but won't trigger any errors. - if (validator.isAsync) { - return; - } - - if (validator instanceof RegExp) { - validate(validator.test(value), validatorProperties); - } else if (typeof validator === 'function') { - try { - if (validatorProperties.propsParameter) { - ok = validator.call(scope, value, validatorProperties); - } else { - ok = validator.call(scope, value); - } - } catch (error) { - ok = false; - validatorProperties.reason = error; - } - - // Skip any validators that return a promise, we can't handle those - // synchronously - if (ok != null && typeof ok.then === 'function') { - return; - } - validate(ok, validatorProperties); - } - }); - - return err; -}; - -/** - * Determines if value is a valid Reference. - * - * @param {SchemaType} self - * @param {Object} value - * @param {Document} doc - * @param {Boolean} init - * @return {Boolean} - * @api private - */ - -SchemaType._isRef = function(self, value, doc, init) { - // fast path - let ref = init && self.options && (self.options.ref || self.options.refPath); - - if (!ref && doc && doc.$__ != null) { - // checks for - // - this populated with adhoc model and no ref was set in schema OR - // - setting / pushing values after population - const path = doc.$__fullPath(self.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - ref = owner.populated(path); - } - - if (ref) { - if (value == null) { - return true; - } - if (!Buffer.isBuffer(value) && // buffers are objects too - value._bsontype !== 'Binary' // raw binary value from the db - && utils.isObject(value) // might have deselected _id in population query - ) { - return true; - } - } - - return false; -}; - -/*! - * ignore - */ - -function handleSingle(val) { - return this.castForQuery(val); -} - -/*! - * ignore - */ - -function handleArray(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.castForQuery(val)]; - } - return val.map(function(m) { - return _this.castForQuery(m); - }); -} - -/*! - * Just like handleArray, except also allows `[]` because surprisingly - * `$in: [1, []]` works fine - */ - -function handle$in(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.castForQuery(val)]; - } - return val.map(function(m) { - if (Array.isArray(m) && m.length === 0) { - return m; - } - return _this.castForQuery(m); - }); -} - -/*! - * ignore - */ - -SchemaType.prototype.$conditionalHandlers = { - $all: handleArray, - $eq: handleSingle, - $in: handle$in, - $ne: handleSingle, - $nin: handleArray, - $exists: $exists, - $type: $type -}; - -/*! - * Wraps `castForQuery` to handle context - */ - -SchemaType.prototype.castForQueryWrapper = function(params) { - this.$$context = params.context; - if ('$conditional' in params) { - return this.castForQuery(params.$conditional, params.val); - } - if (params.$skipQueryCastForUpdate) { - return this._castForQuery(params.val); - } - return this.castForQuery(params.val); -}; - -/** - * Cast the given value with the given optional query operator. - * - * @param {String} [$conditional] query operator, like `$eq` or `$in` - * @param {any} val - * @api private - */ - -SchemaType.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error('Can\'t use ' + $conditional); - } - return handler.call(this, val); - } - val = $conditional; - return this._castForQuery(val); -}; - -/*! - * Internal switch for runSetters - * - * @api private - */ - -SchemaType.prototype._castForQuery = function(val) { - return this.applySetters(val, this.$$context); -}; - -/** - * Override the function the required validator uses to check whether a value - * passes the `required` check. Override this on the individual SchemaType. - * - * ####Example: - * - * // Use this to allow empty strings to pass the `required` validator - * mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string'); - * - * @param {Function} fn - * @return {Function} - * @static - * @receiver SchemaType - * @function checkRequired - * @api public - */ - -SchemaType.checkRequired = function(fn) { - if (arguments.length > 0) { - this._checkRequired = fn; - } - - return this._checkRequired; -}; - -/** - * Default check for if this path satisfies the `required` validator. - * - * @param {any} val - * @api private - */ - -SchemaType.prototype.checkRequired = function(val) { - return val != null; -}; - -/*! - * Module exports. - */ - -module.exports = exports = SchemaType; - -exports.CastError = CastError; - -exports.ValidatorError = ValidatorError; diff --git a/node_modules/mongoose/lib/statemachine.js b/node_modules/mongoose/lib/statemachine.js deleted file mode 100644 index 7e36dc1ced29351c3e427016e1a3979d3a5970c0..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/statemachine.js +++ /dev/null @@ -1,180 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const utils = require('./utils'); - -/*! - * StateMachine represents a minimal `interface` for the - * constructors it builds via StateMachine.ctor(...). - * - * @api private - */ - -const StateMachine = module.exports = exports = function StateMachine() { -}; - -/*! - * StateMachine.ctor('state1', 'state2', ...) - * A factory method for subclassing StateMachine. - * The arguments are a list of states. For each state, - * the constructor's prototype gets state transition - * methods named after each state. These transition methods - * place their path argument into the given state. - * - * @param {String} state - * @param {String} [state] - * @return {Function} subclass constructor - * @private - */ - -StateMachine.ctor = function() { - const states = utils.args(arguments); - - const ctor = function() { - StateMachine.apply(this, arguments); - this.paths = {}; - this.states = {}; - this.stateNames = states; - - let i = states.length, - state; - - while (i--) { - state = states[i]; - this.states[state] = {}; - } - }; - - ctor.prototype = new StateMachine(); - - states.forEach(function(state) { - // Changes the `path`'s state to `state`. - ctor.prototype[state] = function(path) { - this._changeState(path, state); - }; - }); - - return ctor; -}; - -/*! - * This function is wrapped by the state change functions: - * - * - `require(path)` - * - `modify(path)` - * - `init(path)` - * - * @api private - */ - -StateMachine.prototype._changeState = function _changeState(path, nextState) { - const prevBucket = this.states[this.paths[path]]; - if (prevBucket) delete prevBucket[path]; - - this.paths[path] = nextState; - this.states[nextState][path] = true; -}; - -/*! - * ignore - */ - -StateMachine.prototype.clear = function clear(state) { - const keys = Object.keys(this.states[state]); - let i = keys.length; - let path; - - while (i--) { - path = keys[i]; - delete this.states[state][path]; - delete this.paths[path]; - } -}; - -/*! - * Checks to see if at least one path is in the states passed in via `arguments` - * e.g., this.some('required', 'inited') - * - * @param {String} state that we want to check for. - * @private - */ - -StateMachine.prototype.some = function some() { - const _this = this; - const what = arguments.length ? arguments : this.stateNames; - return Array.prototype.some.call(what, function(state) { - return Object.keys(_this.states[state]).length; - }); -}; - -/*! - * This function builds the functions that get assigned to `forEach` and `map`, - * since both of those methods share a lot of the same logic. - * - * @param {String} iterMethod is either 'forEach' or 'map' - * @return {Function} - * @api private - */ - -StateMachine.prototype._iter = function _iter(iterMethod) { - return function() { - const numArgs = arguments.length; - let states = utils.args(arguments, 0, numArgs - 1); - const callback = arguments[numArgs - 1]; - - if (!states.length) states = this.stateNames; - - const _this = this; - - const paths = states.reduce(function(paths, state) { - return paths.concat(Object.keys(_this.states[state])); - }, []); - - return paths[iterMethod](function(path, i, paths) { - return callback(path, i, paths); - }); - }; -}; - -/*! - * Iterates over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @private - */ - -StateMachine.prototype.forEach = function forEach() { - this.forEach = this._iter('forEach'); - return this.forEach.apply(this, arguments); -}; - -/*! - * Maps over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @return {Array} - * @private - */ - -StateMachine.prototype.map = function map() { - this.map = this._iter('map'); - return this.map.apply(this, arguments); -}; diff --git a/node_modules/mongoose/lib/types/array.js b/node_modules/mongoose/lib/types/array.js deleted file mode 100644 index 26f03a5c1c469f618eae40f3b6a6c546f22690a4..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/types/array.js +++ /dev/null @@ -1,848 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const EmbeddedDocument = require('./embedded'); -const Document = require('../document'); -const ObjectId = require('./objectid'); -const cleanModifiedSubpaths = require('../helpers/document/cleanModifiedSubpaths'); -const get = require('../helpers/get'); -const internalToObjectOptions = require('../options').internalToObjectOptions; -const utils = require('../utils'); -const util = require('util'); - -const isMongooseObject = utils.isMongooseObject; - -/** - * Mongoose Array constructor. - * - * ####NOTE: - * - * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ - * - * @param {Array} values - * @param {String} path - * @param {Document} doc parent document - * @api private - * @inherits Array - * @see http://bit.ly/f6CnZU - */ - -function MongooseArray(values, path, doc) { - const arr = [].concat(values); - - const keysMA = Object.keys(MongooseArray.mixin); - const numKeys = keysMA.length; - for (let i = 0; i < numKeys; ++i) { - arr[keysMA[i]] = MongooseArray.mixin[keysMA[i]]; - } - - arr._path = path; - arr.isMongooseArray = true; - arr.validators = []; - arr._atomics = {}; - arr._schema = void 0; - if (util.inspect.custom) { - arr[util.inspect.custom] = arr.inspect; - } - - // Because doc comes from the context of another function, doc === global - // can happen if there was a null somewhere up the chain (see #3020) - // RB Jun 17, 2015 updated to check for presence of expected paths instead - // to make more proof against unusual node environments - if (doc && doc instanceof Document) { - arr._parent = doc; - arr._schema = doc.schema.path(path); - } - - return arr; -} - -MongooseArray.mixin = { - /*! - * ignore - */ - toBSON: function() { - return this.toObject(internalToObjectOptions); - }, - - /** - * Stores a queue of atomic operations to perform - * - * @property _atomics - * @api private - */ - - _atomics: undefined, - - /** - * Parent owner document - * - * @property _parent - * @api private - * @memberOf MongooseArray - */ - - _parent: undefined, - - /** - * Casts a member based on this arrays schema. - * - * @param {any} value - * @return value the casted value - * @method _cast - * @api private - * @memberOf MongooseArray - */ - - _cast: function(value) { - let populated = false; - let Model; - - if (this._parent) { - populated = this._parent.populated(this._path, true); - } - - if (populated && value !== null && value !== undefined) { - // cast to the populated Models schema - Model = populated.options.model || populated.options.Model; - - // only objects are permitted so we can safely assume that - // non-objects are to be interpreted as _id - if (Buffer.isBuffer(value) || - value instanceof ObjectId || !utils.isObject(value)) { - value = {_id: value}; - } - - // gh-2399 - // we should cast model only when it's not a discriminator - const isDisc = value.schema && value.schema.discriminatorMapping && - value.schema.discriminatorMapping.key !== undefined; - if (!isDisc) { - value = new Model(value); - } - return this._schema.caster.applySetters(value, this._parent, true); - } - - return this._schema.caster.applySetters(value, this._parent, false); - }, - - /** - * Marks this array as modified. - * - * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) - * - * @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array - * @param {String} embeddedPath the path which changed in the embeddedDoc - * @method _markModified - * @api private - * @memberOf MongooseArray - */ - - _markModified: function(elem, embeddedPath) { - const parent = this._parent; - let dirtyPath; - - if (parent) { - dirtyPath = this._path; - - if (arguments.length) { - if (embeddedPath != null) { - // an embedded doc bubbled up the change - dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath; - } else { - // directly set an index - dirtyPath = dirtyPath + '.' + elem; - } - } - - parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent); - } - - return this; - }, - - /** - * Register an atomic operation with the parent. - * - * @param {Array} op operation - * @param {any} val - * @method _registerAtomic - * @api private - * @memberOf MongooseArray - */ - - _registerAtomic: function(op, val) { - if (op === '$set') { - // $set takes precedence over all other ops. - // mark entire array modified. - this._atomics = {$set: val}; - return this; - } - - const atomics = this._atomics; - - // reset pop/shift after save - if (op === '$pop' && !('$pop' in atomics)) { - const _this = this; - this._parent.once('save', function() { - _this._popped = _this._shifted = null; - }); - } - - // check for impossible $atomic combos (Mongo denies more than one - // $atomic op on a single path - if (this._atomics.$set || - Object.keys(atomics).length && !(op in atomics)) { - // a different op was previously registered. - // save the entire thing. - this._atomics = {$set: this}; - return this; - } - - let selector; - - if (op === '$pullAll' || op === '$addToSet') { - atomics[op] || (atomics[op] = []); - atomics[op] = atomics[op].concat(val); - } else if (op === '$pullDocs') { - const pullOp = atomics['$pull'] || (atomics['$pull'] = {}); - if (val[0] instanceof EmbeddedDocument) { - selector = pullOp['$or'] || (pullOp['$or'] = []); - Array.prototype.push.apply(selector, val.map(function(v) { - return v.toObject({transform: false, virtuals: false}); - })); - } else { - selector = pullOp['_id'] || (pullOp['_id'] = {$in: []}); - selector['$in'] = selector['$in'].concat(val); - } - } else if (op === '$push') { - atomics.$push = atomics.$push || { $each: [] }; - atomics.$push.$each = atomics.$push.$each.concat(val); - } else { - atomics[op] = val; - } - - return this; - }, - - /** - * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. - * - * If no atomics exist, we return all array values after conversion. - * - * @return {Array} - * @method $__getAtomics - * @memberOf MongooseArray - * @instance - * @api private - */ - - $__getAtomics: function() { - const ret = []; - const keys = Object.keys(this._atomics); - let i = keys.length; - - const opts = Object.assign({}, internalToObjectOptions, { _isNested: true }); - - if (i === 0) { - ret[0] = ['$set', this.toObject(opts)]; - return ret; - } - - while (i--) { - const op = keys[i]; - let val = this._atomics[op]; - - // the atomic values which are arrays are not MongooseArrays. we - // need to convert their elements as if they were MongooseArrays - // to handle populated arrays versus DocumentArrays properly. - if (isMongooseObject(val)) { - val = val.toObject(opts); - } else if (Array.isArray(val)) { - val = this.toObject.call(val, opts); - } else if (val != null && Array.isArray(val.$each)) { - val.$each = this.toObject.call(val.$each, opts); - } else if (val.valueOf) { - val = val.valueOf(); - } - - if (op === '$addToSet') { - val = {$each: val}; - } - - ret.push([op, val]); - } - - return ret; - }, - - /** - * Returns the number of pending atomic operations to send to the db for this array. - * - * @api private - * @return {Number} - * @method hasAtomics - * @memberOf MongooseArray - */ - - hasAtomics: function hasAtomics() { - if (!(this._atomics && this._atomics.constructor.name === 'Object')) { - return 0; - } - - return Object.keys(this._atomics).length; - }, - - /** - * Internal helper for .map() - * - * @api private - * @return {Number} - * @method _mapCast - * @memberOf MongooseArray - */ - _mapCast: function(val, index) { - return this._cast(val, this.length + index); - }, - - /** - * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. - * - * @param {Object} [args...] - * @api public - * @method push - * @memberOf MongooseArray - */ - - push: function() { - _checkManualPopulation(this, arguments); - let values = [].map.call(arguments, this._mapCast, this); - values = this._schema.applySetters(values, this._parent, undefined, - undefined, { skipDocumentArrayCast: true }); - const ret = [].push.apply(this, values); - - this._registerAtomic('$push', values); - this._markModified(); - return ret; - }, - - /** - * Pushes items to the array non-atomically. - * - * ####NOTE: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @param {any} [args...] - * @api public - * @method nonAtomicPush - * @memberOf MongooseArray - */ - - nonAtomicPush: function() { - const values = [].map.call(arguments, this._mapCast, this); - const ret = [].push.apply(this, values); - this._registerAtomic('$set', this); - this._markModified(); - return ret; - }, - - /** - * Pops the array atomically at most one time per document `save()`. - * - * #### NOTE: - * - * _Calling this mulitple times on an array before saving sends the same command as calling it once._ - * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ - * - * doc.array = [1,2,3]; - * - * var popped = doc.array.$pop(); - * console.log(popped); // 3 - * console.log(doc.array); // [1,2] - * - * // no affect - * popped = doc.array.$pop(); - * console.log(doc.array); // [1,2] - * - * doc.save(function (err) { - * if (err) return handleError(err); - * - * // we saved, now $pop works again - * popped = doc.array.$pop(); - * console.log(popped); // 2 - * console.log(doc.array); // [1] - * }) - * - * @api public - * @method $pop - * @memberOf MongooseArray - * @instance - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop - * @method $pop - * @memberOf MongooseArray - */ - - $pop: function() { - this._registerAtomic('$pop', 1); - this._markModified(); - - // only allow popping once - if (this._popped) { - return; - } - this._popped = true; - - return [].pop.call(this); - }, - - /** - * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. - * - * ####Note: - * - * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @see MongooseArray#$pop #types_array_MongooseArray-%24pop - * @api public - * @method pop - * @memberOf MongooseArray - */ - - pop: function() { - const ret = [].pop.call(this); - this._registerAtomic('$set', this); - this._markModified(); - return ret; - }, - - /** - * Atomically shifts the array at most one time per document `save()`. - * - * ####NOTE: - * - * _Calling this mulitple times on an array before saving sends the same command as calling it once._ - * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ - * - * doc.array = [1,2,3]; - * - * var shifted = doc.array.$shift(); - * console.log(shifted); // 1 - * console.log(doc.array); // [2,3] - * - * // no affect - * shifted = doc.array.$shift(); - * console.log(doc.array); // [2,3] - * - * doc.save(function (err) { - * if (err) return handleError(err); - * - * // we saved, now $shift works again - * shifted = doc.array.$shift(); - * console.log(shifted ); // 2 - * console.log(doc.array); // [3] - * }) - * - * @api public - * @memberOf MongooseArray - * @instance - * @method $shift - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop - */ - - $shift: function $shift() { - this._registerAtomic('$pop', -1); - this._markModified(); - - // only allow shifting once - if (this._shifted) { - return; - } - this._shifted = true; - - return [].shift.call(this); - }, - - /** - * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - * - * ####Example: - * - * doc.array = [2,3]; - * var res = doc.array.shift(); - * console.log(res) // 2 - * console.log(doc.array) // [3] - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method shift - * @memberOf MongooseArray - */ - - shift: function() { - const ret = [].shift.call(this); - this._registerAtomic('$set', this); - this._markModified(); - return ret; - }, - - /** - * Pulls items from the array atomically. Equality is determined by casting - * the provided value to an embedded document and comparing using - * [the `Document.equals()` function.](./api.html#document_Document-equals) - * - * ####Examples: - * - * doc.array.pull(ObjectId) - * doc.array.pull({ _id: 'someId' }) - * doc.array.pull(36) - * doc.array.pull('tag 1', 'tag 2') - * - * To remove a document from a subdocument array we may pass an object with a matching `_id`. - * - * doc.subdocs.push({ _id: 4815162342 }) - * doc.subdocs.pull({ _id: 4815162342 }) // removed - * - * Or we may passing the _id directly and let mongoose take care of it. - * - * doc.subdocs.push({ _id: 4815162342 }) - * doc.subdocs.pull(4815162342); // works - * - * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime. - * - * @param {any} [args...] - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull - * @api public - * @method pull - * @memberOf MongooseArray - */ - - pull: function() { - const values = [].map.call(arguments, this._cast, this); - const cur = this._parent.get(this._path); - let i = cur.length; - let mem; - - while (i--) { - mem = cur[i]; - if (mem instanceof Document) { - const some = values.some(function(v) { - return mem.equals(v); - }); - if (some) { - [].splice.call(cur, i, 1); - } - } else if (~cur.indexOf.call(values, mem)) { - [].splice.call(cur, i, 1); - } - } - - if (values[0] instanceof EmbeddedDocument) { - this._registerAtomic('$pullDocs', values.map(function(v) { - return v._id || v; - })); - } else { - this._registerAtomic('$pullAll', values); - } - - this._markModified(); - - // Might have modified child paths and then pulled, like - // `doc.children[1].name = 'test';` followed by - // `doc.children.remove(doc.children[0]);`. In this case we fall back - // to a `$set` on the whole array. See #3511 - if (cleanModifiedSubpaths(this._parent, this._path) > 0) { - this._registerAtomic('$set', this); - } - - return this; - }, - - /** - * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method splice - * @memberOf MongooseArray - */ - - splice: function splice() { - let ret; - - _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2)); - - if (arguments.length) { - const vals = []; - for (let i = 0; i < arguments.length; ++i) { - vals[i] = i < 2 ? - arguments[i] : - this._cast(arguments[i], arguments[0] + (i - 2)); - } - ret = [].splice.apply(this, vals); - this._registerAtomic('$set', this); - this._markModified(); - cleanModifiedSubpaths(this._parent, this._path); - } - - return ret; - }, - - /** - * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method unshift - * @memberOf MongooseArray - */ - - unshift: function() { - _checkManualPopulation(this, arguments); - - let values = [].map.call(arguments, this._cast, this); - values = this._schema.applySetters(values, this._parent); - [].unshift.apply(this, values); - this._registerAtomic('$set', this); - this._markModified(); - return this.length; - }, - - /** - * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. - * - * ####NOTE: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method sort - * @memberOf MongooseArray - */ - - sort: function() { - const ret = [].sort.apply(this, arguments); - this._registerAtomic('$set', this); - this._markModified(); - return ret; - }, - - /** - * Adds values to the array if not already present. - * - * ####Example: - * - * console.log(doc.array) // [2,3,4] - * var added = doc.array.addToSet(4,5); - * console.log(doc.array) // [2,3,4,5] - * console.log(added) // [5] - * - * @param {any} [args...] - * @return {Array} the values that were added - * @memberOf MongooseArray - * @api public - * @method addToSet - */ - - addToSet: function addToSet() { - _checkManualPopulation(this, arguments); - - let values = [].map.call(arguments, this._mapCast, this); - values = this._schema.applySetters(values, this._parent); - const added = []; - let type = ''; - if (values[0] instanceof EmbeddedDocument) { - type = 'doc'; - } else if (values[0] instanceof Date) { - type = 'date'; - } - - values.forEach(function(v) { - let found; - const val = +v; - switch (type) { - case 'doc': - found = this.some(function(doc) { - return doc.equals(v); - }); - break; - case 'date': - found = this.some(function(d) { - return +d === val; - }); - break; - default: - found = ~this.indexOf(v); - } - - if (!found) { - [].push.call(this, v); - this._registerAtomic('$addToSet', v); - this._markModified(); - [].push.call(added, v); - } - }, this); - - return added; - }, - - /** - * Sets the casted `val` at index `i` and marks the array modified. - * - * ####Example: - * - * // given documents based on the following - * var Doc = mongoose.model('Doc', new Schema({ array: [Number] })); - * - * var doc = new Doc({ array: [2,3,4] }) - * - * console.log(doc.array) // [2,3,4] - * - * doc.array.set(1,"5"); - * console.log(doc.array); // [2,5,4] // properly cast to number - * doc.save() // the change is saved - * - * // VS not using array#set - * doc.array[1] = "5"; - * console.log(doc.array); // [2,"5",4] // no casting - * doc.save() // change is not saved - * - * @return {Array} this - * @api public - * @method set - * @memberOf MongooseArray - */ - - set: function set(i, val) { - const value = this._cast(val, i); - this[i] = value; - this._markModified(i); - return this; - }, - - /** - * Returns a native js Array. - * - * @param {Object} options - * @return {Array} - * @api public - * @method toObject - * @memberOf MongooseArray - */ - - toObject: function(options) { - if (options && options.depopulate) { - options = utils.clone(options); - options._isNested = true; - return this.map(function(doc) { - return doc instanceof Document - ? doc.toObject(options) - : doc; - }); - } - - return this.slice(); - }, - - /** - * Helper for console.log - * - * @api public - * @method inspect - * @memberOf MongooseArray - */ - - inspect: function() { - return JSON.stringify(this); - }, - - /** - * Return the index of `obj` or `-1` if not found. - * - * @param {Object} obj the item to look for - * @return {Number} - * @api public - * @method indexOf - * @memberOf MongooseArray - */ - - indexOf: function indexOf(obj) { - if (obj instanceof ObjectId) { - obj = obj.toString(); - } - for (let i = 0, len = this.length; i < len; ++i) { - if (obj == this[i]) { - return i; - } - } - return -1; - } -}; - -/** - * Alias of [pull](#types_array_MongooseArray-pull) - * - * @see MongooseArray#pull #types_array_MongooseArray-pull - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull - * @api public - * @memberOf MongooseArray - * @instance - * @method remove - */ - -MongooseArray.mixin.remove = MongooseArray.mixin.pull; - -/*! - * ignore - */ - -function _isAllSubdocs(docs, ref) { - if (!ref) { - return false; - } - for (let i = 0; i < docs.length; ++i) { - const arg = docs[i]; - if (arg == null) { - return false; - } - const model = arg.constructor; - if (!(arg instanceof Document) || - (model.modelName !== ref && model.baseModelName !== ref)) { - return false; - } - } - - return true; -} - -/*! - * ignore - */ - -function _checkManualPopulation(arr, docs) { - const ref = get(arr, '_schema.caster.options.ref', null); - if (arr.length === 0 && - docs.length > 0) { - if (_isAllSubdocs(docs, ref)) { - arr._parent.populated(arr._path, [], { model: docs[0].constructor }); - } - } -} - -/*! - * Module exports. - */ - -module.exports = exports = MongooseArray; diff --git a/node_modules/mongoose/lib/types/buffer.js b/node_modules/mongoose/lib/types/buffer.js deleted file mode 100644 index 98fcce02a650eec0cb514c3ea089550595c05158..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/types/buffer.js +++ /dev/null @@ -1,305 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const Binary = require('../driver').get().Binary; -const utils = require('../utils'); -const Buffer = require('safe-buffer').Buffer; - -// Yes this is weird. See https://github.com/feross/safe-buffer/pull/23 -const proto = Buffer.from('').constructor.prototype; - -/** - * Mongoose Buffer constructor. - * - * Values always have to be passed to the constructor to initialize. - * - * @param {Buffer} value - * @param {String} encode - * @param {Number} offset - * @api private - * @inherits Buffer - * @see http://bit.ly/f6CnZU - */ - -function MongooseBuffer(value, encode, offset) { - const length = arguments.length; - let val; - - if (length === 0 || arguments[0] === null || arguments[0] === undefined) { - val = 0; - } else { - val = value; - } - - let encoding; - let path; - let doc; - - if (Array.isArray(encode)) { - // internal casting - path = encode[0]; - doc = encode[1]; - } else { - encoding = encode; - } - - let buf; - if (typeof val === 'number' || val instanceof Number) { - buf = Buffer.alloc(val); - } else { // string, array or object { type: 'Buffer', data: [...] } - buf = Buffer.from(val, encoding, offset); - } - utils.decorate(buf, MongooseBuffer.mixin); - buf.isMongooseBuffer = true; - - // make sure these internal props don't show up in Object.keys() - Object.defineProperties(buf, { - validators: { - value: [], - enumerable: false - }, - _path: { - value: path, - enumerable: false - }, - _parent: { - value: doc, - enumerable: false - } - }); - - if (doc && typeof path === 'string') { - Object.defineProperty(buf, '_schema', { - value: doc.schema.path(path) - }); - } - - buf._subtype = 0; - return buf; -} - -/*! - * Inherit from Buffer. - */ - -// MongooseBuffer.prototype = Buffer.alloc(0); - -MongooseBuffer.mixin = { - - /** - * Parent owner document - * - * @api private - * @property _parent - * @receiver MongooseBuffer - */ - - _parent: undefined, - - /** - * Default subtype for the Binary representing this Buffer - * - * @api private - * @property _subtype - * @receiver MongooseBuffer - */ - - _subtype: undefined, - - /** - * Marks this buffer as modified. - * - * @api private - * @method _markModified - * @receiver MongooseBuffer - */ - - _markModified: function() { - const parent = this._parent; - - if (parent) { - parent.markModified(this._path); - } - return this; - }, - - /** - * Writes the buffer. - * - * @api public - * @method write - * @receiver MongooseBuffer - */ - - write: function() { - const written = proto.write.apply(this, arguments); - - if (written > 0) { - this._markModified(); - } - - return written; - }, - - /** - * Copies the buffer. - * - * ####Note: - * - * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. - * - * @return {Number} The number of bytes copied. - * @param {Buffer} target - * @method copy - * @receiver MongooseBuffer - */ - - copy: function(target) { - const ret = proto.copy.apply(this, arguments); - - if (target && target.isMongooseBuffer) { - target._markModified(); - } - - return ret; - } -}; - -/*! - * Compile other Buffer methods marking this buffer as modified. - */ - -( -// node < 0.5 - ('writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' + - 'writeFloat writeDouble fill ' + - 'utf8Write binaryWrite asciiWrite set ' + - - // node >= 0.5 - 'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' + - 'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' + 'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE') -).split(' ').forEach(function(method) { - if (!proto[method]) { - return; - } - MongooseBuffer.mixin[method] = function() { - const ret = proto[method].apply(this, arguments); - this._markModified(); - return ret; - }; -}); - -/** - * Converts this buffer to its Binary type representation. - * - * ####SubTypes: - * - * var bson = require('bson') - * bson.BSON_BINARY_SUBTYPE_DEFAULT - * bson.BSON_BINARY_SUBTYPE_FUNCTION - * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY - * bson.BSON_BINARY_SUBTYPE_UUID - * bson.BSON_BINARY_SUBTYPE_MD5 - * bson.BSON_BINARY_SUBTYPE_USER_DEFINED - * - * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED); - * - * @see http://bsonspec.org/#/specification - * @param {Hex} [subtype] - * @return {Binary} - * @api public - * @method toObject - * @receiver MongooseBuffer - */ - -MongooseBuffer.mixin.toObject = function(options) { - const subtype = typeof options === 'number' - ? options - : (this._subtype || 0); - return new Binary(this, subtype); -}; - -/** - * Converts this buffer for storage in MongoDB, including subtype - * - * @return {Binary} - * @api public - * @method toBSON - * @receiver MongooseBuffer - */ - -MongooseBuffer.mixin.toBSON = function() { - return new Binary(this, this._subtype || 0); -}; - -/** - * Determines if this buffer is equals to `other` buffer - * - * @param {Buffer} other - * @return {Boolean} - * @method equals - * @receiver MongooseBuffer - */ - -MongooseBuffer.mixin.equals = function(other) { - if (!Buffer.isBuffer(other)) { - return false; - } - - if (this.length !== other.length) { - return false; - } - - for (let i = 0; i < this.length; ++i) { - if (this[i] !== other[i]) { - return false; - } - } - - return true; -}; - -/** - * Sets the subtype option and marks the buffer modified. - * - * ####SubTypes: - * - * var bson = require('bson') - * bson.BSON_BINARY_SUBTYPE_DEFAULT - * bson.BSON_BINARY_SUBTYPE_FUNCTION - * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY - * bson.BSON_BINARY_SUBTYPE_UUID - * bson.BSON_BINARY_SUBTYPE_MD5 - * bson.BSON_BINARY_SUBTYPE_USER_DEFINED - * - * doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID); - * - * @see http://bsonspec.org/#/specification - * @param {Hex} subtype - * @api public - * @method subtype - * @receiver MongooseBuffer - */ - -MongooseBuffer.mixin.subtype = function(subtype) { - if (typeof subtype !== 'number') { - throw new TypeError('Invalid subtype. Expected a number'); - } - - if (this._subtype !== subtype) { - this._markModified(); - } - - this._subtype = subtype; -}; - -/*! - * Module exports. - */ - -MongooseBuffer.Binary = Binary; - -module.exports = MongooseBuffer; diff --git a/node_modules/mongoose/lib/types/decimal128.js b/node_modules/mongoose/lib/types/decimal128.js deleted file mode 100644 index f0bae2a13157349c4b865e6a024f191dd2cccfdd..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/types/decimal128.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * ObjectId type constructor - * - * ####Example - * - * var id = new mongoose.Types.ObjectId; - * - * @constructor ObjectId - */ - -'use strict'; - -module.exports = require('../driver').get().Decimal128; diff --git a/node_modules/mongoose/lib/types/documentarray.js b/node_modules/mongoose/lib/types/documentarray.js deleted file mode 100644 index 223b7be3b956b4c5fc47da8a097bd34e3995f284..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/types/documentarray.js +++ /dev/null @@ -1,360 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const Document = require('../document'); -const MongooseArray = require('./array'); -const ObjectId = require('./objectid'); -const castObjectId = require('../cast/objectid'); -const get = require('../helpers/get'); -const getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue; -const internalToObjectOptions = require('../options').internalToObjectOptions; -const util = require('util'); -const utils = require('../utils'); - -const documentArrayParent = require('../helpers/symbols').documentArrayParent; - -/*! - * ignore - */ - -class CoreMongooseArray extends Array { - get isMongooseArray() { - return true; - } - - remove() {} -} - -/** - * DocumentArray constructor - * - * @param {Array} values - * @param {String} path the path to this array - * @param {Document} doc parent document - * @api private - * @return {MongooseDocumentArray} - * @inherits MongooseArray - * @see http://bit.ly/f6CnZU - */ - -function MongooseDocumentArray(values, path, doc) { - // TODO: replace this with `new CoreMongooseArray().concat()` when we remove - // support for node 4.x and 5.x, see https://i.imgur.com/UAAHk4S.png - const arr = new CoreMongooseArray(); - - const props = { - isMongooseDocumentArray: true, - validators: [], - _atomics: {}, - _schema: void 0, - _handlers: void 0 - }; - - if (Array.isArray(values)) { - if (values instanceof CoreMongooseArray && - values._path === path && - values._parent === doc) { - props._atomics = Object.assign({}, values._atomics); - } - values.forEach(v => { - arr.push(v); - }); - } - arr._path = path; - - // Values always have to be passed to the constructor to initialize, since - // otherwise MongooseArray#push will mark the array as modified to the parent. - const keysMA = Object.keys(MongooseArray.mixin); - let numKeys = keysMA.length; - for (let j = 0; j < numKeys; ++j) { - arr[keysMA[j]] = MongooseArray.mixin[keysMA[j]]; - } - - const keysMDA = Object.keys(MongooseDocumentArray.mixin); - numKeys = keysMDA.length; - for (let i = 0; i < numKeys; ++i) { - arr[keysMDA[i]] = MongooseDocumentArray.mixin[keysMDA[i]]; - } - if (util.inspect.custom) { - props[util.inspect.custom] = arr.inspect; - } - - const keysP = Object.keys(props); - numKeys = keysP.length; - for (let k = 0; k < numKeys; ++k) { - arr[keysP[k]] = props[keysP[k]]; - } - - // Because doc comes from the context of another function, doc === global - // can happen if there was a null somewhere up the chain (see #3020 && #3034) - // RB Jun 17, 2015 updated to check for presence of expected paths instead - // to make more proof against unusual node environments - if (doc && doc instanceof Document) { - arr._parent = doc; - arr._schema = doc.schema.path(path); - - // `schema.path()` doesn't drill into nested arrays properly yet, see - // gh-6398, gh-6602. This is a workaround because nested arrays are - // always plain non-document arrays, so once you get to a document array - // nesting is done. Matryoshka code. - while (get(arr, '_schema.$isMongooseArray') && - !get(arr, '_schema.$isMongooseDocumentArray')) { - arr._schema = arr._schema.casterConstructor; - } - - // Tricky but this may be a document array embedded in a normal array, - // in which case `path` would point to the embedded array. See #6405, #6398 - if (arr._schema && !arr._schema.$isMongooseDocumentArray) { - arr._schema = arr._schema.casterConstructor; - } - - arr._handlers = { - isNew: arr.notify('isNew'), - save: arr.notify('save') - }; - - doc.on('save', arr._handlers.save); - doc.on('isNew', arr._handlers.isNew); - } - - return arr; -} - -/*! - * Inherits from MongooseArray - */ - -MongooseDocumentArray.mixin = { - /*! - * ignore - */ - toBSON: function() { - return this.toObject(internalToObjectOptions); - }, - - /** - * Overrides MongooseArray#cast - * - * @method _cast - * @api private - * @receiver MongooseDocumentArray - */ - - _cast: function(value, index) { - let Constructor = this._schema.casterConstructor; - const isInstance = Constructor.$isMongooseDocumentArray ? - value && value.isMongooseDocumentArray : - value instanceof Constructor; - if (isInstance || - // Hack re: #5001, see #5005 - (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) { - if (!(value[documentArrayParent] && value.__parentArray)) { - // value may have been created using array.create() - value[documentArrayParent] = this._parent; - value.__parentArray = this; - } - value.$setIndex(index); - return value; - } - - if (value === undefined || value === null) { - return null; - } - - // handle cast('string') or cast(ObjectId) etc. - // only objects are permitted so we can safely assume that - // non-objects are to be interpreted as _id - if (Buffer.isBuffer(value) || - value instanceof ObjectId || !utils.isObject(value)) { - value = {_id: value}; - } - - if (value && - Constructor.discriminators && - Constructor.schema && - Constructor.schema.options && - Constructor.schema.options.discriminatorKey) { - if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' && - Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) { - Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, value[Constructor.schema.options.discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - if (Constructor.$isMongooseDocumentArray) { - return Constructor.cast(value, this, undefined, undefined, index); - } - return new Constructor(value, this, undefined, undefined, index); - }, - - /** - * Searches array items for the first document with a matching _id. - * - * ####Example: - * - * var embeddedDoc = m.array.id(some_id); - * - * @return {EmbeddedDocument|null} the subdocument or null if not found. - * @param {ObjectId|String|Number|Buffer} id - * @TODO cast to the _id based on schema for proper comparison - * @method id - * @api public - * @receiver MongooseDocumentArray - */ - - id: function(id) { - let casted; - let sid; - let _id; - - try { - casted = castObjectId(id).toString(); - } catch (e) { - casted = null; - } - - for (let i = 0, l = this.length; i < l; i++) { - if (!this[i]) { - continue; - } - _id = this[i].get('_id'); - - if (_id === null || typeof _id === 'undefined') { - continue; - } else if (_id instanceof Document) { - sid || (sid = String(id)); - if (sid == _id._id) { - return this[i]; - } - } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) { - if (utils.deepEqual(id, _id)) { - return this[i]; - } - } else if (casted == _id) { - return this[i]; - } - } - - return null; - }, - - /** - * Returns a native js Array of plain js objects - * - * ####NOTE: - * - * _Each sub-document is converted to a plain object by calling its `#toObject` method._ - * - * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion - * @return {Array} - * @method toObject - * @api public - * @receiver MongooseDocumentArray - */ - - toObject: function(options) { - return this.map(function(doc) { - try { - return doc.toObject(options); - } catch (e) { - return doc || null; - } - }); - }, - - /** - * Helper for console.log - * - * @method inspect - * @api public - * @receiver MongooseDocumentArray - */ - - inspect: function() { - return this.toObject(); - }, - - /** - * Creates a subdocument casted to this schema. - * - * This is the same subdocument constructor used for casting. - * - * @param {Object} obj the value to cast to this arrays SubDocument schema - * @method create - * @api public - * @receiver MongooseDocumentArray - */ - - create: function(obj) { - let Constructor = this._schema.casterConstructor; - if (obj && - Constructor.discriminators && - Constructor.schema && - Constructor.schema.options && - Constructor.schema.options.discriminatorKey) { - if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' && - Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) { - Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, obj[Constructor.schema.options.discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - return new Constructor(obj); - }, - - /** - * Creates a fn that notifies all child docs of `event`. - * - * @param {String} event - * @return {Function} - * @method notify - * @api private - * @receiver MongooseDocumentArray - */ - - notify: function notify(event) { - const _this = this; - return function notify(val, _arr) { - _arr = _arr || _this; - let i = _arr.length; - while (i--) { - if (_arr[i] == null) { - continue; - } - switch (event) { - // only swap for save event for now, we may change this to all event types later - case 'save': - val = _this[i]; - break; - default: - // NO-OP - break; - } - - if (_arr[i].isMongooseArray) { - notify(val, _arr[i]); - } else if (_arr[i]) { - _arr[i].emit(event, val); - } - } - }; - } - -}; - -/*! - * Module exports. - */ - -module.exports = MongooseDocumentArray; diff --git a/node_modules/mongoose/lib/types/embedded.js b/node_modules/mongoose/lib/types/embedded.js deleted file mode 100644 index 1558c8106eca9ff8dc9cd3c1196071895f4f4545..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/types/embedded.js +++ /dev/null @@ -1,446 +0,0 @@ -/* eslint no-func-assign: 1 */ - -/*! - * Module dependencies. - */ - -'use strict'; - -const Document = require('../document_provider')(); -const EventEmitter = require('events').EventEmitter; -const immediate = require('../helpers/immediate'); -const internalToObjectOptions = require('../options').internalToObjectOptions; -const get = require('../helpers/get'); -const utils = require('../utils'); -const util = require('util'); - -const documentArrayParent = require('../helpers/symbols').documentArrayParent; -const validatorErrorSymbol = require('../helpers/symbols').validatorErrorSymbol; - -/** - * EmbeddedDocument constructor. - * - * @param {Object} obj js object returned from the db - * @param {MongooseDocumentArray} parentArr the parent array of this document - * @param {Boolean} skipId - * @inherits Document - * @api private - */ - -function EmbeddedDocument(obj, parentArr, skipId, fields, index) { - if (parentArr) { - this.__parentArray = parentArr; - this[documentArrayParent] = parentArr._parent; - } else { - this.__parentArray = undefined; - this[documentArrayParent] = undefined; - } - this.$setIndex(index); - this.$isDocumentArrayElement = true; - - Document.call(this, obj, fields, skipId); - - const _this = this; - this.on('isNew', function(val) { - _this.isNew = val; - }); - - _this.on('save', function() { - _this.constructor.emit('save', _this); - }); -} - -/*! - * Inherit from Document - */ -EmbeddedDocument.prototype = Object.create(Document.prototype); -EmbeddedDocument.prototype.constructor = EmbeddedDocument; - -for (const i in EventEmitter.prototype) { - EmbeddedDocument[i] = EventEmitter.prototype[i]; -} - -EmbeddedDocument.prototype.toBSON = function() { - return this.toObject(internalToObjectOptions); -}; - -/*! - * ignore - */ - -EmbeddedDocument.prototype.$setIndex = function(index) { - this.__index = index; - - if (get(this, '$__.validationError', null) != null) { - const keys = Object.keys(this.$__.validationError.errors); - for (const key of keys) { - this.invalidate(key, this.$__.validationError.errors[key]); - } - } -}; - -/** - * Marks the embedded doc modified. - * - * ####Example: - * - * var doc = blogpost.comments.id(hexstring); - * doc.mixed.type = 'changed'; - * doc.markModified('mixed.type'); - * - * @param {String} path the path which changed - * @api public - * @receiver EmbeddedDocument - */ - -EmbeddedDocument.prototype.markModified = function(path) { - this.$__.activePaths.modify(path); - if (!this.__parentArray) { - return; - } - - if (this.isNew) { - // Mark the WHOLE parent array as modified - // if this is a new document (i.e., we are initializing - // a document), - this.__parentArray._markModified(); - } else { - this.__parentArray._markModified(this, path); - } -}; - -/*! - * ignore - */ - -EmbeddedDocument.prototype.populate = function() { - throw new Error('Mongoose does not support calling populate() on nested ' + - 'docs. Instead of `doc.arr[0].populate("path")`, use ' + - '`doc.populate("arr.0.path")`'); -}; - -/** - * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @return {Promise} resolved Promise - * @api private - */ - -EmbeddedDocument.prototype.save = function(options, fn) { - if (typeof options === 'function') { - fn = options; - options = {}; - } - options = options || {}; - - if (!options.suppressWarning) { - console.warn('mongoose: calling `save()` on a subdoc does **not** save ' + - 'the document to MongoDB, it only runs save middleware. ' + - 'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' + - 'if you\'re sure this behavior is right for your app.'); - } - - return utils.promiseOrCallback(fn, cb => { - this.$__save(cb); - }); -}; - -/** - * Used as a stub for middleware - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @method $__save - * @api private - */ - -EmbeddedDocument.prototype.$__save = function(fn) { - return immediate(() => fn(null, this)); -}; - -/*! - * Registers remove event listeners for triggering - * on subdocuments. - * - * @param {EmbeddedDocument} sub - * @api private - */ - -function registerRemoveListener(sub) { - let owner = sub.ownerDocument(); - - function emitRemove() { - owner.removeListener('save', emitRemove); - owner.removeListener('remove', emitRemove); - sub.emit('remove', sub); - sub.constructor.emit('remove', sub); - owner = sub = null; - } - - owner.on('save', emitRemove); - owner.on('remove', emitRemove); -} - -/*! - * no-op for hooks - */ - -EmbeddedDocument.prototype.$__remove = function(cb) { - return cb(null, this); -}; - -/** - * Removes the subdocument from its parent array. - * - * @param {Object} [options] - * @param {Function} [fn] - * @api public - */ - -EmbeddedDocument.prototype.remove = function(options, fn) { - if ( typeof options === 'function' && !fn ) { - fn = options; - options = undefined; - } - if (!this.__parentArray || (options && options.noop)) { - fn && fn(null); - return this; - } - - let _id; - if (!this.willRemove) { - _id = this._doc._id; - if (!_id) { - throw new Error('For your own good, Mongoose does not know ' + - 'how to remove an EmbeddedDocument that has no _id'); - } - this.__parentArray.pull({_id: _id}); - this.willRemove = true; - registerRemoveListener(this); - } - - if (fn) { - fn(null); - } - - return this; -}; - -/** - * Override #update method of parent documents. - * @api private - */ - -EmbeddedDocument.prototype.update = function() { - throw new Error('The #update method is not available on EmbeddedDocuments'); -}; - -/** - * Helper for console.log - * - * @api public - */ - -EmbeddedDocument.prototype.inspect = function() { - return this.toObject({ - transform: false, - virtuals: false, - flattenDecimals: false - }); -}; - -if (util.inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ - - EmbeddedDocument.prototype[util.inspect.custom] = EmbeddedDocument.prototype.inspect; -} - -/** - * Marks a path as invalid, causing validation to fail. - * - * @param {String} path the field to invalidate - * @param {String|Error} err error which states the reason `path` was invalid - * @return {Boolean} - * @api public - */ - -EmbeddedDocument.prototype.invalidate = function(path, err, val) { - Document.prototype.invalidate.call(this, path, err, val); - - if (!this[documentArrayParent]) { - if (err[validatorErrorSymbol] || err.name === 'ValidationError') { - return true; - } - throw err; - } - - const index = this.__index; - if (typeof index !== 'undefined') { - const parentPath = this.__parentArray._path; - const fullPath = [parentPath, index, path].join('.'); - this[documentArrayParent].invalidate(fullPath, err, val); - } - - return true; -}; - -/** - * Marks a path as valid, removing existing validation errors. - * - * @param {String} path the field to mark as valid - * @api private - * @method $markValid - * @receiver EmbeddedDocument - */ - -EmbeddedDocument.prototype.$markValid = function(path) { - if (!this[documentArrayParent]) { - return; - } - - const index = this.__index; - if (typeof index !== 'undefined') { - const parentPath = this.__parentArray._path; - const fullPath = [parentPath, index, path].join('.'); - this[documentArrayParent].$markValid(fullPath); - } -}; - -/*! - * ignore - */ - -EmbeddedDocument.prototype.$ignore = function(path) { - Document.prototype.$ignore.call(this, path); - - if (!this[documentArrayParent]) { - return; - } - - const index = this.__index; - if (typeof index !== 'undefined') { - const parentPath = this.__parentArray._path; - const fullPath = [parentPath, index, path].join('.'); - this[documentArrayParent].$ignore(fullPath); - } -}; - -/** - * Checks if a path is invalid - * - * @param {String} path the field to check - * @api private - * @method $isValid - * @receiver EmbeddedDocument - */ - -EmbeddedDocument.prototype.$isValid = function(path) { - const index = this.__index; - if (typeof index !== 'undefined' && this[documentArrayParent]) { - return !this[documentArrayParent].$__.validationError || - !this[documentArrayParent].$__.validationError.errors[this.$__fullPath(path)]; - } - - return true; -}; - -/** - * Returns the top level document of this sub-document. - * - * @return {Document} - */ - -EmbeddedDocument.prototype.ownerDocument = function() { - if (this.$__.ownerDocument) { - return this.$__.ownerDocument; - } - - let parent = this[documentArrayParent]; - if (!parent) { - return this; - } - - while (parent[documentArrayParent] || parent.$parent) { - parent = parent[documentArrayParent] || parent.$parent; - } - - this.$__.ownerDocument = parent; - return this.$__.ownerDocument; -}; - -/** - * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. - * - * @param {String} [path] - * @return {String} - * @api private - * @method $__fullPath - * @memberOf EmbeddedDocument - * @instance - */ - -EmbeddedDocument.prototype.$__fullPath = function(path) { - if (!this.$__.fullPath) { - let parent = this; // eslint-disable-line consistent-this - if (!parent[documentArrayParent]) { - return path; - } - - const paths = []; - while (parent[documentArrayParent] || parent.$parent) { - if (parent[documentArrayParent]) { - paths.unshift(parent.__parentArray._path); - } else { - paths.unshift(parent.$basePath); - } - parent = parent[documentArrayParent] || parent.$parent; - } - - this.$__.fullPath = paths.join('.'); - - if (!this.$__.ownerDocument) { - // optimization - this.$__.ownerDocument = parent; - } - } - - return path - ? this.$__.fullPath + '.' + path - : this.$__.fullPath; -}; - -/** - * Returns this sub-documents parent document. - * - * @api public - */ - -EmbeddedDocument.prototype.parent = function() { - return this[documentArrayParent]; -}; - -/** - * Returns this sub-documents parent array. - * - * @api public - */ - -EmbeddedDocument.prototype.parentArray = function() { - return this.__parentArray; -}; - -/*! - * Module exports. - */ - -module.exports = EmbeddedDocument; diff --git a/node_modules/mongoose/lib/types/index.js b/node_modules/mongoose/lib/types/index.js deleted file mode 100644 index a1945a03d1cdc3ffdae14a1e2ec410016625b923..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/types/index.js +++ /dev/null @@ -1,20 +0,0 @@ - -/*! - * Module exports. - */ - -'use strict'; - -exports.Array = require('./array'); -exports.Buffer = require('./buffer'); - -exports.Document = // @deprecate -exports.Embedded = require('./embedded'); - -exports.DocumentArray = require('./documentarray'); -exports.Decimal128 = require('./decimal128'); -exports.ObjectId = require('./objectid'); - -exports.Map = require('./map'); - -exports.Subdocument = require('./subdocument'); diff --git a/node_modules/mongoose/lib/types/map.js b/node_modules/mongoose/lib/types/map.js deleted file mode 100644 index bea39bfc2d44447f254d885dd9df8f5193511fed..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/types/map.js +++ /dev/null @@ -1,192 +0,0 @@ -'use strict'; - -const Mixed = require('../schema/mixed'); -const get = require('../helpers/get'); -const util = require('util'); - -/*! - * ignore - */ - -class MongooseMap extends Map { - constructor(v, path, doc, schemaType) { - if (v != null && v.constructor.name === 'Object') { - v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []); - } - super(v); - - this.$__parent = doc != null && doc.$__ != null ? doc : null; - this.$__path = path; - this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType; - - this.$__runDeferred(); - } - - $init(key, value) { - checkValidKey(key); - - super.set(key, value); - - if (value != null && value.$isSingleNested) { - value.$basePath = this.$__path + '.' + key; - } - } - - $__set(key, value) { - super.set(key, value); - } - - set(key, value) { - checkValidKey(key); - - // Weird, but because you can't assign to `this` before calling `super()` - // you can't get access to `$__schemaType` to cast in the initial call to - // `set()` from the `super()` constructor. - - if (this.$__schemaType == null) { - this.$__deferred = this.$__deferred || []; - this.$__deferred.push({ key: key, value: value }); - return; - } - - const fullPath = this.$__path + '.' + key; - const populated = this.$__parent != null && this.$__parent.$__ ? - this.$__parent.populated(fullPath) || this.$__parent.populated(this.$__path) : - null; - - if (populated != null) { - if (value.$__ == null) { - value = new populated.options.model(value); - } - value.$__.wasPopulated = true; - } else { - try { - value = this.$__schemaType. - applySetters(value, this.$__parent, false, this.get(key)); - } catch (error) { - if (this.$__parent != null && this.$__parent.$__ != null) { - this.$__parent.invalidate(fullPath, error); - return; - } - throw error; - } - } - - super.set(key, value); - - if (value != null && value.$isSingleNested) { - value.$basePath = this.$__path + '.' + key; - } - - if (this.$__parent != null && this.$__parent.$__) { - this.$__parent.markModified(this.$__path + '.' + key); - } - } - - toBSON() { - return new Map(this); - } - - toObject(options) { - if (get(options, 'flattenMaps')) { - const ret = {}; - const keys = this.keys(); - for (const key of keys) { - ret[key] = this.get(key); - } - return ret; - } - - return new Map(this); - } - - toJSON() { - const ret = {}; - const keys = this.keys(); - for (const key of keys) { - ret[key] = this.get(key); - } - return ret; - } - - inspect() { - return new Map(this); - } - - $__runDeferred() { - if (!this.$__deferred) { - return; - } - for (let i = 0; i < this.$__deferred.length; ++i) { - this.set(this.$__deferred[i].key, this.$__deferred[i].value); - } - this.$__deferred = null; - } -} - -if (util.inspect.custom) { - Object.defineProperty(MongooseMap.prototype, util.inspect.custom, { - enumerable: false, - writable: false, - configurable: false, - value: MongooseMap.prototype.inspect - }); -} - -Object.defineProperty(MongooseMap.prototype, '$__set', { - enumerable: false, - writable: true, - configurable: false -}); - -Object.defineProperty(MongooseMap.prototype, '$__parent', { - enumerable: false, - writable: true, - configurable: false -}); - -Object.defineProperty(MongooseMap.prototype, '$__path', { - enumerable: false, - writable: true, - configurable: false -}); - -Object.defineProperty(MongooseMap.prototype, '$__schemaType', { - enumerable: false, - writable: true, - configurable: false -}); - -Object.defineProperty(MongooseMap.prototype, '$isMongooseMap', { - enumerable: false, - writable: false, - configurable: false, - value: true -}); - -Object.defineProperty(MongooseMap.prototype, '$__deferredCalls', { - enumerable: false, - writable: false, - configurable: false, - value: true -}); - -/*! - * Since maps are stored as objects under the hood, keys must be strings - * and can't contain any invalid characters - */ - -function checkValidKey(key) { - const keyType = typeof key; - if (keyType !== 'string') { - throw new TypeError(`Mongoose maps only support string keys, got ${keyType}`); - } - if (key.startsWith('$')) { - throw new Error(`Mongoose maps do not support keys that start with "$", got "${key}"`); - } - if (key.includes('.')) { - throw new Error(`Mongoose maps do not support keys that contain ".", got "${key}"`); - } -} - -module.exports = MongooseMap; diff --git a/node_modules/mongoose/lib/types/objectid.js b/node_modules/mongoose/lib/types/objectid.js deleted file mode 100644 index 4c3f8b4ffa07deaa168dfb8c1a89e59e1045ca90..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/types/objectid.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * ObjectId type constructor - * - * ####Example - * - * var id = new mongoose.Types.ObjectId; - * - * @constructor ObjectId - */ - -'use strict'; - -const ObjectId = require('../driver').get().ObjectId; -const objectIdSymbol = require('../helpers/symbols').objectIdSymbol; - -/*! - * Getter for convenience with populate, see gh-6115 - */ - -Object.defineProperty(ObjectId.prototype, '_id', { - enumerable: false, - configurable: true, - get: function() { - return this; - } -}); - -ObjectId.prototype[objectIdSymbol] = true; - -module.exports = ObjectId; diff --git a/node_modules/mongoose/lib/types/subdocument.js b/node_modules/mongoose/lib/types/subdocument.js deleted file mode 100644 index 182d84ed0495b6d33332f62f40cd4f93235fdbd0..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/types/subdocument.js +++ /dev/null @@ -1,236 +0,0 @@ -'use strict'; - -const Document = require('../document'); -const immediate = require('../helpers/immediate'); -const internalToObjectOptions = require('../options').internalToObjectOptions; -const utils = require('../utils'); - -const documentArrayParent = require('../helpers/symbols').documentArrayParent; - -module.exports = Subdocument; - -/** - * Subdocument constructor. - * - * @inherits Document - * @api private - */ - -function Subdocument(value, fields, parent, skipId, options) { - this.$isSingleNested = true; - if (parent != null) { - // If setting a nested path, should copy isNew from parent re: gh-7048 - options = Object.assign({}, options, { isNew: parent.isNew }); - } - Document.call(this, value, fields, skipId, options); - - delete this.$__.$options.priorDoc; -} - -Subdocument.prototype = Object.create(Document.prototype); - -Subdocument.prototype.toBSON = function() { - return this.toObject(internalToObjectOptions); -}; - -/** - * Used as a stub for middleware - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @return {Promise} resolved Promise - * @api private - */ - -Subdocument.prototype.save = function(options, fn) { - if (typeof options === 'function') { - fn = options; - options = {}; - } - options = options || {}; - - if (!options.suppressWarning) { - console.warn('mongoose: calling `save()` on a subdoc does **not** save ' + - 'the document to MongoDB, it only runs save middleware. ' + - 'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' + - 'if you\'re sure this behavior is right for your app.'); - } - - return utils.promiseOrCallback(fn, cb => { - this.$__save(cb); - }); -}; - -/** - * Used as a stub for middleware - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @method $__save - * @api private - */ - -Subdocument.prototype.$__save = function(fn) { - return immediate(() => fn(null, this)); -}; - -Subdocument.prototype.$isValid = function(path) { - if (this.$parent && this.$basePath) { - return this.$parent.$isValid([this.$basePath, path].join('.')); - } - return Document.prototype.$isValid.call(this, path); -}; - -Subdocument.prototype.markModified = function(path) { - Document.prototype.markModified.call(this, path); - - if (this.$parent && this.$basePath) { - if (this.$parent.isDirectModified(this.$basePath)) { - return; - } - this.$parent.markModified([this.$basePath, path].join('.'), this); - } -}; - -Subdocument.prototype.$markValid = function(path) { - Document.prototype.$markValid.call(this, path); - if (this.$parent && this.$basePath) { - this.$parent.$markValid([this.$basePath, path].join('.')); - } -}; - -/*! - * ignore - */ - -Subdocument.prototype.invalidate = function(path, err, val) { - // Hack: array subdocuments' validationError is equal to the owner doc's, - // so validating an array subdoc gives the top-level doc back. Temporary - // workaround for #5208 so we don't have circular errors. - if (err !== this.ownerDocument().$__.validationError) { - Document.prototype.invalidate.call(this, path, err, val); - } - - if (this.$parent && this.$basePath) { - this.$parent.invalidate([this.$basePath, path].join('.'), err, val); - } else if (err.kind === 'cast' || err.name === 'CastError') { - throw err; - } -}; - -/*! - * ignore - */ - -Subdocument.prototype.$ignore = function(path) { - Document.prototype.$ignore.call(this, path); - if (this.$parent && this.$basePath) { - this.$parent.$ignore([this.$basePath, path].join('.')); - } -}; - -/** - * Returns the top level document of this sub-document. - * - * @return {Document} - */ - -Subdocument.prototype.ownerDocument = function() { - if (this.$__.ownerDocument) { - return this.$__.ownerDocument; - } - - let parent = this.$parent; - if (!parent) { - return this; - } - - while (parent.$parent || parent[documentArrayParent]) { - parent = parent.$parent || parent[documentArrayParent]; - } - - this.$__.ownerDocument = parent; - return this.$__.ownerDocument; -}; - -/** - * Returns this sub-documents parent document. - * - * @api public - */ - -Subdocument.prototype.parent = function() { - return this.$parent; -}; - -/*! - * no-op for hooks - */ - -Subdocument.prototype.$__remove = function(cb) { - return cb(null, this); -}; - -/** - * Null-out this subdoc - * - * @param {Object} [options] - * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove - */ - -Subdocument.prototype.remove = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = null; - } - - registerRemoveListener(this); - - // If removing entire doc, no need to remove subdoc - if (!options || !options.noop) { - this.$parent.set(this.$basePath, null); - } - - if (typeof callback === 'function') { - callback(null); - } -}; - -/*! - * ignore - */ - -Subdocument.prototype.populate = function() { - throw new Error('Mongoose does not support calling populate() on nested ' + - 'docs. Instead of `doc.nested.populate("path")`, use ' + - '`doc.populate("nested.path")`'); -}; - -/*! - * Registers remove event listeners for triggering - * on subdocuments. - * - * @param {EmbeddedDocument} sub - * @api private - */ - -function registerRemoveListener(sub) { - let owner = sub.ownerDocument(); - - function emitRemove() { - owner.removeListener('save', emitRemove); - owner.removeListener('remove', emitRemove); - sub.emit('remove', sub); - sub.constructor.emit('remove', sub); - owner = sub = null; - } - - owner.on('save', emitRemove); - owner.on('remove', emitRemove); -} diff --git a/node_modules/mongoose/lib/utils.js b/node_modules/mongoose/lib/utils.js deleted file mode 100644 index bb9f2fe1c7c43313e0d2e5f2cd1f306dd459fcfe..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/utils.js +++ /dev/null @@ -1,974 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const Decimal = require('./types/decimal128'); -const ObjectId = require('./types/objectid'); -const PromiseProvider = require('./promise_provider'); -const cloneRegExp = require('regexp-clone'); -const get = require('./helpers/get'); -const sliced = require('sliced'); -const mpath = require('mpath'); -const ms = require('ms'); -const Buffer = require('safe-buffer').Buffer; - -const emittedSymbol = Symbol.for('mongoose:emitted'); - -let MongooseBuffer; -let MongooseArray; -let Document; - -const specialProperties = new Set(['__proto__', 'constructor', 'prototype']); - -exports.specialProperties = specialProperties; - -/*! - * Produces a collection name from model `name`. By default, just returns - * the model name - * - * @param {String} name a model name - * @param {Function} pluralize function that pluralizes the collection name - * @return {String} a collection name - * @api private - */ - -exports.toCollectionName = function(name, pluralize) { - if (name === 'system.profile') { - return name; - } - if (name === 'system.indexes') { - return name; - } - if (typeof pluralize === 'function') { - return pluralize(name); - } - return name; -}; - -/*! - * Determines if `a` and `b` are deep equal. - * - * Modified from node/lib/assert.js - * - * @param {any} a a value to compare to `b` - * @param {any} b a value to compare to `a` - * @return {Boolean} - * @api private - */ - -exports.deepEqual = function deepEqual(a, b) { - if (a === b) { - return true; - } - - if (a instanceof Date && b instanceof Date) { - return a.getTime() === b.getTime(); - } - - if ((isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) || - (isBsonType(a, 'Decimal128') && isBsonType(b, 'Decimal128'))) { - return a.toString() === b.toString(); - } - - if (a instanceof RegExp && b instanceof RegExp) { - return a.source === b.source && - a.ignoreCase === b.ignoreCase && - a.multiline === b.multiline && - a.global === b.global; - } - - if (typeof a !== 'object' && typeof b !== 'object') { - return a == b; - } - - if (a === null || b === null || a === undefined || b === undefined) { - return false; - } - - if (a.prototype !== b.prototype) { - return false; - } - - // Handle MongooseNumbers - if (a instanceof Number && b instanceof Number) { - return a.valueOf() === b.valueOf(); - } - - if (Buffer.isBuffer(a)) { - return exports.buffer.areEqual(a, b); - } - - if (isMongooseObject(a)) { - a = a.toObject(); - } - if (isMongooseObject(b)) { - b = b.toObject(); - } - - let ka; - let kb; - let key; - let i; - try { - ka = Object.keys(a); - kb = Object.keys(b); - } catch (e) { - // happens when one is a string literal and the other isn't - return false; - } - - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) { - return false; - } - - // the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - - // ~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) { - return false; - } - } - - // equivalent values for every corresponding key, and - // ~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!deepEqual(a[key], b[key])) { - return false; - } - } - - return true; -}; - -/*! - * Get the bson type, if it exists - */ - -function isBsonType(obj, typename) { - return get(obj, '_bsontype', void 0) === typename; -} - -/*! - * Get the last element of an array - */ - -exports.last = function(arr) { - if (arr.length > 0) { - return arr[arr.length - 1]; - } - return void 0; -}; - -/*! - * Object clone with Mongoose natives support. - * - * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. - * - * Functions are never cloned. - * - * @param {Object} obj the object to clone - * @param {Object} options - * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize. - * @return {Object} the cloned object - * @api private - */ - -exports.clone = function clone(obj, options, isArrayChild) { - if (obj == null) { - return obj; - } - - if (Array.isArray(obj)) { - return cloneArray(obj, options); - } - - if (isMongooseObject(obj)) { - if (options && options.json && typeof obj.toJSON === 'function') { - return obj.toJSON(options); - } - return obj.toObject(options); - } - - if (obj.constructor) { - switch (exports.getFunctionName(obj.constructor)) { - case 'Object': - return cloneObject(obj, options, isArrayChild); - case 'Date': - return new obj.constructor(+obj); - case 'RegExp': - return cloneRegExp(obj); - default: - // ignore - break; - } - } - - if (obj instanceof ObjectId) { - return new ObjectId(obj.id); - } - if (isBsonType(obj, 'Decimal128')) { - if (options && options.flattenDecimals) { - return obj.toJSON(); - } - return Decimal.fromString(obj.toString()); - } - - if (!obj.constructor && exports.isObject(obj)) { - // object created with Object.create(null) - return cloneObject(obj, options, isArrayChild); - } - - if (obj.valueOf) { - return obj.valueOf(); - } - - return cloneObject(obj, options, isArrayChild); -}; -const clone = exports.clone; - -/*! - * ignore - */ - -exports.promiseOrCallback = function promiseOrCallback(callback, fn, ee) { - if (typeof callback === 'function') { - return fn(function(error) { - if (error != null) { - if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) { - error[emittedSymbol] = true; - ee.emit('error', error); - } - try { - callback(error); - } catch (error) { - return process.nextTick(() => { - throw error; - }); - } - return; - } - callback.apply(this, arguments); - }); - } - - const Promise = PromiseProvider.get(); - - return new Promise((resolve, reject) => { - fn(function(error, res) { - if (error != null) { - if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) { - error[emittedSymbol] = true; - ee.emit('error', error); - } - return reject(error); - } - if (arguments.length > 2) { - return resolve(Array.prototype.slice.call(arguments, 1)); - } - resolve(res); - }); - }); -}; - -/*! - * ignore - */ - -function cloneObject(obj, options, isArrayChild) { - const minimize = options && options.minimize; - const ret = {}; - let hasKeys; - - for (const k in obj) { - if (specialProperties.has(k)) { - continue; - } - - // Don't pass `isArrayChild` down - const val = clone(obj[k], options); - - if (!minimize || (typeof val !== 'undefined')) { - hasKeys || (hasKeys = true); - ret[k] = val; - } - } - - return minimize && !isArrayChild ? hasKeys && ret : ret; -} - -function cloneArray(arr, options) { - const ret = []; - for (let i = 0, l = arr.length; i < l; i++) { - ret.push(clone(arr[i], options, true)); - } - return ret; -} - -/*! - * Shallow copies defaults into options. - * - * @param {Object} defaults - * @param {Object} options - * @return {Object} the merged object - * @api private - */ - -exports.options = function(defaults, options) { - const keys = Object.keys(defaults); - let i = keys.length; - let k; - - options = options || {}; - - while (i--) { - k = keys[i]; - if (!(k in options)) { - options[k] = defaults[k]; - } - } - - return options; -}; - -/*! - * Generates a random string - * - * @api private - */ - -exports.random = function() { - return Math.random().toString().substr(3); -}; - -/*! - * Merges `from` into `to` without overwriting existing properties. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - -exports.merge = function merge(to, from, options, path) { - options = options || {}; - - const keys = Object.keys(from); - let i = 0; - const len = keys.length; - let key; - - path = path || ''; - const omitNested = options.omitNested || {}; - - while (i < len) { - key = keys[i++]; - if (options.omit && options.omit[key]) { - continue; - } - if (omitNested[path]) { - continue; - } - if (specialProperties.has(key)) { - continue; - } - if (to[key] == null) { - to[key] = from[key]; - } else if (exports.isObject(from[key])) { - if (!exports.isObject(to[key])) { - to[key] = {}; - } - if (from[key] != null) { - if (from[key].instanceOfSchema) { - to[key] = from[key].clone(); - continue; - } else if (from[key] instanceof ObjectId) { - to[key] = new ObjectId(from[key]); - continue; - } - } - merge(to[key], from[key], options, path ? path + '.' + key : key); - } else if (options.overwrite) { - to[key] = from[key]; - } - } -}; - -/*! - * Applies toObject recursively. - * - * @param {Document|Array|Object} obj - * @return {Object} - * @api private - */ - -exports.toObject = function toObject(obj) { - Document || (Document = require('./document')); - let ret; - - if (obj == null) { - return obj; - } - - if (obj instanceof Document) { - return obj.toObject(); - } - - if (Array.isArray(obj)) { - ret = []; - - for (let i = 0, len = obj.length; i < len; ++i) { - ret.push(toObject(obj[i])); - } - - return ret; - } - - if (exports.isPOJO(obj)) { - ret = {}; - - for (const k in obj) { - if (specialProperties.has(k)) { - continue; - } - ret[k] = toObject(obj[k]); - } - - return ret; - } - - return obj; -}; - -/*! - * Determines if `arg` is an object. - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @api private - * @return {Boolean} - */ - -exports.isObject = function(arg) { - if (Buffer.isBuffer(arg)) { - return true; - } - return Object.prototype.toString.call(arg) === '[object Object]'; -}; - -/*! - * Determines if `arg` is a plain old JavaScript object (POJO). Specifically, - * `arg` must be an object but not an instance of any special class, like String, - * ObjectId, etc. - * - * `Object.getPrototypeOf()` is part of ES5: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @api private - * @return {Boolean} - */ - -exports.isPOJO = function(arg) { - if (arg == null || typeof arg !== 'object') { - return false; - } - const proto = Object.getPrototypeOf(arg); - // Prototype may be null if you used `Object.create(null)` - // Checking `proto`'s constructor is safe because `getPrototypeOf()` - // explicitly crosses the boundary from object data to object metadata - return !proto || proto.constructor.name === 'Object'; -}; - -/*! - * A faster Array.prototype.slice.call(arguments) alternative - * @api private - */ - -exports.args = sliced; - -/*! - * process.nextTick helper. - * - * Wraps `callback` in a try/catch + nextTick. - * - * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. - * - * @param {Function} callback - * @api private - */ - -exports.tick = function tick(callback) { - if (typeof callback !== 'function') { - return; - } - return function() { - try { - callback.apply(this, arguments); - } catch (err) { - // only nextTick on err to get out of - // the event loop and avoid state corruption. - process.nextTick(function() { - throw err; - }); - } - }; -}; - -/*! - * Returns if `v` is a mongoose object that has a `toObject()` method we can use. - * - * This is for compatibility with libs like Date.js which do foolish things to Natives. - * - * @param {any} v - * @api private - */ - -exports.isMongooseObject = function(v) { - Document || (Document = require('./document')); - MongooseArray || (MongooseArray = require('./types').Array); - MongooseBuffer || (MongooseBuffer = require('./types').Buffer); - - if (v == null) { - return false; - } - - return v.$__ != null || // Document - v.isMongooseArray || // Array or Document Array - v.isMongooseBuffer || // Buffer - v.$isMongooseMap; // Map -}; - -const isMongooseObject = exports.isMongooseObject; - -/*! - * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. - * - * @param {Object} object - * @api private - */ - -exports.expires = function expires(object) { - if (!(object && object.constructor.name === 'Object')) { - return; - } - if (!('expires' in object)) { - return; - } - - let when; - if (typeof object.expires !== 'string') { - when = object.expires; - } else { - when = Math.round(ms(object.expires) / 1000); - } - object.expireAfterSeconds = when; - delete object.expires; -}; - -/*! - * Populate options constructor - */ - -function PopulateOptions(obj) { - this.path = obj.path; - this.match = obj.match; - this.select = obj.select; - this.options = obj.options; - this.model = obj.model; - if (typeof obj.subPopulate === 'object') { - this.populate = obj.subPopulate; - } - if (obj.justOne != null) { - this.justOne = obj.justOne; - } - if (obj.count != null) { - this.count = obj.count; - } - this._docs = {}; -} - -// make it compatible with utils.clone -PopulateOptions.prototype.constructor = Object; - -// expose -exports.PopulateOptions = PopulateOptions; - -/*! - * populate helper - */ - -exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) { - // The order of select/conditions args is opposite Model.find but - // necessary to keep backward compatibility (select could be - // an array, string, or object literal). - function makeSingles(arr) { - const ret = []; - arr.forEach(function(obj) { - if (/[\s]/.test(obj.path)) { - const paths = obj.path.split(' '); - paths.forEach(function(p) { - const copy = Object.assign({}, obj); - copy.path = p; - ret.push(copy); - }); - } else { - ret.push(obj); - } - }); - - return ret; - } - - // might have passed an object specifying all arguments - if (arguments.length === 1) { - if (path instanceof PopulateOptions) { - return [path]; - } - - if (Array.isArray(path)) { - const singles = makeSingles(path); - return singles.map(function(o) { - if (o.populate && !(o.match || o.options)) { - return exports.populate(o)[0]; - } else { - return exports.populate(o)[0]; - } - }); - } - - if (exports.isObject(path)) { - match = path.match; - options = path.options; - select = path.select; - model = path.model; - subPopulate = path.populate; - justOne = path.justOne; - path = path.path; - count = path.count; - } - } else if (typeof model === 'object') { - options = match; - match = model; - model = undefined; - } - - if (typeof path !== 'string') { - throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); - } - - if (Array.isArray(subPopulate)) { - const ret = []; - subPopulate.forEach(function(obj) { - if (/[\s]/.test(obj.path)) { - const copy = Object.assign({}, obj); - const paths = copy.path.split(' '); - paths.forEach(function(p) { - copy.path = p; - ret.push(exports.populate(copy)[0]); - }); - } else { - ret.push(exports.populate(obj)[0]); - } - }); - subPopulate = exports.populate(ret); - } else if (typeof subPopulate === 'object') { - subPopulate = exports.populate(subPopulate); - } - - const ret = []; - const paths = path.split(' '); - options = exports.clone(options); - for (let i = 0; i < paths.length; ++i) { - ret.push(new PopulateOptions({ - path: paths[i], - select: select, - match: match, - options: options, - model: model, - subPopulate: subPopulate, - justOne: justOne, - count: count - })); - } - - return ret; -}; - -/*! - * Return the value of `obj` at the given `path`. - * - * @param {String} path - * @param {Object} obj - */ - -exports.getValue = function(path, obj, map) { - return mpath.get(path, obj, '_doc', map); -}; - -/*! - * Sets the value of `obj` at the given `path`. - * - * @param {String} path - * @param {Anything} val - * @param {Object} obj - */ - -exports.setValue = function(path, val, obj, map, _copying) { - mpath.set(path, val, obj, '_doc', map, _copying); -}; - -/*! - * Returns an array of values from object `o`. - * - * @param {Object} o - * @return {Array} - * @private - */ - -exports.object = {}; -exports.object.vals = function vals(o) { - const keys = Object.keys(o); - let i = keys.length; - const ret = []; - - while (i--) { - ret.push(o[keys[i]]); - } - - return ret; -}; - -/*! - * @see exports.options - */ - -exports.object.shallowCopy = exports.options; - -/*! - * Safer helper for hasOwnProperty checks - * - * @param {Object} obj - * @param {String} prop - */ - -const hop = Object.prototype.hasOwnProperty; -exports.object.hasOwnProperty = function(obj, prop) { - return hop.call(obj, prop); -}; - -/*! - * Determine if `val` is null or undefined - * - * @return {Boolean} - */ - -exports.isNullOrUndefined = function(val) { - return val === null || val === undefined; -}; - -/*! - * ignore - */ - -exports.array = {}; - -/*! - * Flattens an array. - * - * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] - * - * @param {Array} arr - * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsey value, the item will not be included in the results. - * @return {Array} - * @private - */ - -exports.array.flatten = function flatten(arr, filter, ret) { - ret || (ret = []); - - arr.forEach(function(item) { - if (Array.isArray(item)) { - flatten(item, filter, ret); - } else { - if (!filter || filter(item)) { - ret.push(item); - } - } - }); - - return ret; -}; - -/*! - * Removes duplicate values from an array - * - * [1, 2, 3, 3, 5] => [1, 2, 3, 5] - * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ] - * => [ObjectId("550988ba0c19d57f697dc45e")] - * - * @param {Array} arr - * @return {Array} - * @private - */ - -exports.array.unique = function(arr) { - const primitives = {}; - const ids = {}; - const ret = []; - const length = arr.length; - for (let i = 0; i < length; ++i) { - if (typeof arr[i] === 'number' || typeof arr[i] === 'string' || arr[i] == null) { - if (primitives[arr[i]]) { - continue; - } - ret.push(arr[i]); - primitives[arr[i]] = true; - } else if (arr[i] instanceof ObjectId) { - if (ids[arr[i].toString()]) { - continue; - } - ret.push(arr[i]); - ids[arr[i].toString()] = true; - } else { - ret.push(arr[i]); - } - } - - return ret; -}; - -/*! - * Determines if two buffers are equal. - * - * @param {Buffer} a - * @param {Object} b - */ - -exports.buffer = {}; -exports.buffer.areEqual = function(a, b) { - if (!Buffer.isBuffer(a)) { - return false; - } - if (!Buffer.isBuffer(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (let i = 0, len = a.length; i < len; ++i) { - if (a[i] !== b[i]) { - return false; - } - } - return true; -}; - -exports.getFunctionName = function(fn) { - if (fn.name) { - return fn.name; - } - return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; -}; - -/*! - * Decorate buffers - */ - -exports.decorate = function(destination, source) { - for (const key in source) { - if (specialProperties.has(key)) { - continue; - } - destination[key] = source[key]; - } -}; - -/** - * merges to with a copy of from - * - * @param {Object} to - * @param {Object} fromObj - * @api private - */ - -exports.mergeClone = function(to, fromObj) { - if (isMongooseObject(fromObj)) { - fromObj = fromObj.toObject({ - transform: false, - virtuals: false, - depopulate: true, - getters: false, - flattenDecimals: false - }); - } - const keys = Object.keys(fromObj); - const len = keys.length; - let i = 0; - let key; - - while (i < len) { - key = keys[i++]; - if (specialProperties.has(key)) { - continue; - } - if (typeof to[key] === 'undefined') { - to[key] = exports.clone(fromObj[key], { - transform: false, - virtuals: false, - depopulate: true, - getters: false, - flattenDecimals: false - }); - } else { - let val = fromObj[key]; - if (val != null && val.valueOf && !(val instanceof Date)) { - val = val.valueOf(); - } - if (exports.isObject(val)) { - let obj = val; - if (isMongooseObject(val) && !val.isMongooseBuffer) { - obj = obj.toObject({ - transform: false, - virtuals: false, - depopulate: true, - getters: false, - flattenDecimals: false - }); - } - if (val.isMongooseBuffer) { - obj = Buffer.from(obj); - } - exports.mergeClone(to[key], obj); - } else { - to[key] = exports.clone(val, { - flattenDecimals: false - }); - } - } - } -}; - -/** - * Executes a function on each element of an array (like _.each) - * - * @param {Array} arr - * @param {Function} fn - * @api private - */ - -exports.each = function(arr, fn) { - for (let i = 0; i < arr.length; ++i) { - fn(arr[i]); - } -}; - -/*! - * ignore - */ - -exports.noop = function() {}; diff --git a/node_modules/mongoose/lib/virtualtype.js b/node_modules/mongoose/lib/virtualtype.js deleted file mode 100644 index 060ec610229bde842d5683c2232ca2f99b26535b..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/lib/virtualtype.js +++ /dev/null @@ -1,144 +0,0 @@ -'use strict'; - -/** - * VirtualType constructor - * - * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. - * - * ####Example: - * - * const fullname = schema.virtual('fullname'); - * fullname instanceof mongoose.VirtualType // true - * - * @param {Object} options - * @param {string|function} [options.ref] if `ref` is not nullish, this becomes a [populated virtual](/docs/populate.html#populate-virtuals) - * @param {string|function} [options.localField] the local field to populate on if this is a populated virtual. - * @param {string|function} [options.foreignField] the foreign field to populate on if this is a populated virtual. - * @param {boolean} [options.justOne=false] by default, a populated virtual is an array. If you set `justOne`, the populated virtual will be a single doc or `null`. - * @param {boolean} [options.getters=false] if you set this to `true`, Mongoose will call any custom getters you defined on this virtual - * @param {boolean} [options.count=false] if you set this to `true`, `populate()` will set this virtual to the number of populated documents, as opposed to the documents themselves, using [`Query#countDocuments()`](./api.html#query_Query-countDocuments) - * @api public - */ - -function VirtualType(options, name) { - this.path = name; - this.getters = []; - this.setters = []; - this.options = Object.assign({}, options); -} - -/** - * If no getters/getters, add a default - * - * @param {Function} fn - * @return {VirtualType} this - * @api private - */ - -VirtualType.prototype._applyDefaultGetters = function() { - if (this.getters.length > 0 || this.setters.length > 0) { - return; - } - - const path = this.path; - const internalProperty = '$' + path; - this.getters.push(function() { - return this[internalProperty]; - }); - this.setters.push(function(v) { - this[internalProperty] = v; - }); -}; - -/*! - * ignore - */ - -VirtualType.prototype.clone = function() { - const clone = new VirtualType(this.name, this.options); - clone.getters = [].concat(this.getters); - clone.setters = [].concat(this.setters); - return clone; -}; - -/** - * Defines a getter. - * - * ####Example: - * - * var virtual = schema.virtual('fullname'); - * virtual.get(function () { - * return this.name.first + ' ' + this.name.last; - * }); - * - * @param {Function} fn - * @return {VirtualType} this - * @api public - */ - -VirtualType.prototype.get = function(fn) { - this.getters.push(fn); - return this; -}; - -/** - * Defines a setter. - * - * ####Example: - * - * var virtual = schema.virtual('fullname'); - * virtual.set(function (v) { - * var parts = v.split(' '); - * this.name.first = parts[0]; - * this.name.last = parts[1]; - * }); - * - * @param {Function} fn - * @return {VirtualType} this - * @api public - */ - -VirtualType.prototype.set = function(fn) { - this.setters.push(fn); - return this; -}; - -/** - * Applies getters to `value` using optional `scope`. - * - * @param {Object} value - * @param {Object} scope - * @return {any} the value after applying all getters - * @api public - */ - -VirtualType.prototype.applyGetters = function(value, scope) { - let v = value; - for (let l = this.getters.length - 1; l >= 0; l--) { - v = this.getters[l].call(scope, v, this); - } - return v; -}; - -/** - * Applies setters to `value` using optional `scope`. - * - * @param {Object} value - * @param {Object} scope - * @return {any} the value after applying all setters - * @api public - */ - -VirtualType.prototype.applySetters = function(value, scope) { - let v = value; - for (let l = this.setters.length - 1; l >= 0; l--) { - v = this.setters[l].call(scope, v, this); - } - return v; -}; - -/*! - * exports - */ - -module.exports = VirtualType; diff --git a/node_modules/mongoose/migrating_to_5.md b/node_modules/mongoose/migrating_to_5.md deleted file mode 100644 index 7b6377c15db293818c4b6a06f2bf77ffcc6a5e9c..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/migrating_to_5.md +++ /dev/null @@ -1,432 +0,0 @@ -### Version Requirements - -Mongoose now requires node.js >= 4.0.0 and MongoDB >= 3.0.0. [MongoDB 2.6](https://www.mongodb.com/blog/post/mongodb-2-6-end-of-life) and [Node.js < 4](https://github.com/nodejs/Release) where both EOL-ed in 2016. - -### Query Middleware - -Query middleware is now compiled when you call `mongoose.model()` or `db.model()`. If you add query middleware after calling `mongoose.model()`, that middleware will **not** get called. - -```javascript -const schema = new Schema({ name: String }); -const MyModel = mongoose.model('Test', schema); -schema.pre('find', () => { console.log('find!'); }); - -MyModel.find().exec(function() { - // In mongoose 4.x, the above `.find()` will print "find!" - // In mongoose 5.x, "find!" will **not** be printed. - // Call `pre('find')` **before** calling `mongoose.model()` to make the middleware apply. -}); -``` - -### Promises and Callbacks for `mongoose.connect()` - -`mongoose.connect()` and `mongoose.disconnect()` now return a promise if no callback specified, or `null` otherwise. It does **not** return the mongoose singleton. - -```javascript -// Worked in mongoose 4. Does **not** work in mongoose 5, `mongoose.connect()` -// now returns a promise consistently. This is to avoid the horrible things -// we've done to allow mongoose to be a thenable that resolves to itself. -mongoose.connect('mongodb://localhost:27017/test').model('Test', new Schema({})); - -// Do this instead -mongoose.connect('mongodb://localhost:27017/test'); -mongoose.model('Test', new Schema({})); -``` - -### Connection Logic and `useMongoClient` - -The [`useMongoClient` option](http://mongoosejs.com/docs/4.x/docs/connections.html#use-mongo-client) was -removed in Mongoose 5, it is now always `true`. As a consequence, Mongoose 5 -no longer supports several function signatures for `mongoose.connect()` that -worked in Mongoose 4.x if the `useMongoClient` option was off. Below are some -examples of `mongoose.connect()` calls that do **not** work in Mongoose 5.x. - -* `mongoose.connect('localhost', 27017);` -* `mongoose.connect('localhost', 'mydb', 27017);` -* `mongoose.connect('mongodb://host1:27017,mongodb://host2:27017');` - -In Mongoose 5.x, the first parameter to `mongoose.connect()` and `mongoose.createConnection()`, if specified, **must** be a [MongoDB connection string](https://docs.mongodb.com/manual/reference/connection-string/). The -connection string and options are then passed down to [the MongoDB Node.js driver's `MongoClient.connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#.connect). Mongoose does not modify the connection string, although `mongoose.connect()` and `mongoose.createConnection()` support a [few additional options in addition to the ones the MongoDB driver supports](http://mongoosejs.com/docs/connections.html#options). - -### Setter Order - -Setters run in reverse order in 4.x: - -```javascript -const schema = new Schema({ name: String }); -schema.path('name'). - get(() => console.log('This will print 2nd')). - get(() => console.log('This will print first')); -``` - -In 5.x, setters run in the order they're declared. - -```javascript -const schema = new Schema({ name: String }); -schema.path('name'). - get(() => console.log('This will print first')). - get(() => console.log('This will print 2nd')); -``` - -### Checking if a path is populated - -Mongoose 5.1.0 introduced an `_id` getter to ObjectIds that lets you get an ObjectId regardless of whether a path -is populated. - -```javascript -const blogPostSchema = new Schema({ - title: String, - author: { - type: mongoose.Schema.Types.ObjectId, - ref: 'Author' - } -}); -const BlogPost = mongoose.model('BlogPost', blogPostSchema); - -await BlogPost.create({ title: 'test', author: author._id }); -const blogPost = await BlogPost.findOne(); - -console.log(blogPost.author); // '5b207f84e8061d1d2711b421' -// New in Mongoose 5.1.0: this will print '5b207f84e8061d1d2711b421' as well -console.log(blogPost.author._id); - -await blogPost.populate('author'); -console.log(blogPost.author._id); '5b207f84e8061d1d2711b421' -``` - -As a consequence, checking whether `blogPost.author._id` is [no longer viable as a way to check whether `author` is populated](https://github.com/Automattic/mongoose/issues/6415#issuecomment-388579185). Use `blogPost.populated('author') != null` or `blogPost.author instanceof mongoose.Types.ObjectId` to check whether `author` is populated instead. - -Note that you can call `mongoose.set('objectIdGetter', false)` to change this behavior. - -### Return Values for `remove()` and `deleteX()` - -`deleteOne()`, `deleteMany()`, and `remove()` now resolve to the result object -rather than the full [driver `WriteOpResult` object](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~writeOpCallback). - -```javascript -// In 4.x, this is how you got the number of documents deleted -MyModel.deleteMany().then(res => console.log(res.result.n)); -// In 5.x this is how you get the number of documents deleted -MyModel.deleteMany().then(res => res.n); -``` - -### Aggregation Cursors - -The `useMongooseAggCursor` option from 4.x is now always on. This is the new syntax for aggregation cursors in mongoose 5: - -```javascript -// When you call `.cursor()`, `.exec()` will now return a mongoose aggregation -// cursor. -const cursor = MyModel.aggregate([{ $match: { name: 'Val' } }]).cursor().exec(); -// No need to `await` on the cursor or wait for a promise to resolve -cursor.eachAsync(doc => console.log(doc)); - -// Can also pass options to `cursor()` -const cursorWithOptions = MyModel. - aggregate([{ $match: { name: 'Val' } }]). - cursor({ batchSize: 10 }). - exec(); -``` - -### geoNear - -`Model.geoNear()` has been removed because the [MongoDB driver no longer supports it](https://github.com/mongodb/node-mongodb-native/blob/master/CHANGES_3.0.0.md#geonear-command-helper) - -### Required URI encoding of connection strings - -Due to changes in the MongoDB driver, connection strings must be URI encoded. - -If they are not, connections may fail with an illegal character message. - -#### Passwords which contain certain characters - -See a [full list of affected characters](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). - -If your app is used by a lot of different connection strings, it's possible -that your test cases will pass, but production passwords will fail. Encode all your connection -strings to be safe. - -If you want to continue to use unencoded connection strings, the easiest fix is to use -the `mongodb-uri` module to parse the connection strings, and then produce the properly encoded -versions. You can use a function like this: - -```javascript -const uriFormat = require('mongodb-uri') -function encodeMongoURI (urlString) { - if (urlString) { - let parsed = uriFormat.parse(urlString) - urlString = uriFormat.format(parsed); - } - return urlString; - } -} - -// Your un-encoded string. -const mongodbConnectString = "mongodb://..."; -mongoose.connect(encodeMongoURI(mongodbConnectString)) -``` - -The function above is safe to use whether the existing string is already encoded or not. - -#### Domain sockets - -Domain sockets must be URI encoded. For example: - -```javascript -// Works in mongoose 4. Does **not** work in mongoose 5 because of more -// stringent URI parsing. -const host = '/tmp/mongodb-27017.sock'; -mongoose.createConnection(`mongodb://aaron:psw@${host}/fake`); - -// Do this instead -const host = encodeURIComponent('/tmp/mongodb-27017.sock'); -mongoose.createConnection(`mongodb://aaron:psw@${host}/fake`); -``` - -### `toObject()` Options - -The `options` parameter to `toObject()` and `toJSON()` merge defaults rather than overwriting them. - -```javascript -// Note the `toObject` option below -const schema = new Schema({ name: String }, { toObject: { virtuals: true } }); -schema.virtual('answer').get(() => 42); -const MyModel = db.model('MyModel', schema); - -const doc = new MyModel({ name: 'test' }); -// In mongoose 4.x this prints "undefined", because `{ minimize: false }` -// overwrites the entire schema-defined options object. -// In mongoose 5.x this prints "42", because `{ minimize: false }` gets -// merged with the schema-defined options. -console.log(doc.toJSON({ minimize: false }).answer); -``` - -### Aggregate Parameters - -`aggregate()` no longer accepts a spread, you **must** pass your aggregation pipeline as an array. The below code worked in 4.x: - -```javascript -MyModel.aggregate({ $match: { isDeleted: false } }, { $skip: 10 }).exec(cb); -``` - -The above code does **not** work in 5.x, you **must** wrap the `$match` and `$skip` stages in an array. - -```javascript -MyModel.aggregate([{ $match: { isDeleted: false } }, { $skip: 10 }]).exec(cb); -``` - -### Boolean Casting - -By default, mongoose 4 would coerce any value to a boolean without error. - -```javascript -// Fine in mongoose 4, would save a doc with `boolField = true` -const MyModel = mongoose.model('Test', new Schema({ - boolField: Boolean -})); - -MyModel.create({ boolField: 'not a boolean' }); -``` - -Mongoose 5 only casts the following values to `true`: - -* `true` -* `'true'` -* `1` -* `'1'` -* `'yes'` - -And the following values to `false`: - -* `false` -* `'false'` -* `0` -* `'0'` -* `'no'` - -All other values will cause a `CastError` -### Query Casting - -Casting for `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, -`remove()`, `deleteOne()`, and `deleteMany()` doesn't happen until `exec()`. -This makes it easier for hooks and custom query helpers to modify data, because -mongoose won't restructure the data you passed in until after your hooks and -query helpers have ran. It also makes it possible to set the `overwrite` option -_after_ passing in an update. - -```javascript -// In mongoose 4.x, this becomes `{ $set: { name: 'Baz' } }` despite the `overwrite` -// In mongoose 5.x, this overwrite is respected and the first document with -// `name = 'Bar'` will be replaced with `{ name: 'Baz' }` -User.where({ name: 'Bar' }).update({ name: 'Baz' }).setOptions({ overwrite: true }); -``` - -### Post Save Hooks Get Flow Control - -Post hooks now get flow control, which means async post save hooks and child document post save hooks execute **before** your `save()` callback. - -```javsscript -const ChildModelSchema = new mongoose.Schema({ - text: { - type: String - } -}); -ChildModelSchema.post('save', function(doc) { - // In mongoose 5.x this will print **before** the `console.log()` - // in the `save()` callback. In mongoose 4.x this was reversed. - console.log('Child post save'); -}); -const ParentModelSchema = new mongoose.Schema({ - children: [ChildModelSchema] -}); - -const Model = mongoose.model('Parent', ParentModelSchema); -const m = new Model({ children: [{ text: 'test' }] }); -m.save(function() { - // In mongoose 5.xm this prints **after** the "Child post save" message. - console.log('Save callback'); -}); -``` - -### The `$pushAll` Operator - -`$pushAll` is no longer supported and no longer used internally for `save()`, since it has been [deprecated since MongoDB 2.4](https://docs.mongodb.com/manual/reference/operator/update/pushAll/). Use `$push` with `$each` instead. - -### Always Use Forward Key Order - -The `retainKeyOrder` option was removed, mongoose will now always retain the same key position when cloning objects. If you have queries or indexes that rely on reverse key order, you will have to change them. - -### Run setters on queries - -Setters now run on queries by default, and the old `runSettersOnQuery` option -has been removed. - -```javascript -const schema = new Schema({ - email: { type: String, lowercase: true } -}); -const Model = mongoose.model('Test', schema); -Model.find({ email: 'FOO@BAR.BAZ' }); // Converted to `find({ email: 'foo@bar.baz' })` -``` - -### Pre-compiled Browser Bundle - -We no longer have a pre-compiled version of mongoose for the browser. If you want to use mongoose schemas in the browser, you need to build your own bundle with browserify/webpack. - -### Save Errors - -The `saveErrorIfNotFound` option was removed, mongoose will now always error out from `save()` if the underlying document was not found - -### Init hook signatures - -`init` hooks are now fully synchronous and do not receive `next()` as a parameter. - -`Document.prototype.init()` no longer takes a callback as a parameter. It -was always synchronous, just had a callback for legacy reasons. - -### `numAffected` and `save()` - -`doc.save()` no longer passes `numAffected` as a 3rd param to its callback. - -### `remove()` and debouncing - -`doc.remove()` no longer debounces - -### `getPromiseConstructor()` - -`getPromiseConstructor()` is gone, just use `mongoose.Promise`. - -### Passing Parameters from Pre Hooks - -You cannot pass parameters to the next pre middleware in the chain using `next()` in mongoose 5.x. In mongoose 4, `next('Test')` in pre middleware would call the -next middleware with 'Test' as a parameter. Mongoose 5.x has removed support for this. - -### `required` validator for arrays - -In mongoose 5 the `required` validator only verifies if the value is an array. That is, it will **not** fail for _empty_ arrays as it would in mongoose 4. - -### debug output defaults to stdout instead of stderr - -In mongoose 5 the default debug function uses `console.info()` to display messages instead of `console.error()`. - -### Overwriting filter properties - -In Mongoose 4.x, overwriting a filter property that's a primitive with one that is an object would silently fail. For example, the below code would ignore the `where()` and be equivalent to `Sport.find({ name: 'baseball' })` - -```javascript -Sport.find({ name: 'baseball' }).where({name: {$ne: 'softball'}}); -``` - -In Mongoose 5.x, the above code will correctly overwrite `'baseball'` with `{ $ne: 'softball' }` - -### `bulkWrite()` results - -Mongoose 5.x uses version 3.x of the [MongoDB Node.js driver](http://npmjs.com/package/mongodb). MongoDB driver 3.x changed the format of -the result of [`bulkWrite()` calls](http://localhost:8088/docs/api.html#model_Model.bulkWrite) so there is no longer a top-level `nInserted`, `nModified`, etc. property. The new result object structure is [described here](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult). - -```javascript -const Model = mongoose.model('Test', new Schema({ name: String })); - -const res = await Model.bulkWrite([{ insertOne: { document: { name: 'test' } } }]); - -console.log(res); -``` - -In Mongoose 4.x, the above will print: - -``` -BulkWriteResult { - ok: [Getter], - nInserted: [Getter], - nUpserted: [Getter], - nMatched: [Getter], - nModified: [Getter], - nRemoved: [Getter], - getInsertedIds: [Function], - getUpsertedIds: [Function], - getUpsertedIdAt: [Function], - getRawResponse: [Function], - hasWriteErrors: [Function], - getWriteErrorCount: [Function], - getWriteErrorAt: [Function], - getWriteErrors: [Function], - getLastOp: [Function], - getWriteConcernError: [Function], - toJSON: [Function], - toString: [Function], - isOk: [Function], - insertedCount: 1, - matchedCount: 0, - modifiedCount: 0, - deletedCount: 0, - upsertedCount: 0, - upsertedIds: {}, - insertedIds: { '0': 5be9a3101638a066702a0d38 }, - n: 1 } -``` - -In Mongoose 5.x, the script will print: - -``` -BulkWriteResult { - result: - { ok: 1, - writeErrors: [], - writeConcernErrors: [], - insertedIds: [ [Object] ], - nInserted: 1, - nUpserted: 0, - nMatched: 0, - nModified: 0, - nRemoved: 0, - upserted: [], - lastOp: { ts: [Object], t: 1 } }, - insertedCount: 1, - matchedCount: 0, - modifiedCount: 0, - deletedCount: 0, - upsertedCount: 0, - upsertedIds: {}, - insertedIds: { '0': 5be9a1c87decfc6443dd9f18 }, - n: 1 } -``` \ No newline at end of file diff --git a/node_modules/mongoose/package.json b/node_modules/mongoose/package.json deleted file mode 100644 index 344059935e3fabf223521f3544ccf074f6e1941e..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/package.json +++ /dev/null @@ -1,178 +0,0 @@ -{ - "_from": "mongoose", - "_id": "mongoose@5.4.12", - "_inBundle": false, - "_integrity": "sha512-+Xlw2JhARps/yAtMaWluJnHAidk+v38YhJNu1nX4RYleQIyXYnzFlANoD01vZyZL8X6PjOwkWDjnMFbfyy9Shg==", - "_location": "/mongoose", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "mongoose", - "name": "mongoose", - "escapedName": "mongoose", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.4.12.tgz", - "_shasum": "3c4b0d05af78a614fcdcc5abcd99c7102564ffec", - "_spec": "mongoose", - "_where": "/home/capsule_man/developpement/happy-botday", - "author": { - "name": "Guillermo Rauch", - "email": "guillermo@learnboost.com" - }, - "browser": "./browser.js", - "bugs": { - "url": "https://github.com/Automattic/mongoose/issues/new" - }, - "bundleDependencies": false, - "dependencies": { - "async": "2.6.1", - "bson": "~1.1.0", - "kareem": "2.3.0", - "mongodb": "3.1.13", - "mongodb-core": "3.1.11", - "mongoose-legacy-pluralize": "1.0.2", - "mpath": "0.5.1", - "mquery": "3.2.0", - "ms": "2.1.1", - "regexp-clone": "0.0.1", - "safe-buffer": "5.1.2", - "sliced": "1.0.1" - }, - "deprecated": false, - "description": "Mongoose MongoDB ODM", - "devDependencies": { - "acorn": "5.7.3", - "acquit": "1.0.2", - "acquit-ignore": "0.1.0", - "acquit-require": "0.1.1", - "babel-loader": "7.1.4", - "babel-preset-es2015": "6.24.1", - "benchmark": "2.1.2", - "bluebird": "3.5.0", - "chalk": "2.4.1", - "cheerio": "1.0.0-rc.2", - "co": "4.6.0", - "dox": "0.3.1", - "eslint": "5.3.0", - "highlight.js": "9.1.0", - "jade": "1.11.0", - "lodash": "4.17.11", - "markdown": "0.5.0", - "marked": "0.3.9", - "mocha": "5.2.0", - "mongodb-topology-manager": "1.0.11", - "mongoose-long": "0.2.1", - "node-static": "0.7.10", - "nyc": "11.8.0", - "power-assert": "1.4.1", - "promise-debug": "0.1.1", - "q": "1.5.1", - "semver": "5.5.0", - "uuid": "2.0.3", - "uuid-parse": "1.0.0", - "validator": "10.8.0", - "webpack": "4.16.4" - }, - "directories": { - "lib": "./lib/mongoose" - }, - "engines": { - "node": ">=4.0.0" - }, - "eslintConfig": { - "extends": [ - "eslint:recommended" - ], - "parserOptions": { - "ecmaVersion": 2015 - }, - "env": { - "node": true, - "es6": true - }, - "rules": { - "comma-style": "error", - "consistent-this": [ - "error", - "_this" - ], - "indent": [ - "error", - 2, - { - "SwitchCase": 1, - "VariableDeclarator": 2 - } - ], - "keyword-spacing": "error", - "no-buffer-constructor": "warn", - "no-console": "off", - "no-multi-spaces": "error", - "func-call-spacing": "error", - "no-trailing-spaces": "error", - "quotes": [ - "error", - "single" - ], - "semi": "error", - "space-before-blocks": "error", - "space-before-function-paren": [ - "error", - "never" - ], - "space-infix-ops": "error", - "space-unary-ops": "error", - "no-var": "warn", - "prefer-const": "warn", - "strict": [ - "error", - "global" - ], - "no-restricted-globals": [ - "error", - { - "name": "context", - "message": "Don't use Mocha's global context" - } - ] - } - }, - "homepage": "http://mongoosejs.com", - "keywords": [ - "mongodb", - "document", - "model", - "schema", - "database", - "odm", - "data", - "datastore", - "query", - "nosql", - "orm", - "db" - ], - "license": "MIT", - "main": "./index.js", - "name": "mongoose", - "repository": { - "type": "git", - "url": "git://github.com/Automattic/mongoose.git" - }, - "scripts": { - "lint": "eslint .", - "release": "git pull && git push origin master --tags && npm publish", - "release-legacy": "git pull origin 4.x && git push origin 4.x --tags && npm publish --tag legacy", - "test": "mocha --exit test/*.test.js test/**/*.test.js", - "test-cov": "nyc --reporter=html --reporter=text npm test" - }, - "version": "5.4.12" -} diff --git a/node_modules/mongoose/renovate.json b/node_modules/mongoose/renovate.json deleted file mode 100644 index 615748978ea694f6616df30704171871fd1a0776..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/renovate.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": ["config:base", ":rebaseStalePrs", ":preserveSemverRanges"], - "devDependencies": { - "enabled": false - } -} diff --git a/node_modules/mongoose/tools/auth.js b/node_modules/mongoose/tools/auth.js deleted file mode 100644 index 967f5e1f8b9dc4e5db8e99dac31610165565d60a..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/tools/auth.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -const Server = require('mongodb-topology-manager').Server; -const co = require('co'); -const mongodb = require('mongodb'); - -co(function*() { - // Create new instance - var server = new Server('mongod', { - auth: null, - dbpath: '/data/db/27017' - }); - - // Purge the directory - yield server.purge(); - - // Start process - yield server.start(); - - const db = yield mongodb.MongoClient.connect('mongodb://localhost:27017/admin'); - - yield db.addUser('passwordIsTaco', 'taco', { - roles: ['dbOwner'] - }); - - console.log('done'); -}).catch(error => { - console.error(error); - process.exit(-1); -}); diff --git a/node_modules/mongoose/tools/repl.js b/node_modules/mongoose/tools/repl.js deleted file mode 100644 index ca3b6de5618007389d6167a8aad855706f1f7bcd..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/tools/repl.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -const co = require('co'); - -co(function*() { - var ReplSet = require('mongodb-topology-manager').ReplSet; - - // Create new instance - var topology = new ReplSet('mongod', [{ - // mongod process options - options: { - bind_ip: 'localhost', port: 31000, dbpath: `/data/db/31000` - } - }, { - // mongod process options - options: { - bind_ip: 'localhost', port: 31001, dbpath: `/data/db/31001` - } - }, { - // Type of node - arbiterOnly: true, - // mongod process options - options: { - bind_ip: 'localhost', port: 31002, dbpath: `/data/db/31002` - } - }], { - replSet: 'rs' - }); - - yield topology.start(); - - console.log('done'); -}).catch(error => { - console.error(error); - process.exit(-1); -}); diff --git a/node_modules/mongoose/tools/sharded.js b/node_modules/mongoose/tools/sharded.js deleted file mode 100644 index 82cad14162caf5cb84a2a939956ee86ae967aefe..0000000000000000000000000000000000000000 --- a/node_modules/mongoose/tools/sharded.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const co = require('co'); - -co(function*() { - var Sharded = require('mongodb-topology-manager').Sharded; - - // Create new instance - var topology = new Sharded({ - mongod: 'mongod', - mongos: 'mongos' - }); - - yield topology.addShard([{ - options: { - bind_ip: 'localhost', port: 31000, dbpath: `/data/db/31000`, shardsvr: null - } - }], { replSet: 'rs1' }); - - yield topology.addConfigurationServers([{ - options: { - bind_ip: 'localhost', port: 35000, dbpath: `/data/db/35000` - } - }], { replSet: 'rs0' }); - - yield topology.addProxies([{ - bind_ip: 'localhost', port: 51000, configdb: 'localhost:35000' - }], { - binary: 'mongos' - }); - - console.log('Start...'); - // Start up topology - yield topology.start(); - - console.log('Started'); - - // Shard db - yield topology.enableSharding('test'); - - console.log('done'); -}).catch(error => { - console.error(error); - process.exit(-1); -}); diff --git a/node_modules/mpath/.travis.yml b/node_modules/mpath/.travis.yml deleted file mode 100644 index 0743746c26b1fa3c2464bdc004667b7136e359b2..0000000000000000000000000000000000000000 --- a/node_modules/mpath/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: node_js -node_js: - - "0.10" - - "0.12" - - "4" - - "5" - - "6" - - "7" - - "8" - - "9" - - "10" diff --git a/node_modules/mpath/History.md b/node_modules/mpath/History.md deleted file mode 100644 index b7ab531d4b2e944374d9e2a8944b526d8df657d7..0000000000000000000000000000000000000000 --- a/node_modules/mpath/History.md +++ /dev/null @@ -1,51 +0,0 @@ -0.5.1 / 2018-08-30 -================== - * fix: prevent writing to constructor and prototype as well as __proto__ - -0.5.0 / 2018-08-30 -================== - * BREAKING CHANGE: disallow setting/unsetting __proto__ properties - * feat: re-add support for Node < 4 for this release - -0.4.1 / 2018-04-08 -================== - * fix: allow opting out of weird `$` set behavior re: Automattic/mongoose#6273 - -0.4.0 / 2018-03-27 -================== - * feat: add support for ES6 maps - * BREAKING CHANGE: drop support for Node < 4 - -0.3.0 / 2017-06-05 -================== - * feat: add has() and unset() functions - -0.2.1 / 2013-03-22 -================== - - * test; added for #5 - * fix typo that breaks set #5 [Contra](https://github.com/Contra) - -0.2.0 / 2013-03-15 -================== - - * added; adapter support for set - * added; adapter support for get - * add basic benchmarks - * add support for using module as a component #2 [Contra](https://github.com/Contra) - -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/mpath/LICENSE b/node_modules/mpath/LICENSE deleted file mode 100644 index 38c529daa677faf963fc24fcd00cdb5b61f07102..0000000000000000000000000000000000000000 --- a/node_modules/mpath/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(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/mpath/Makefile b/node_modules/mpath/Makefile deleted file mode 100644 index 8d6a79c019eadd797be41d87aa892a882b413646..0000000000000000000000000000000000000000 --- a/node_modules/mpath/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -bench: - node bench.js - -.PHONY: test diff --git a/node_modules/mpath/README.md b/node_modules/mpath/README.md deleted file mode 100644 index 9831dd066c482a7350e9acdb16ee266394951dad..0000000000000000000000000000000000000000 --- a/node_modules/mpath/README.md +++ /dev/null @@ -1,278 +0,0 @@ -#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/mpath/bench.js b/node_modules/mpath/bench.js deleted file mode 100644 index 7ec6a875c8076fa47fa1b9ef203c56f758cf1cd8..0000000000000000000000000000000000000000 --- a/node_modules/mpath/bench.js +++ /dev/null @@ -1,109 +0,0 @@ - -var mpath = require('./') -var Bench = require('benchmark'); -var sha = require('child_process').exec("git log --pretty=format:'%h' -n 1", function (err, sha) { - if (err) throw err; - - var fs = require('fs') - var filename = __dirname + '/bench.out'; - var out = fs.createWriteStream(filename, { flags: 'a', encoding: 'utf8' }); - - /** - * 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; - } - - var o = doc(); - - var s = new Bench.Suite; - s.add('mpath.get("first", obj)', function () { - mpath.get('first', o); - }) - s.add('mpath.get("first.second", obj)', function () { - mpath.get('first.second', o); - }) - s.add('mpath.get("first.second.third.1.name", obj)', function () { - mpath.get('first.second.third.1.name', o); - }) - s.add('mpath.get("comments", obj)', function () { - mpath.get('comments', o); - }) - s.add('mpath.get("comments.1", obj)', function () { - mpath.get('comments.1', o); - }) - s.add('mpath.get("comments.2.name", obj)', function () { - mpath.get('comments.2.name', o); - }) - s.add('mpath.get("comments.2.comments.1.comments.0.val", obj)', function () { - mpath.get('comments.2.comments.1.comments.0.val', o); - }) - s.add('mpath.get("comments.name", obj)', function () { - mpath.get('comments.name', o); - }) - - s.add('mpath.set("first", obj, val)', function () { - mpath.set('first', o, 1); - }) - s.add('mpath.set("first.second", obj, val)', function () { - mpath.set('first.second', o, 1); - }) - s.add('mpath.set("first.second.third.1.name", obj, val)', function () { - mpath.set('first.second.third.1.name', o, 1); - }) - s.add('mpath.set("comments", obj, val)', function () { - mpath.set('comments', o, 1); - }) - s.add('mpath.set("comments.1", obj, val)', function () { - mpath.set('comments.1', o, 1); - }) - s.add('mpath.set("comments.2.name", obj, val)', function () { - mpath.set('comments.2.name', o, 1); - }) - s.add('mpath.set("comments.2.comments.1.comments.0.val", obj, val)', function () { - mpath.set('comments.2.comments.1.comments.0.val', o, 1); - }) - s.add('mpath.set("comments.name", obj, val)', function () { - mpath.set('comments.name', o, 1); - }) - - s.on('start', function () { - console.log('starting...'); - out.write('*' + sha + ': ' + String(new Date()) + '\n'); - }); - s.on('cycle', function (e) { - var s = String(e.target); - console.log(s); - out.write(s + '\n'); - }) - s.on('complete', function () { - console.log('done') - out.end(''); - }) - s.run() -}) - diff --git a/node_modules/mpath/bench.log b/node_modules/mpath/bench.log deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/node_modules/mpath/bench.out b/node_modules/mpath/bench.out deleted file mode 100644 index b9b0371d37588479b6231de01a770e803c5ec646..0000000000000000000000000000000000000000 --- a/node_modules/mpath/bench.out +++ /dev/null @@ -1,52 +0,0 @@ -*b566c26: Fri Mar 15 2013 14:14:04 GMT-0700 (PDT) -mpath.get("first", obj) x 3,827,405 ops/sec ±0.91% (90 runs sampled) -mpath.get("first.second", obj) x 4,930,222 ops/sec ±1.92% (91 runs sampled) -mpath.get("first.second.third.1.name", obj) x 3,070,837 ops/sec ±1.45% (97 runs sampled) -mpath.get("comments", obj) x 3,649,771 ops/sec ±1.71% (93 runs sampled) -mpath.get("comments.1", obj) x 3,846,728 ops/sec ±0.86% (94 runs sampled) -mpath.get("comments.2.name", obj) x 3,527,680 ops/sec ±0.95% (96 runs sampled) -mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,046,982 ops/sec ±0.80% (96 runs sampled) -mpath.get("comments.name", obj) x 625,546 ops/sec ±2.02% (82 runs sampled) -*e42bdb1: Fri Mar 15 2013 14:19:28 GMT-0700 (PDT) -mpath.get("first", obj) x 3,700,783 ops/sec ±1.30% (95 runs sampled) -mpath.get("first.second", obj) x 4,621,795 ops/sec ±0.86% (95 runs sampled) -mpath.get("first.second.third.1.name", obj) x 3,012,671 ops/sec ±1.21% (100 runs sampled) -mpath.get("comments", obj) x 3,677,694 ops/sec ±0.80% (96 runs sampled) -mpath.get("comments.1", obj) x 3,798,862 ops/sec ±0.81% (91 runs sampled) -mpath.get("comments.2.name", obj) x 3,489,356 ops/sec ±0.66% (98 runs sampled) -mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,004,076 ops/sec ±0.85% (99 runs sampled) -mpath.get("comments.name", obj) x 613,270 ops/sec ±1.33% (83 runs sampled) -*0521aac: Fri Mar 15 2013 16:37:16 GMT-0700 (PDT) -mpath.get("first", obj) x 3,834,755 ops/sec ±0.70% (100 runs sampled) -mpath.get("first.second", obj) x 4,999,965 ops/sec ±1.01% (98 runs sampled) -mpath.get("first.second.third.1.name", obj) x 3,125,953 ops/sec ±0.97% (100 runs sampled) -mpath.get("comments", obj) x 3,759,233 ops/sec ±0.81% (97 runs sampled) -mpath.get("comments.1", obj) x 3,894,893 ops/sec ±0.76% (96 runs sampled) -mpath.get("comments.2.name", obj) x 3,576,929 ops/sec ±0.68% (98 runs sampled) -mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,149,610 ops/sec ±0.67% (97 runs sampled) -mpath.get("comments.name", obj) x 629,259 ops/sec ±1.30% (87 runs sampled) -mpath.set("first", obj, val) x 2,869,477 ops/sec ±0.63% (97 runs sampled) -mpath.set("first.second", obj, val) x 2,418,751 ops/sec ±0.62% (98 runs sampled) -mpath.set("first.second.third.1.name", obj, val) x 2,313,099 ops/sec ±0.69% (94 runs sampled) -mpath.set("comments", obj, val) x 2,680,882 ops/sec ±0.76% (99 runs sampled) -mpath.set("comments.1", obj, val) x 2,401,829 ops/sec ±0.68% (98 runs sampled) -mpath.set("comments.2.name", obj, val) x 2,335,081 ops/sec ±1.07% (96 runs sampled) -mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,245,436 ops/sec ±0.76% (92 runs sampled) -mpath.set("comments.name", obj, val) x 2,356,278 ops/sec ±1.15% (100 runs sampled) -*97e85d3: Fri Mar 15 2013 16:39:21 GMT-0700 (PDT) -mpath.get("first", obj) x 3,837,614 ops/sec ±0.74% (99 runs sampled) -mpath.get("first.second", obj) x 4,991,779 ops/sec ±1.01% (94 runs sampled) -mpath.get("first.second.third.1.name", obj) x 3,078,455 ops/sec ±1.17% (96 runs sampled) -mpath.get("comments", obj) x 3,770,961 ops/sec ±0.45% (101 runs sampled) -mpath.get("comments.1", obj) x 3,832,814 ops/sec ±0.67% (92 runs sampled) -mpath.get("comments.2.name", obj) x 3,536,436 ops/sec ±0.49% (100 runs sampled) -mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,141,947 ops/sec ±0.72% (98 runs sampled) -mpath.get("comments.name", obj) x 667,898 ops/sec ±1.62% (85 runs sampled) -mpath.set("first", obj, val) x 2,642,517 ops/sec ±0.72% (98 runs sampled) -mpath.set("first.second", obj, val) x 2,502,124 ops/sec ±1.28% (99 runs sampled) -mpath.set("first.second.third.1.name", obj, val) x 2,426,804 ops/sec ±0.55% (99 runs sampled) -mpath.set("comments", obj, val) x 2,699,478 ops/sec ±0.85% (98 runs sampled) -mpath.set("comments.1", obj, val) x 2,494,454 ops/sec ±1.05% (96 runs sampled) -mpath.set("comments.2.name", obj, val) x 2,463,894 ops/sec ±0.86% (98 runs sampled) -mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,320,398 ops/sec ±0.82% (95 runs sampled) -mpath.set("comments.name", obj, val) x 2,512,408 ops/sec ±0.77% (95 runs sampled) diff --git a/node_modules/mpath/component.json b/node_modules/mpath/component.json deleted file mode 100644 index 53c28467e18c6b233657a0434b828463c56d0988..0000000000000000000000000000000000000000 --- a/node_modules/mpath/component.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "mpath", - "version": "0.2.1", - "main": "lib/index.js", - "scripts": [ - "lib/index.js" - ] -} diff --git a/node_modules/mpath/index.js b/node_modules/mpath/index.js deleted file mode 100644 index f7b65dd590f7a237c1ddbefbcb502e16b899223c..0000000000000000000000000000000000000000 --- a/node_modules/mpath/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = exports = require('./lib'); diff --git a/node_modules/mpath/lib/index.js b/node_modules/mpath/lib/index.js deleted file mode 100644 index c8ac5b6d6c0fd5e4f23e822850caf51258a1ac3c..0000000000000000000000000000000000000000 --- a/node_modules/mpath/lib/index.js +++ /dev/null @@ -1,299 +0,0 @@ -// Make sure Map exists for old Node.js versions -var Map = global.Map != null ? global.Map : function() {}; - -// These properties are special and can open client libraries to security -// issues -var ignoreProperties = ['__proto__', 'constructor', 'prototype']; - -/** - * 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) { - var lookup; - - if ('function' == typeof special) { - if (special.length < 2) { - map = special; - special = undefined; - } else { - lookup = 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 || lookup, map) - : map(undefined); - }); - } - - if (lookup) { - obj = lookup(obj, part); - } else { - var _from = special && obj[special] ? obj[special] : obj; - obj = _from instanceof Map ? - _from.get(part) : - _from[part]; - } - - if (!obj) return map(obj); - } - - return map(obj); -}; - -/** - * Returns true if `in` returns true for every piece of the path - * - * @param {String} path - * @param {Object} o - */ - -exports.has = function (path, o) { - var parts = typeof path === 'string' ? - path.split('.') : - path; - - if (!Array.isArray(parts)) { - throw new TypeError('Invalid `path`. Must be either string or array'); - } - - var len = parts.length; - var cur = o; - for (var i = 0; i < len; ++i) { - if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { - return false; - } - cur = cur[parts[i]]; - } - - return true; -}; - -/** - * Deletes the last piece of `path` - * - * @param {String} path - * @param {Object} o - */ - -exports.unset = function (path, o) { - var parts = typeof path === 'string' ? - path.split('.') : - path; - - if (!Array.isArray(parts)) { - throw new TypeError('Invalid `path`. Must be either string or array'); - } - - var len = parts.length; - var cur = o; - for (var i = 0; i < len; ++i) { - if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { - return false; - } - // Disallow any updates to __proto__ or special properties. - if (ignoreProperties.indexOf(parts[i]) !== -1) { - return false; - } - if (i === len - 1) { - delete cur[parts[i]]; - return true; - } - cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]]; - } - - return true; -}; - -/** - * 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) { - var lookup; - - if ('function' == typeof special) { - if (special.length < 2) { - map = special; - special = undefined; - } else { - lookup = 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; - - for (var i = 0; i < parts.length; ++i) { - // Silently ignore any updates to `__proto__`, these are potentially - // dangerous if using mpath with unsanitized data. - if (ignoreProperties.indexOf(parts[i]) !== -1) { - 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. Unless the user explicitly opted out by passing - // false, see Automattic/mongoose#6273 - var copy = _copying || (/\$/.test(path) && _copying !== false) - , 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 || lookup, map, copy); - } - } else { - for (var j = 0; j < obj.length; ++j) { - // assignment of entire value - exports.set(paths, val, obj[j], special || lookup, map, copy); - } - } - return; - } - - if (lookup) { - obj = lookup(obj, part); - } else { - var _to = special && obj[special] ? obj[special] : obj; - obj = _to instanceof Map ? - _to.get(part) : - _to[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 (lookup) { - lookup(item, part, map(val[j])); - } else { - 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 (lookup) { - lookup(item, part, map(val)); - } else { - if (item[special]) item = item[special]; - item[part] = map(val); - } - } - } - } - } else { - if (lookup) { - lookup(obj, part, map(val)); - } else if (obj instanceof Map) { - obj.set(part, map(val)); - } else { - obj[part] = map(val); - } - } -} - -/*! - * Returns the value passed to it. - */ - -function K (v) { - return v; -} diff --git a/node_modules/mpath/package.json b/node_modules/mpath/package.json deleted file mode 100644 index 8d758eb542efb0f12c76fb142dfae5a16f8031be..0000000000000000000000000000000000000000 --- a/node_modules/mpath/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "_from": "mpath@0.5.1", - "_id": "mpath@0.5.1", - "_inBundle": false, - "_integrity": "sha512-H8OVQ+QEz82sch4wbODFOz+3YQ61FYz/z3eJ5pIdbMEaUzDqA268Wd+Vt4Paw9TJfvDgVKaayC0gBzMIw2jhsg==", - "_location": "/mpath", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mpath@0.5.1", - "name": "mpath", - "escapedName": "mpath", - "rawSpec": "0.5.1", - "saveSpec": null, - "fetchSpec": "0.5.1" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/mpath/-/mpath-0.5.1.tgz", - "_shasum": "17131501f1ff9e6e4fbc8ffa875aa7065b5775ab", - "_spec": "mpath@0.5.1", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongoose", - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "bugs": { - "url": "https://github.com/aheckmann/mpath/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "{G,S}et object values using MongoDB-like path notation", - "devDependencies": { - "benchmark": "~1.0.0", - "mocha": "1.8.1" - }, - "engines": { - "node": ">=4.0.0" - }, - "homepage": "https://github.com/aheckmann/mpath#readme", - "keywords": [ - "mongodb", - "path", - "get", - "set" - ], - "license": "MIT", - "main": "index.js", - "name": "mpath", - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mpath.git" - }, - "scripts": { - "test": "mocha test/*" - }, - "version": "0.5.1" -} diff --git a/node_modules/mpath/test/index.js b/node_modules/mpath/test/index.js deleted file mode 100644 index 4ad4e5dd5db920a6fbadc572b83c08f0345bd503..0000000000000000000000000000000000000000 --- a/node_modules/mpath/test/index.js +++ /dev/null @@ -1,1857 +0,0 @@ - -/** - * 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(){ - describe('that is a string', 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('that is a function', function(){ - var special = function (obj, key) { - return obj[key] - } - - 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('two', mpath.get('comments.1.name', o, special)); - assert.deepEqual('three', mpath.get('comments.2.name', o, special)); - assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function (v) { - return 'three' === v ? 'nice' : v; - })); - - assert.deepEqual([{},{ comments: [{ val: 'twoo' }] }] - , mpath.get('comments.2.comments', o, special)); - - assert.deepEqual({ comments: [{val: 'twoo'}]} - , mpath.get('comments.2.comments.1', o, special)); - - assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o, special)); - - var overide = false; - assert.deepEqual('twoo', mpath.get('comments.8.comments.1.comments.0.val', o, function (obj, path) { - if (Array.isArray(obj) && 8 == path) { - overide = true; - return obj[2]; - } - return obj[path]; - })); - assert.ok(overide); - - done(); - }) - - it('in combination with map', function(done){ - var special = function (obj, key) { - if (Array.isArray(obj)) return obj[key]; - return obj.mpath; - } - var map = function (val) { - return 'convert' == val - ? 'mpath' - : val; - } - var o = { mpath: [{ mpath: 'converse' }, { mpath: 'convert' }] } - - assert.equal('mpath', mpath.get('something.1.kewl', o, special, map)); - done(); - }) - }) - }) - }) - - describe('set', function() { - it('prevents writing to __proto__', function() { - var obj = {}; - mpath.set('__proto__.x', 'foobar', obj); - assert.ok(!({}.x)); - - mpath.set('constructor.prototype.x', 'foobar', obj); - assert.ok(!({}.x)); - }); - - 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('that is a function', function(){ - describe('without map', function(){ - it('works on array value', function(done){ - var o = { hello: { world: [{ how: 'are' }, { you: '?' }] }}; - var special = function (obj, key, val) { - if (val) { - obj[key] = val; - } else { - return 'thing' == key - ? obj.world - : obj[key] - } - } - mpath.set('hello.thing.how', 'arrrr', o, special); - assert.deepEqual(o, { hello: { world: [{ how: 'arrrr' }, { you: '?', how: 'arrrr' }] }}); - done(); - }) - it('works on non-array value', function(done){ - var o = { hello: { world: { how: 'are you' }}}; - var special = function (obj, key, val) { - if (val) { - obj[key] = val; - } else { - return 'thing' == key - ? obj.world - : obj[key] - } - } - mpath.set('hello.thing.how', 'RU', o, special); - assert.deepEqual(o, { hello: { world: { how: 'RU' }}}); - done(); - }) - }) - it('works with map', function(done){ - var o = { hello: { world: [{ how: 'are' }, { you: '?' }] }}; - var special = function (obj, key, val) { - if (val) { - obj[key] = val; - } else { - return 'thing' == key - ? obj.world - : obj[key] - } - } - var map = function (val) { - return 'convert' == val - ? 'ºº' - : val - } - mpath.set('hello.thing.how', 'convert', o, special, map); - assert.deepEqual(o, { hello: { world: [{ how: 'ºº' }, { you: '?', how: 'ºº' }] }}); - 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('has', function(done) { - assert.ok(mpath.has('a', { a: 1 })); - assert.ok(mpath.has('a', { a: undefined })); - assert.ok(!mpath.has('a', {})); - assert.ok(!mpath.has('a', null)); - - assert.ok(mpath.has('a.b', { a: { b: 1 } })); - assert.ok(mpath.has('a.b', { a: { b: undefined } })); - assert.ok(!mpath.has('a.b', { a: 1 })); - assert.ok(!mpath.has('a.b', { a: null })); - - done(); - }); - - it('underneath a map', function(done) { - if (!global.Map) { - done(); - return; - } - assert.equal(mpath.get('a.b', { a: new Map([['b', 1]]) }), 1); - - var m = new Map([['b', 1]]); - var obj = { a: m }; - mpath.set('a.c', 2, obj); - assert.equal(m.get('c'), 2); - - done(); - }); - - it('unset', function(done) { - var o = { a: 1 }; - mpath.unset('a', o); - assert.deepEqual(o, {}); - - o = { a: { b: 1 } }; - mpath.unset('a.b', o); - assert.deepEqual(o, { a: {} }); - - o = { a: null }; - mpath.unset('a.b', o); - assert.deepEqual(o, { a: null }); - - done(); - }); - - it('unset with __proto__', function(done) { - // Should refuse to set __proto__ - function Clazz() {} - Clazz.prototype.foobar = true; - - mpath.unset('__proto__.foobar', new Clazz()); - assert.ok(Clazz.prototype.foobar); - - mpath.unset('constructor.prototype.foobar', new Clazz()); - assert.ok(Clazz.prototype.foobar); - - 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/mquery/.eslintignore b/node_modules/mquery/.eslintignore deleted file mode 100644 index 4b4d863104f46ec8845711cbe235ca3ac08b3654..0000000000000000000000000000000000000000 --- a/node_modules/mquery/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -coverage/ \ No newline at end of file diff --git a/node_modules/mquery/.travis.yml b/node_modules/mquery/.travis.yml deleted file mode 100644 index de18290871948f744ebe48f08162caafce9e6cf9..0000000000000000000000000000000000000000 --- a/node_modules/mquery/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: node_js -node_js: - - "4" - - "5" - - "6" - - "7" - - "8" - - "9" - - "10" -script: - - npm test - - npm run lint -services: - - mongodb diff --git a/node_modules/mquery/History.md b/node_modules/mquery/History.md deleted file mode 100644 index 92382768e482f6387b9f6c8d12f70ad0ecb8b9b4..0000000000000000000000000000000000000000 --- a/node_modules/mquery/History.md +++ /dev/null @@ -1,334 +0,0 @@ -3.2.0 / 2018-08-24 -================== - * feat: add $useProjection to opt in to using `projection` instead of `fields` re: MongoDB deprecation warnings Automattic/mongoose#6880 - -3.1.2 / 2018-08-01 -================== - * chore: move eslint to devDependencies #110 [jakesjews](https://github.com/jakesjews) - -3.1.1 / 2018-07-30 -================== - * chore: add eslint #107 [Fonger](https://github.com/Fonger) - * docs: clean up readConcern docs #106 [Fonger](https://github.com/Fonger) - -3.1.0 / 2018-07-29 -================== - * feat: add `readConcern()` helper #105 [Fonger](https://github.com/Fonger) - * feat: add `maxTimeMS()` as alias of `maxTime()` #105 [Fonger](https://github.com/Fonger) - * feat: add `collation()` helper #105 [Fonger](https://github.com/Fonger) - -3.0.1 / 2018-07-02 -================== - * fix: parse sort array options correctly #103 #102 [Fonger](https://github.com/Fonger) - -3.0.0 / 2018-01-20 -================== - * chore: upgrade deps and add nsp - -3.0.0-rc0 / 2017-12-06 -====================== - * BREAKING CHANGE: remove support for node < 4 - * BREAKING CHANGE: remove support for retainKeyOrder, will always be true by default re: Automattic/mongoose#2749 - -2.3.3 / 2017-11-19 -================== - * fixed; catch sync errors in cursor.toArray() re: Automattic/mongoose#5812 - -2.3.2 / 2017-09-27 -================== - * fixed; bumped debug -> 2.6.9 re: #89 - -2.3.1 / 2017-05-22 -================== - * fixed; bumped debug -> 2.6.7 re: #86 - -2.3.0 / 2017-03-05 -================== - * added; replaceOne function - * added; deleteOne and deleteMany functions - -2.2.3 / 2017-01-31 -================== - * fixed; throw correct error when passing incorrectly formatted array to sort() - -2.2.2 / 2017-01-31 -================== - * fixed; allow passing maps to sort() - -2.2.1 / 2017-01-29 -================== - * fixed; allow passing string to hint() - -2.2.0 / 2017-01-08 -================== - * added; updateOne and updateMany functions - -2.1.0 / 2016-12-22 -================== - * added; ability to pass an array to select() #81 [dciccale](https://github.com/dciccale) - -2.0.0 / 2016-09-25 -================== - * added; support for mongodb driver 2.0 streams - -1.12.0 / 2016-09-25 -=================== - * added; `retainKeyOrder` option re: Automattic/mongoose#4542 - -1.11.0 / 2016-06-04 -=================== - * added; `.minDistance()` helper and minDistance for `.near()` Automattic/mongoose#4179 - -1.10.1 / 2016-04-26 -=================== - * fixed; ensure conditions is an object before assigning #75 - -1.10.0 / 2016-03-16 -================== - - * updated; bluebird to latest 2.10.2 version #74 [matskiv](https://github.com/matskiv) - -1.9.0 / 2016-03-15 -================== - * added; `.eq` as a shortcut for `.equals` #72 [Fonger](https://github.com/Fonger) - * added; ability to use array syntax for sort re: https://jira.mongodb.org/browse/NODE-578 #67 - -1.8.0 / 2016-03-01 -================== - * fixed; dont throw an error if count used with sort or select Automattic/mongoose#3914 - -1.7.0 / 2016-02-23 -================== - * fixed; don't treat objects with a length property as argument objects #70 - * added; `.findCursor()` method #69 [nswbmw](https://github.com/nswbmw) - * added; `_compiledUpdate` property #68 [nswbmw](https://github.com/nswbmw) - -1.6.2 / 2015-07-12 -================== - - * fixed; support exec cb being called synchronously #66 - -1.6.1 / 2015-06-16 -================== - - * fixed; do not treat $meta projection as inclusive [vkarpov15](https://github.com/vkarpov15) - -1.6.0 / 2015-05-27 -================== - - * update dependencies #65 [bachp](https://github.com/bachp) - -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/mquery/LICENSE b/node_modules/mquery/LICENSE deleted file mode 100644 index 38c529daa677faf963fc24fcd00cdb5b61f07102..0000000000000000000000000000000000000000 --- a/node_modules/mquery/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(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/mquery/Makefile b/node_modules/mquery/Makefile deleted file mode 100644 index 587655db2569dc9acaa8d98c2c83dc2a3b0785a0..0000000000000000000000000000000000000000 --- a/node_modules/mquery/Makefile +++ /dev/null @@ -1,26 +0,0 @@ - -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 - -lint: - @NODE_ENV=test node ./node_modules/eslint/bin/eslint.js . - -test-travis: - @NODE_ENV=test node \ - node_modules/.bin/istanbul cover \ - ./node_modules/.bin/_mocha \ - --report lcovonly \ - --bail - @NODE_ENV=test node \ - ./node_modules/eslint/bin/eslint.js . - -.PHONY: test test-cov open-cov lint test-travis diff --git a/node_modules/mquery/README.md b/node_modules/mquery/README.md deleted file mode 100644 index 58d632287be8f638502fca2a562eb1cb83e42893..0000000000000000000000000000000000000000 --- a/node_modules/mquery/README.md +++ /dev/null @@ -1,1375 +0,0 @@ -# mquery - -`mquery` is a fluent mongodb query builder designed to run in multiple environments. - -[](https://travis-ci.org/aheckmann/mquery) -[](http://badge.fury.io/js/mquery) - -[](https://www.npmjs.com/package/mquery) - -## 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 - -## 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) -- [findOneAndDelete, 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) -- [collation](#collation) -- [comment](#comment) -- [hint](#hint) -- [j](#j) -- [limit](#limit) -- [maxScan](#maxscan) -- [maxTime, maxTimeMS](#maxtime) -- [skip](#skip) -- [sort](#sort) -- [read, setReadPreference](#read) -- [readConcern, r](#readconcern) -- [slaveOk](#slaveok) -- [snapshot](#snapshot) -- [tailable](#tailable) -- [writeConcern, w](#writeconcern) -- [wtimeout, wTimeout](#wtimeout) - -## 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. Alias of findOneAndDelete. -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().findOneAndDelete() -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/) - -### collation() - -Specifies the collation option. - -```js -query.collation({ locale: "en_US", strength: 1 }) -``` - -[MongoDB documentation](https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation) - -### 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/) - -### j() - -Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal. - -This option is only valid for operations that write to the database: - -- `deleteOne()` -- `deleteMany()` -- `findOneAndDelete()` -- `findOneAndUpdate()` -- `remove()` -- `update()` -- `updateOne()` -- `updateMany()` - -Defaults to the `j` value if it is specified in [writeConcern](#writeconcern) - -```js -mquery().j(true); -``` - -### 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) -query.maxTimeMS(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 - -mquery().setReadPreference('primary') // alias of .read() -``` - -##### 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). - - -### readConcern() - -Sets the readConcern option for the query. - -```js -// local -mquery().readConcern('local') -mquery().readConcern('l') -mquery().r('l') - -// available -mquery().readConcern('available') -mquery().readConcern('a') -mquery().r('a') - -// majority -mquery().readConcern('majority') -mquery().readConcern('m') -mquery().r('m') - -// linearizable -mquery().readConcern('linearizable') -mquery().readConcern('lz') -mquery().r('lz') - -// snapshot -mquery().readConcern('snapshot') -mquery().readConcern('s') -mquery().r('s') -``` - -##### Read Concern Level: - -- `local` - The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). (MongoDB 3.2+) -- `available` - The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). (MongoDB 3.6+) -- `majority` - The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. (MongoDB 3.2+) -- `linearizable` - The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. (MongoDB 3.4+) -- `snapshot` - Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. (MongoDB 4.0+) - -Aliases - -- `l` local -- `a` available -- `m` majority -- `lz` linearizable -- `s` snapshot - -Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). - -### writeConcern() - -Sets the writeConcern option for the query. - -This option is only valid for operations that write to the database: - -- `deleteOne()` -- `deleteMany()` -- `findOneAndDelete()` -- `findOneAndUpdate()` -- `remove()` -- `update()` -- `updateOne()` -- `updateMany()` - -```js -mquery().writeConcern(0) -mquery().writeConcern(1) -mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 }) -mquery().writeConcern('majority') -mquery().writeConcern('m') // same as majority -mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead -mquery().w(1) // w is alias of writeConcern -``` - -##### Write Concern: - -writeConcern({ w: `<value>`, j: `<boolean>`, wtimeout: `<number>` }`) - -- the w option to request acknowledgement that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags -- the j option to request acknowledgement that the write operation has been written to the journal -- the wtimeout option to specify a time limit to prevent write operations from blocking indefinitely - -Can be break down to use the following syntax: - -mquery().w(`<value>`).j(`<boolean>`).wtimeout(`<number>`) - -Read more about how to use write concern [here](https://docs.mongodb.com/manual/reference/write-concern/) - -### 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/) - -### wtimeout() - -Specifies a time limit, in milliseconds, for the write concern. If `w > 1`, it is maximum amount of time to -wait for this write to propagate through the replica set before this operation fails. The default is `0`, which means no timeout. - -This option is only valid for operations that write to the database: - -- `deleteOne()` -- `deleteMany()` -- `findOneAndDelete()` -- `findOneAndUpdate()` -- `remove()` -- `update()` -- `updateOne()` -- `updateMany()` - -Defaults to `wtimeout` value if it is specified in [writeConcern](#writeconcern) - -```js -mquery().wtimeout(2000) -mquery().wTimeout(2000) -``` - -## 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 mquery instance is passed, its match conditions, field selection and options are merged. - -```js -var drum = mquery({ type: 'drum' }).collection(instruments); -var redDrum = mquery({ 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/mquery/lib/collection/collection.js b/node_modules/mquery/lib/collection/collection.js deleted file mode 100644 index 0f39c76b3e7c128016353b8c08fb47b06028627a..0000000000000000000000000000000000000000 --- a/node_modules/mquery/lib/collection/collection.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -/** - * methods a collection must implement - */ - -var methods = [ - 'find', - 'findOne', - 'update', - 'updateMany', - 'updateOne', - 'replaceOne', - 'remove', - 'count', - 'distinct', - 'findAndModify', - 'aggregate', - 'findStream', - 'deleteOne', - 'deleteMany' -]; - -/** - * 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/mquery/lib/collection/index.js b/node_modules/mquery/lib/collection/index.js deleted file mode 100644 index 1992e201eb9a81cbda175a7b2b6378f54559d531..0000000000000000000000000000000000000000 --- a/node_modules/mquery/lib/collection/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'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/mquery/lib/collection/node.js b/node_modules/mquery/lib/collection/node.js deleted file mode 100644 index cc07d607275575bbd828890e5493e77080710b42..0000000000000000000000000000000000000000 --- a/node_modules/mquery/lib/collection/node.js +++ /dev/null @@ -1,151 +0,0 @@ -'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); - - try { - cursor.toArray(cb); - } catch (error) { - cb(error); - } - }); -}; - -/** - * 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); -}; - -/** - * update(match, update, options, function(err[, result])) - */ - -NodeCollection.prototype.updateMany = function(match, update, options, cb) { - this.collection.updateMany(match, update, options, cb); -}; - -/** - * update(match, update, options, function(err[, result])) - */ - -NodeCollection.prototype.updateOne = function(match, update, options, cb) { - this.collection.updateOne(match, update, options, cb); -}; - -/** - * replaceOne(match, update, options, function(err[, result])) - */ - -NodeCollection.prototype.replaceOne = function(match, update, options, cb) { - this.collection.replaceOne(match, update, options, cb); -}; - -/** - * deleteOne(match, options, function(err[, result]) - */ - -NodeCollection.prototype.deleteOne = function(match, options, cb) { - this.collection.deleteOne(match, options, cb); -}; - -/** - * deleteMany(match, options, function(err[, result]) - */ - -NodeCollection.prototype.deleteMany = function(match, options, cb) { - this.collection.deleteMany(match, 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); -}; - -/** - * var cursor = findCursor(match, findOptions) - */ - -NodeCollection.prototype.findCursor = function(match, findOptions) { - return this.collection.find(match, findOptions); -}; - -/** - * aggregation(operators..., function(err, doc)) - * TODO - */ - -/** - * Expose - */ - -module.exports = exports = NodeCollection; diff --git a/node_modules/mquery/lib/env.js b/node_modules/mquery/lib/env.js deleted file mode 100644 index d3d225b7c911143dc768b1b9060a42826b22f5c6..0000000000000000000000000000000000000000 --- a/node_modules/mquery/lib/env.js +++ /dev/null @@ -1,22 +0,0 @@ -'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/mquery/lib/mquery.js b/node_modules/mquery/lib/mquery.js deleted file mode 100644 index 9d82cff1a8a3fa7d46e7a2a20972c8a0cd3d6feb..0000000000000000000000000000000000000000 --- a/node_modules/mquery/lib/mquery.js +++ /dev/null @@ -1,3253 +0,0 @@ -'use strict'; - -/** - * Dependencies - */ - -var slice = require('sliced'); -var assert = require('assert'); -var util = require('util'); -var utils = require('./utils'); -var debug = require('debug')('mquery'); - -/* global Map */ - -/** - * 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; -}; - -/** - * Adds a collation to this op (MongoDB 3.4 and up) - * - * ####Example - * - * query.find().collation({ locale: "en_US", strength: 1 }) - * - * @param {Object} value - * @return {Query} this - * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation - * @api public - */ - -Query.prototype.collation = function(value) { - this.options.collation = value; - 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 the complementary comparison value for paths specified with `where()` - * This is alias of `equals` - * - * ####Example - * - * User.where('age').eq(49); - * - * // is the same as - * - * User.shere('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @param {Object} val - * @return {Query} this - * @api public - */ - -Query.prototype.eq = function eq(val) { - this._ensurePath('eq'); - 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 {String|RegExp} 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 minDistance'.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] === null || typeof this._conditions[path] === 'object' ? - 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; - } - if (null != val.minDistance) { - conds.$minDistance = val.minDistance; - } - } 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; - } - if ('minDistance' in val) { - conds[type]['$minDistance'] = val.minDistance; - } - } - - 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; - var i, len; - - if (('string' == type || utils.isArgumentsObject(arg)) && - 'number' == typeof arg.length || Array.isArray(arg)) { - if ('string' == type) - arg = arg.split(/\s+/); - - for (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)) { - var keys = utils.keys(arg); - for (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'); - * query.sort([['field', 1], ['test', -1]]); - * - * ####Note - * - * - The array syntax `.sort([['field', 1], ['test', -1]])` can only be used with [mongodb driver >= 2.0.46](https://github.com/mongodb/node-mongodb-native/blob/2.1/HISTORY.md#2046-2015-10-15). - * - Cannot be used with `distinct()` - * - * @param {Object|String|Array} arg - * @return {Query} this - * @api public - */ - -Query.prototype.sort = function(arg) { - if (!arg) return this; - var i, len, field; - - this._validate('sort'); - - var type = typeof arg; - - // .sort([['field', 1], ['test', -1]]) - if (Array.isArray(arg)) { - len = arg.length; - for (i = 0; i < arg.length; ++i) { - if (!Array.isArray(arg[i])) { - throw new Error('Invalid sort() argument, must be array of arrays'); - } - _pushArr(this.options, arg[i][0], arg[i][1]); - } - return this; - } - - // .sort('field -test') - if (1 === arguments.length && 'string' == type) { - arg = arg.split(/\s+/); - len = arg.length; - for (i = 0; i < len; ++i) { - 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; - } - - // .sort({ field: 1, test: -1 }) - if (utils.isObject(arg)) { - var keys = utils.keys(arg); - for (i = 0; i < keys.length; ++i) { - field = keys[i]; - push(this.options, field, arg[field]); - } - - return this; - } - - if (typeof Map !== 'undefined' && arg instanceof Map) { - _pushMap(this.options, arg); - return this; - } - throw new TypeError('Invalid sort() argument. Must be a string, object, or array.'); -}; - -/*! - * @ignore - */ - -var _validSortValue = { - '1': 1, - '-1': -1, - 'asc': 1, - 'ascending': 1, - 'desc': -1, - 'descending': -1 -}; - -function push(opts, field, value) { - if (Array.isArray(opts.sort)) { - throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' + - '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' + - '\n- `.sort({ field: 1, test: -1 })`'); - } - - var s; - if (value && value.$meta) { - s = opts.sort || (opts.sort = {}); - s[field] = { $meta : value.$meta }; - return; - } - - s = opts.sort || (opts.sort = {}); - var val = String(value || 1).toLowerCase(); - val = _validSortValue[val]; - if (!val) throw new TypeError('Invalid sort value: { ' + field + ': ' + value + ' }'); - - s[field] = val; -} - -function _pushArr(opts, field, value) { - opts.sort = opts.sort || []; - if (!Array.isArray(opts.sort)) { - throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' + - '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' + - '\n- `.sort({ field: 1, test: -1 })`'); - } - - var val = String(value || 1).toLowerCase(); - val = _validSortValue[val]; - if (!val) throw new TypeError('Invalid sort value: [ ' + field + ', ' + value + ' ]'); - - opts.sort.push([field, val]); -} - -function _pushMap(opts, map) { - opts.sort = opts.sort || new Map(); - if (!(opts.sort instanceof Map)) { - throw new TypeError('Can\'t mix sort syntaxes. Use either array or ' + - 'object or map consistently'); - } - map.forEach(function(value, key) { - var val = String(value || 1).toLowerCase(); - val = _validSortValue[val]; - if (!val) throw new TypeError('Invalid sort value: < ' + key + ': ' + value + ' >'); - - opts.sort.set(key, val); - }); -} - - - -/** - * 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) - * query.maxTimeMS(100) - * - * @method maxTime - * @memberOf Query - * @param {Number} ms - * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS - * @api public - */ - -Query.prototype.maxTime = Query.prototype.maxTimeMS = function(ms) { - this._validate('maxTime'); - this.options.maxTimeMS = ms; - 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}); - * query.hint('indexA_1_indexB_1'); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|string} val a hint object or the index name - * @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; - } - if (typeof arg === 'string') { - this.options.hint = arg; - return this; - } - - throw new TypeError('Invalid hint. ' + arg); -}; - -/** - * Requests acknowledgement that this operation has been persisted to MongoDB's - * on-disk journal. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the `j` value if it is specified in writeConcern options - * - * ####Example: - * - * mquery().w(2).j(true).wtimeout(2000); - * - * @method j - * @memberOf Query - * @instance - * @param {boolean} val - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option - * @return {Query} this - * @api public - */ - -Query.prototype.j = function j(val) { - this.options.j = val; - return this; -}; - -/** - * 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 }])) - * - * new Query().setReadPreference('primary') // alias of .read() - * - * ####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 = Query.prototype.setReadPreference = 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 the readConcern option for the query. - * - * ####Example: - * - * new Query().readConcern('local') - * new Query().readConcern('l') // same as local - * - * new Query().readConcern('available') - * new Query().readConcern('a') // same as available - * - * new Query().readConcern('majority') - * new Query().readConcern('m') // same as majority - * - * new Query().readConcern('linearizable') - * new Query().readConcern('lz') // same as linearizable - * - * new Query().readConcern('snapshot') - * new Query().readConcern('s') // same as snapshot - * - * new Query().r('s') // r is alias of readConcern - * - * - * ####Read Concern Level: - * - * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. - * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. - * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. - - - * - * - * Aliases - * - * l local - * a available - * m majority - * lz linearizable - * s snapshot - * - * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). - * - * @param {String} level one of the listed read concern level or their aliases - * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ - * @return {Query} this - * @api public - */ - -Query.prototype.readConcern = Query.prototype.r = function(level) { - this.options.readConcern = utils.readConcern(level); - 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; -}; - -/** - * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, - * that must acknowledge this write before this write is considered successful. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the `w` value if it is specified in writeConcern options - * - * ####Example: - * - * mquery().writeConcern(0) - * mquery().writeConcern(1) - * mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 }) - * mquery().writeConcern('majority') - * mquery().writeConcern('m') // same as majority - * mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead - * mquery().w(1) // w is alias of writeConcern - * - * @method writeConcern - * @memberOf Query - * @instance - * @param {String|number|object} concern 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option - * @return {Query} this - * @api public - */ - -Query.prototype.writeConcern = Query.prototype.w = function writeConcern(concern) { - if ('object' === typeof concern) { - if ('undefined' !== typeof concern.j) this.options.j = concern.j; - if ('undefined' !== typeof concern.w) this.options.w = concern.w; - if ('undefined' !== typeof concern.wtimeout) this.options.wtimeout = concern.wtimeout; - } else { - this.options.w = 'm' === concern ? 'majority' : concern; - } - return this; -}; - -/** - * Specifies a time limit, in milliseconds, for the write concern. - * If `ms > 1`, it is maximum amount of time to wait for this write - * to propagate through the replica set before this operation fails. - * The default is `0`, which means no timeout. - * - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to `wtimeout` value if it is specified in writeConcern - * - * ####Example: - * - * mquery().w(2).j(true).wtimeout(2000) - * - * @method wtimeout - * @memberOf Query - * @instance - * @param {number} ms number of milliseconds to wait - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout - * @return {Query} this - * @api public - */ - -Query.prototype.wtimeout = Query.prototype.wTimeout = function wtimeout(ms) { - this.options.wtimeout = ms; - 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 conds = this._conditions; - var options = this._optionsForExec(); - - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - 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; -}; - -/** - * Returns the query cursor - * - * ####Examples - * - * query.find().cursor(); - * query.cursor({ name: 'Burning Lights' }); - * - * @param {Object} [criteria] mongodb selector - * @return {Object} cursor - * @api public - */ - -Query.prototype.cursor = function cursor(criteria) { - if (this.op) { - if (this.op !== 'find') { - throw new TypeError('.cursor only support .find method'); - } - } else { - this.find(criteria); - } - - var conds = this._conditions; - var options = this._optionsForExec(); - - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } - - debug('findCursor', this._collection.collectionName, conds, options); - return this._collection.findCursor(conds, options); -}; - -/** - * 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 conds = this._conditions; - var options = this._optionsForExec(); - - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - 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'); - } - - 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. By default, - * `update()` only modifies the _first_ document that matches `criteria`. - * - * _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) { - 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; - } - } - - return _update(this, 'update', criteria, doc, options, force, callback); -}; - -/** - * Declare and/or execute this query as an `updateMany()` operation. Identical - * to `update()` except `updateMany()` will update _all_ documents that match - * `criteria`, rather than just the first one. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * // Update every document whose `title` contains 'test' - * mquery().updateMany({ title: /test/ }, { year: 2017 }) - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.updateMany = function updateMany(criteria, doc, options, callback) { - 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; - } - } - - return _update(this, 'updateMany', criteria, doc, options, force, callback); -}; - -/** - * Declare and/or execute this query as an `updateOne()` operation. Identical - * to `update()` except `updateOne()` will _always_ update just one document, - * regardless of the `multi` option. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * // Update the first document whose `title` contains 'test' - * mquery().updateMany({ title: /test/ }, { year: 2017 }) - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.updateOne = function updateOne(criteria, doc, options, callback) { - 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; - } - } - - return _update(this, 'updateOne', criteria, doc, options, force, callback); -}; - -/** - * Declare and/or execute this query as an `replaceOne()` operation. Similar - * to `updateOne()`, except `replaceOne()` is not allowed to use atomic - * modifiers (`$set`, `$push`, etc.). Calling `replaceOne()` will always - * replace the existing doc. - * - * ####Example - * - * // Replace the document with `_id` 1 with `{ _id: 1, year: 2017 }` - * mquery().replaceOne({ _id: 1 }, { year: 2017 }) - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.replaceOne = function replaceOne(criteria, doc, options, callback) { - 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; - } - } - - this.setOptions({ overwrite: true }); - return _update(this, 'replaceOne', criteria, doc, options, force, callback); -}; - - -/*! - * Internal helper for update, updateMany, updateOne - */ - -function _update(query, op, criteria, doc, options, force, callback) { - query.op = op; - - if (Query.canMerge(criteria)) { - query.merge(criteria); - } - - if (doc) { - query._mergeUpdate(doc); - } - - if (utils.isObject(options)) { - // { overwrite: true } - query.setOptions(options); - } - - // we are done if we don't have callback and they are - // not forcing an unsafe write. - if (!(force || callback)) { - return query; - } - - if (!query._update || - !query.options.overwrite && 0 === utils.keys(query._update).length) { - callback && utils.soon(callback.bind(null, null, 0)); - return query; - } - - options = query._optionsForExec(); - if (!callback) options.safe = false; - - criteria = query._conditions; - doc = query._updateForExec(); - - debug('update', query._collection.collectionName, criteria, doc, options); - callback = query._wrapCallback(op, callback, { - conditions: criteria, - doc: doc, - options: options - }); - - query._collection[op](criteria, doc, options, utils.tick(callback)); - - return query; -} - -/** - * 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; -}; - -/** - * Declare and/or execute this query as a `deleteOne()` operation. Behaves like - * `remove()`, except for ignores the `justOne` option and always deletes at - * most one document. - * - * ####Example - * - * mquery(collection).deleteOne({ artist: 'Anne Murray' }, callback) - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.deleteOne = function(criteria, callback) { - this.op = 'deleteOne'; - 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; - delete options.justOne; - - var conds = this._conditions; - - debug('deleteOne', this._collection.collectionName, conds, options); - callback = this._wrapCallback('deleteOne', callback, { - conditions: conds, - options: options - }); - - this._collection.deleteOne(conds, options, utils.tick(callback)); - - return this; -}; - -/** - * Declare and/or execute this query as a `deleteMany()` operation. Behaves like - * `remove()`, except for ignores the `justOne` option and always deletes - * _every_ document that matches `criteria`. - * - * ####Example - * - * mquery(collection).deleteMany({ artist: 'Anne Murray' }, callback) - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.deleteMany = function(criteria, callback) { - this.op = 'deleteMany'; - 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; - delete options.justOne; - - var conds = this._conditions; - - debug('deleteOne', this._collection.collectionName, conds, options); - callback = this._wrapCallback('deleteOne', callback, { - conditions: conds, - options: options - }); - - this._collection.deleteMany(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 - * A.where().findOneAndDelete() // alias of .findOneAndRemove() - * - * @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 = Query.prototype.findOneAndDelete = 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 options = this._optionsForExec(); - var fields; - var doc; - - if ('remove' == type) { - options.remove = true; - } else { - if (!('new' in options)) options.new = true; - if (!('upsert' in options)) options.upsert = false; - - doc = this._updateForExec(); - if (!doc) { - if (options.upsert) { - // still need to do the upsert to empty doc - doc = { $set: {} }; - } else { - return this.findOne(callback); - } - } - } - - fields = this._fieldsForExec(); - if (fields != null) { - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } - } - - var conds = this._conditions; - - debug('findAndModify', this._collection.collectionName, conds, doc, options); - callback = this._wrapCallback('findAndModify', callback, { - conditions: conds, - doc: doc, - options: options - }); - - this._collection.findAndModify(conds, doc, options, 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: <name of the collection>, - * conditions: <query criteria>, - * options: <comment, fields, readPreference, etc>, - * 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); - } - - var _this = this; - - if ('function' == typeof callback) { - this[this.op](callback); - } else { - return new Query.Promise(function(success, error) { - _this[_this.op](function(err, val) { - if (err) error(err); - else success(val); - success = error = null; - }); - }); - } -}; - -/** - * 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 _this = this; - return function(cb) { - _this.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 _this = this; - var promise = new Query.Promise(function(success, error) { - _this.exec(function(err, val) { - if (err) error(err); - else success(val); - success = error = null; - }); - }); - 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(); - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - 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; - if (this._fields[key] && - typeof this._fields[key] === 'object' && - this._fields[key].$meta) { - 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); - 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), - ops = utils.keys(update), - i = ops.length, - ret = {}; - - 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]; - } - } - - this._compiledUpdate = ret; - 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/mquery/lib/permissions.js b/node_modules/mquery/lib/permissions.js deleted file mode 100644 index c306f3a47c1fc412a390c255ded99d93b0f38f56..0000000000000000000000000000000000000000 --- a/node_modules/mquery/lib/permissions.js +++ /dev/null @@ -1,88 +0,0 @@ -'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.slice = -denied.count.batchSize = -denied.count.comment = -denied.count.maxScan = -denied.count.snapshot = -denied.count.tailable = true; diff --git a/node_modules/mquery/lib/utils.js b/node_modules/mquery/lib/utils.js deleted file mode 100644 index ef51712870abd4ad1d3258034033a657411a9f41..0000000000000000000000000000000000000000 --- a/node_modules/mquery/lib/utils.js +++ /dev/null @@ -1,356 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -var Buffer = require('safe-buffer').Buffer; -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 (obj.constructor.name === 'ReadPreference') { - return 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 - */ - -exports.cloneObject = function cloneObject(obj, options) { - var minimize = options && options.minimize; - var ret = {}; - var hasKeys; - var val; - var k; - - for (k in obj) { - val = clone(obj[k], options); - - if (!minimize || ('undefined' !== typeof val)) { - hasKeys || (hasKeys = true); - ret[k] = val; - } - } - - return minimize - ? hasKeys && ret - : ret; -}; - -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 - */ - -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 - */ - -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 - */ - -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]) { - to[key] = clone(from[key]); - } else { - if (exports.isObject(from[key])) { - mergeClone(to[key], from[key]); - } else { - to[key] = clone(from[key]); - } - } - } -}; - -/** - * 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; -}; - - -/** - * Read Concern helper (mongo 3.2 drivers support this) - * - * Allows using string to specify read concern level: - * - * local 3.2+ - * available 3.6+ - * majority 3.2+ - * linearizable 3.4+ - * snapshot 4.0+ - * - * @param {String|Object} concern - */ - -exports.readConcern = function readConcern(concern) { - if ('string' === typeof concern) { - switch (concern) { - case 'l': - concern = 'local'; - break; - case 'a': - concern = 'available'; - break; - case 'm': - concern = 'majority'; - break; - case 'lz': - concern = 'linearizable'; - break; - case 's': - concern = 'snapshot'; - break; - } - concern = { level: concern }; - } - return concern; -}; - -/** - * Object.prototype.toString.call helper - */ - -var _toString = Object.prototype.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 - */ - -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 = Buffer.alloc(buff.length); - buff.copy(dupe, 0, 0, buff.length); - return dupe; -}; - -/** - * Check if this object is an arguments object - * - * @param {Any} v - * @return {Boolean} - */ - -exports.isArgumentsObject = function(v) { - return Object.prototype.toString.call(v) === '[object Arguments]'; -}; diff --git a/node_modules/mquery/node_modules/bluebird/LICENSE b/node_modules/mquery/node_modules/bluebird/LICENSE deleted file mode 100644 index ae732d5299f49d1eb388247146651845c317579e..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013-2017 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/mquery/node_modules/bluebird/README.md b/node_modules/mquery/node_modules/bluebird/README.md deleted file mode 100644 index ba82f73e275e1cbef6d6322a724c4dabe3b8e266..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/README.md +++ /dev/null @@ -1,52 +0,0 @@ -<a href="http://promisesaplus.com/"> - <img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo" - title="Promises/A+ 1.1 compliant" align="right" /> -</a> - -[](https://travis-ci.org/petkaantonov/bluebird) -[](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) - -**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises) - -# Introduction - -Bluebird is a fully featured promise library with focus on innovative features and performance - -See the [**bluebird website**](http://bluebirdjs.com/docs/getting-started.html) for further documentation, references and instructions. See the [**API reference**](http://bluebirdjs.com/docs/api-reference.html) here. - -For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x). - -# Questions and issues - -The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. - - - -## Thanks - -Thanks to BrowserStack for providing us with a free account which lets us support old browsers like IE8. - -# License - -The MIT License (MIT) - -Copyright (c) 2013-2017 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/mquery/node_modules/bluebird/changelog.md b/node_modules/mquery/node_modules/bluebird/changelog.md deleted file mode 100644 index 73b2eb6c79dd457df0eb958e09333adffc579f25..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/changelog.md +++ /dev/null @@ -1 +0,0 @@ -[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html) diff --git a/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.core.js b/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.core.js deleted file mode 100644 index 85b779137dd10f9ae1f703918d2a746dc92677f7..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.core.js +++ /dev/null @@ -1,3781 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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 3.5.1 - * Features enabled: core - * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each -*/ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ -"use strict"; -var firstLineError; -try {throw new Error(); } catch (e) {firstLineError = e;} -var schedule = _dereq_("./schedule"); -var Queue = _dereq_("./queue"); -var util = _dereq_("./util"); - -function Async() { - this._customScheduler = false; - this._isTickUsed = false; - this._lateQueue = new Queue(16); - this._normalQueue = new Queue(16); - this._haveDrainedQueues = false; - this._trampolineEnabled = true; - var self = this; - this.drainQueues = function () { - self._drainQueues(); - }; - this._schedule = schedule; -} - -Async.prototype.setScheduler = function(fn) { - var prev = this._schedule; - this._schedule = fn; - this._customScheduler = true; - return prev; -}; - -Async.prototype.hasCustomScheduler = function() { - return this._customScheduler; -}; - -Async.prototype.enableTrampoline = function() { - this._trampolineEnabled = true; -}; - -Async.prototype.disableTrampolineIfNecessary = function() { - if (util.hasDevTools) { - this._trampolineEnabled = false; - } -}; - -Async.prototype.haveItemsQueued = function () { - return this._isTickUsed || this._haveDrainedQueues; -}; - - -Async.prototype.fatalError = function(e, isNode) { - if (isNode) { - process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + - "\n"); - process.exit(2); - } else { - this.throwLater(e); - } -}; - -Async.prototype.throwLater = function(fn, arg) { - if (arguments.length === 1) { - arg = fn; - fn = function () { throw arg; }; - } - if (typeof setTimeout !== "undefined") { - setTimeout(function() { - fn(arg); - }, 0); - } else try { - this._schedule(function() { - fn(arg); - }); - } catch (e) { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } -}; - -function AsyncInvokeLater(fn, receiver, arg) { - this._lateQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncInvoke(fn, receiver, arg) { - this._normalQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncSettlePromises(promise) { - this._normalQueue._pushOne(promise); - this._queueTick(); -} - -if (!util.hasDevTools) { - Async.prototype.invokeLater = AsyncInvokeLater; - Async.prototype.invoke = AsyncInvoke; - Async.prototype.settlePromises = AsyncSettlePromises; -} else { - Async.prototype.invokeLater = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvokeLater.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - setTimeout(function() { - fn.call(receiver, arg); - }, 100); - }); - } - }; - - Async.prototype.invoke = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvoke.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - fn.call(receiver, arg); - }); - } - }; - - Async.prototype.settlePromises = function(promise) { - if (this._trampolineEnabled) { - AsyncSettlePromises.call(this, promise); - } else { - this._schedule(function() { - promise._settlePromises(); - }); - } - }; -} - -Async.prototype._drainQueue = function(queue) { - while (queue.length() > 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -}; - -Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; - -},{"./queue":17,"./schedule":18,"./util":21}],2:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { -var calledBind = false; -var rejectThis = function(_, e) { - this._reject(e); -}; - -var targetRejected = function(e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); -}; - -var bindingResolved = function(thisArg, context) { - if (((this._bitField & 50397184) === 0)) { - this._resolveCallback(context.target); - } -}; - -var bindingRejected = function(e, context) { - if (!context.promiseRejectionQueued) this._reject(e); -}; - -Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, bindingRejected, undefined, ret, context); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; -}; - -Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~2097152); - } -}; - -Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; -}; - -Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); -}; -}; - -},{}],3:[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")(); -bluebird.noConflict = noConflict; -module.exports = bluebird; - -},{"./promise":15}],4:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -Promise.prototype["break"] = Promise.prototype.cancel = function() { - if (!debug.cancellation()) return this._warn("cancellation is disabled"); - - var promise = this; - var child = promise; - while (promise._isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } - - var parent = promise._cancellationParent; - if (parent == null || !parent._isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - promise._setWillBeCancelled(); - child = promise; - promise = parent; - } - } -}; - -Promise.prototype._branchHasCancelled = function() { - this._branchesRemainingToCancel--; -}; - -Promise.prototype._enoughBranchesHaveCancelled = function() { - return this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0; -}; - -Promise.prototype._cancelBy = function(canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; - } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; - } - } - return false; -}; - -Promise.prototype._cancelBranched = function() { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } -}; - -Promise.prototype._cancel = function() { - if (!this._isCancellable()) return; - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); -}; - -Promise.prototype._cancelPromises = function() { - if (this._length() > 0) this._settlePromises(); -}; - -Promise.prototype._unsetOnCancel = function() { - this._onCancelField = undefined; -}; - -Promise.prototype._isCancellable = function() { - return this.isPending() && !this._isCancelled(); -}; - -Promise.prototype.isCancellable = function() { - return this.isPending() && !this.isCancelled(); -}; - -Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { - if (util.isArray(onCancelCallback)) { - for (var i = 0; i < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); - } - } - } else { - onCancelCallback._resultCancelled(this); - } - } -}; - -Promise.prototype._invokeOnCancel = function() { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); -}; - -Promise.prototype._invokeInternalOnCancel = function() { - if (this._isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); - } -}; - -Promise.prototype._resultCancelled = function() { - this.cancel(); -}; - -}; - -},{"./util":21}],5:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = _dereq_("./util"); -var getKeys = _dereq_("./es5").keys; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } - } - return NEXT_FILTER; - }; -} - -return catchFilter; -}; - -},{"./es5":10,"./util":21}],6:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var longStackTraces = false; -var contextStack = []; - -Promise.prototype._promiseCreated = function() {}; -Promise.prototype._pushContext = function() {}; -Promise.prototype._popContext = function() {return null;}; -Promise._peekContext = Promise.prototype._peekContext = function() {}; - -function Context() { - this._trace = new Context.CapturedTrace(peekContext()); -} -Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); - } -}; - -Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; - } - return null; -}; - -function createContext() { - if (longStackTraces) return new Context(); -} - -function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; -} -Context.CapturedTrace = null; -Context.create = createContext; -Context.deactivateLongStackTraces = function() {}; -Context.activateLongStackTraces = function() { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var Promise_promiseCreated = Promise.prototype._promiseCreated; - Context.deactivateLongStackTraces = function() { - Promise.prototype._pushContext = Promise_pushContext; - Promise.prototype._popContext = Promise_popContext; - Promise._peekContext = Promise_PeekContext; - Promise.prototype._peekContext = Promise_peekContext; - Promise.prototype._promiseCreated = Promise_promiseCreated; - longStackTraces = false; - }; - longStackTraces = true; - Promise.prototype._pushContext = Context.prototype._pushContext; - Promise.prototype._popContext = Context.prototype._popContext; - Promise._peekContext = Promise.prototype._peekContext = peekContext; - Promise.prototype._promiseCreated = function() { - var ctx = this._peekContext(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; -}; -return Context; -}; - -},{}],7:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = _dereq_("./errors").Warning; -var util = _dereq_("./util"); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; -var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; -var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; -var stackFramePattern = null; -var formatStack = null; -var indentStackFrames = false; -var printWarning; -var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - (true || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); - -var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); - -var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - -var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - -Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); -}; - -Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; - -Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } -}; - -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); -}; - -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; -}; - -Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; -}; - -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); -}; - -Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -var disableLongStackTraces = function() {}; -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - -var fireDomEvent = (function() { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, - event); - return !util.global.dispatchEvent(domEvent); - }; - } - } catch (e) {} - return function() { - return false; - }; -})(); - -var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function() { - return false; - }; - } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } -})(); - -function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; -} - -var eventToObjectGenerator = { - promiseCreated: generatePromiseLifecycleEventObject, - promiseFulfilled: generatePromiseLifecycleEventObject, - promiseRejected: generatePromiseLifecycleEventObject, - promiseResolved: generatePromiseLifecycleEventObject, - promiseCancelled: generatePromiseLifecycleEventObject, - promiseChained: function(name, promise, child) { - return {promise: promise, child: child}; - }, - warning: function(name, warning) { - return {warning: warning}; - }, - unhandledRejection: function (name, reason, promise) { - return {reason: reason, promise: promise}; - }, - rejectionHandled: generatePromiseLifecycleEventObject -}; - -var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; - } - - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; - } - - return domEventFired || globalEventFired; -}; - -Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - - if (util.isObject(warningsOption)) { - if ("wForgottenReturn" in warningsOption) { - wForgottenReturn = !!warningsOption.wForgottenReturn; - } - } - } - if ("cancellation" in opts && opts.cancellation && !config.cancellation) { - if (async.haveItemsQueued()) { - throw new Error( - "cannot enable cancellation after promises are in use"); - } - Promise.prototype._clearCancellationData = - cancellationClearCancellationData; - Promise.prototype._propagateFrom = cancellationPropagateFrom; - Promise.prototype._onCancel = cancellationOnCancel; - Promise.prototype._setOnCancel = cancellationSetOnCancel; - Promise.prototype._attachCancellationCallback = - cancellationAttachCancellationCallback; - Promise.prototype._execute = cancellationExecute; - propagateFromFunction = cancellationPropagateFrom; - config.cancellation = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } - return Promise; -}; - -function defaultFireEvent() { return false; } - -Promise.prototype._fireEvent = defaultFireEvent; -Promise.prototype._execute = function(executor, resolve, reject) { - try { - executor(resolve, reject); - } catch (e) { - return e; - } -}; -Promise.prototype._onCancel = function () {}; -Promise.prototype._setOnCancel = function (handler) { ; }; -Promise.prototype._attachCancellationCallback = function(onCancel) { - ; -}; -Promise.prototype._captureStackTrace = function () {}; -Promise.prototype._attachExtraTrace = function () {}; -Promise.prototype._clearCancellationData = function() {}; -Promise.prototype._propagateFrom = function (parent, flags) { - ; - ; -}; - -function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - throw new TypeError("onCancel must be a function, got: " + - util.toString(onCancel)); - } - promise._attachCancellationCallback(onCancel); - }); - } catch (e) { - return e; - } -} - -function cancellationAttachCancellationCallback(onCancel) { - if (!this._isCancellable()) return this; - - var previousOnCancel = this._onCancel(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); - } -} - -function cancellationOnCancel() { - return this._onCancelField; -} - -function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; -} - -function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; -} - -function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} - -function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} -var propagateFromFunction = bindingPropagateFrom; - -function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; -} - -function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); -} - -function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = parseStackAndMessage(error); - util.notEnumerableProp(error, "stack", - parsed.message + "\n" + parsed.stack.join("\n")); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } -} - -function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = "at " + lineMatches[1] + - ":" + lineMatches[2] + ":" + lineMatches[3] + " "; - } - break; - } - } - - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { - - if (traceLines[i] === firstUserLine) { - if (i > 0) { - creatorLine = "\n" + traceLines[i - 1]; - } - break; - } - } - - } - } - var msg = "a promise was created in a " + name + - "handler " + handlerLine + "but was not returned from it, " + - "see http://goo.gl/rRqMUw" + - creatorLine; - promise._warn(msg, true, promiseCreated); - } -} - -function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); -} - -function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - if (shouldUseOwnTrace) { - promise._attachExtraTrace(warning); - } else if (config.longStackTraces && (ctx = Promise._peekContext())) { - ctx.attachExtraTrace(warning); - } else { - var parsed = parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } - - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } -} - -function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); -} - -function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; - } - } -} - -function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } - - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } -} - -function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; -} - -function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0 && error.name != "SyntaxError") { - stack = stack.slice(i); - } - return stack; -} - -function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: error.name == "SyntaxError" ? stack : cleanStack(stack) - }; -} - -function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -} - -function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } - - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } -} - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? obj.toString() : util.toString(obj); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; -} - -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } -} - -function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; -} - -function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); -} -util.inherits(CapturedTrace, Error); -Context.CapturedTrace = CapturedTrace; - -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } -}; - -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; - } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); - util.notEnumerableProp(error, "__stackCleaned__", true); -}; - -var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } - - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } - - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - return null; - -})([]); - -if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; - } -} - -var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - longStackTraces: function() { - return config.longStackTraces; - }, - warnings: function() { - return config.warnings; - }, - cancellation: function() { - return config.cancellation; - }, - monitoring: function() { - return config.monitoring; - }, - propagateFromFunction: function() { - return propagateFromFunction; - }, - boundValueFunction: function() { - return boundValueFunction; - }, - checkForgottenReturns: checkForgottenReturns, - setBounds: setBounds, - warn: warn, - deprecated: deprecated, - CapturedTrace: CapturedTrace, - fireDomEvent: fireDomEvent, - fireGlobalEvent: fireGlobalEvent -}; -}; - -},{"./errors":9,"./util":21}],8:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -function returner() { - return this.value; -} -function thrower() { - throw this.reason; -} - -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); -}; - -Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } -}; - -Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } -}; -}; - -},{}],9:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var Objectfreeze = es5.freeze; -var util = _dereq_("./util"); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; -} - -var _TypeError, _RangeError; -var Warning = subError("Warning", "warning"); -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); -} - -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} - -es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true -}); -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; - -function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - -} -inherits(OperationalError, Error); - -var errorTypes = Error["__BluebirdErrorTypes__"]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false - }); -} - -module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - Warning: Warning -}; - -},{"./es5":10,"./util":21}],10:[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; - } - }; -} - -},{}],11:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { -var util = _dereq_("./util"); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); - -function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; -} - -PassThroughHandlerContext.prototype.isFinallyHandler = function() { - return this.type === 0; -}; - -function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; -} - -FinallyHandlerCancelReaction.prototype._resultCancelled = function() { - checkCancel(this.finallyHandler); -}; - -function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; -} - -function succeed() { - return finallyHandler.call(this, this.promise._target()._settledValue()); -} -function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; -} -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret === NEXT_FILTER) { - return ret; - } else if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise._isCancelled()) { - var reason = - new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this)); - } - } - return maybePromise._then( - succeed, fail, undefined, this, undefined); - } - } - } - - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } -} - -Promise.prototype._passThrough = function(handler, type, success, fail) { - if (typeof handler !== "function") return this.then(); - return this._then(success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined); -}; - -Promise.prototype.lastly = -Promise.prototype["finally"] = function (handler) { - return this._passThrough(handler, - 0, - finallyHandler, - finallyHandler); -}; - - -Promise.prototype.tap = function (handler) { - return this._passThrough(handler, 1, finallyHandler); -}; - -Promise.prototype.tapCatch = function (handlerOrPredicate) { - var len = arguments.length; - if(len === 1) { - return this._passThrough(handlerOrPredicate, - 1, - undefined, - finallyHandler); - } else { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return Promise.reject(new TypeError( - "tapCatch statement predicate: " - + "expecting an object but got " + util.classString(item) - )); - } - } - catchInstances.length = j; - var handler = arguments[i]; - return this._passThrough(catchFilter(catchInstances, handler, this), - 1, - undefined, - finallyHandler); - } - -}; - -return PassThroughHandlerContext; -}; - -},{"./catch_filter":5,"./util":21}],12:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { -var util = _dereq_("./util"); -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 promiseSetter = function(i) { - return new Function("promise", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = promise; \n\ - ".replace(/Index/g, i)); - }; - - var generateHolderClass = function(total) { - var props = new Array(total); - for (var i = 0; i < props.length; ++i) { - props[i] = "this.p" + (i+1); - } - var assignment = props.join(" = ") + " = null;"; - var cancellationCode= "var promise;\n" + props.map(function(prop) { - return " \n\ - promise = " + prop + "; \n\ - if (promise instanceof Promise) { \n\ - promise.cancel(); \n\ - } \n\ - "; - }).join("\n"); - var passedArguments = props.join(", "); - var name = "Holder$" + total; - - - var code = "return function(tryCatch, errorObj, Promise, async) { \n\ - 'use strict'; \n\ - function [TheName](fn) { \n\ - [TheProperties] \n\ - this.fn = fn; \n\ - this.asyncNeeded = true; \n\ - this.now = 0; \n\ - } \n\ - \n\ - [TheName].prototype._callFunction = function(promise) { \n\ - promise._pushContext(); \n\ - var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ - promise._popContext(); \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(ret.e, false); \n\ - } else { \n\ - promise._resolveCallback(ret); \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype.checkFulfillment = function(promise) { \n\ - var now = ++this.now; \n\ - if (now === [TheTotal]) { \n\ - if (this.asyncNeeded) { \n\ - async.invoke(this._callFunction, this, promise); \n\ - } else { \n\ - this._callFunction(promise); \n\ - } \n\ - \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype._resultCancelled = function() { \n\ - [CancellationCode] \n\ - }; \n\ - \n\ - return [TheName]; \n\ - }(tryCatch, errorObj, Promise, async); \n\ - "; - - code = code.replace(/\[TheName\]/g, name) - .replace(/\[TheTotal\]/g, total) - .replace(/\[ThePassedArguments\]/g, passedArguments) - .replace(/\[TheProperties\]/g, assignment) - .replace(/\[CancellationCode\]/g, cancellationCode); - - return new Function("tryCatch", "errorObj", "Promise", "async", code) - (tryCatch, errorObj, Promise, async); - }; - - var holderClasses = []; - var thenCallbacks = []; - var promiseSetters = []; - - for (var i = 0; i < 8; ++i) { - holderClasses.push(generateHolderClass(i + 1)); - thenCallbacks.push(thenCallback(i + 1)); - promiseSetters.push(promiseSetter(i + 1)); - } - - reject = function (reason) { - this._reject(reason); - }; -}} - -Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (!true) { - if (last <= 8 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var HolderClass = holderClasses[last - 1]; - var holder = new HolderClass(fn); - var callbacks = thenCallbacks; - - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], ret); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - maybePromise._then(callbacks[i], reject, - undefined, ret, holder); - promiseSetters[i](maybePromise, holder); - holder.asyncNeeded = false; - } else if (((bitField & 33554432) !== 0)) { - callbacks[i].call(ret, - maybePromise._value(), holder); - } else if (((bitField & 16777216) !== 0)) { - ret._reject(maybePromise._reason()); - } else { - ret._cancel(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - - if (!ret._isFateSealed()) { - if (holder.asyncNeeded) { - var domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, holder.fn); - } - } - ret._setAsyncGuaranteed(); - ret._setOnCancel(holder); - } - return ret; - } - } - } - var args = [].slice.call(arguments);; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; - -}; - -},{"./util":21}],13:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.method", ret); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var ctx = arguments[2]; - value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) - : tryCatch(fn).call(ctx, arg); - } else { - value = tryCatch(fn)(); - } - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.try", ret); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); - } -}; -}; - -},{"./util":21}],14:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = _dereq_("./errors"); -var OperationalError = errors.OperationalError; -var es5 = _dereq_("./es5"); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -var rErrorKey = /^(?:name|message|stack|cause)$/; -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - util.markAsOriginatingFromRejection(obj); - return obj; -} - -function nodebackForPromise(promise, multiArgs) { - return function(err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); - } else { - var args = [].slice.call(arguments, 1);; - promise._fulfill(args); - } - promise = null; - }; -} - -module.exports = nodebackForPromise; - -},{"./errors":9,"./es5":10,"./util":21}],15:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function() { -var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var reflectHandler = function() { - return new Promise.PromiseInspection(this._target()); -}; -var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); -}; -function Proxyable() {} -var UNDEFINED_BINDING = {}; -var util = _dereq_("./util"); - -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { - return null; - }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); - -var es5 = _dereq_("./es5"); -var Async = _dereq_("./async"); -var async = new Async(); -es5.defineProperty(Promise, "_async", {value: async}); -var errors = _dereq_("./errors"); -var TypeError = Promise.TypeError = errors.TypeError; -Promise.RangeError = errors.RangeError; -var CancellationError = Promise.CancellationError = errors.CancellationError; -Promise.TimeoutError = errors.TimeoutError; -Promise.OperationalError = errors.OperationalError; -Promise.RejectionError = errors.OperationalError; -Promise.AggregateError = errors.AggregateError; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {}; -var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); -var PromiseArray = - _dereq_("./promise_array")(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); -var Context = _dereq_("./context")(Promise); - /*jshint unused:false*/ -var createContext = Context.create; -var debug = _dereq_("./debuggability")(Promise, Context); -var CapturedTrace = debug.CapturedTrace; -var PassThroughHandlerContext = - _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); -var nodebackForPromise = _dereq_("./nodeback"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (self == null || self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - -} - -function Promise(executor) { - if (executor !== INTERNAL) { - check(this, executor); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - this._resolveFromExecutor(executor); - this._promiseCreated(); - this._fireEvent("promiseCreated", this); -} - -Promise.prototype.toString = function () { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection("Catch statement predicate: " + - "expecting an object but got " + util.classString(item)); - } - } - catchInstances.length = j; - fn = arguments[i]; - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); -}; - -Promise.prototype.reflect = function () { - return this._then(reflectHandler, - reflectHandler, undefined, this, undefined); -}; - -Promise.prototype.then = function (didFulfill, didReject) { - if (debug.warnings() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then(didFulfill, didReject, undefined, undefined, undefined); -}; - -Promise.prototype.done = function (didFulfill, didReject) { - var promise = - this._then(didFulfill, didReject, undefined, undefined, undefined); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); -}; - -Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return new PromiseArray(this).promise(); -}; - -Promise.prototype.error = function (fn) { - return this.caught(util.originatesFromRejection, fn); -}; - -Promise.getNewLibraryCopy = module.exports; - -Promise.is = function (val) { - return val instanceof Promise; -}; - -Promise.fromNode = Promise.fromCallback = function(fn) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs - : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); - } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - return async.setScheduler(fn); -}; - -Promise.prototype._then = function ( - didFulfill, - didReject, - _, receiver, - internalData -) { - var haveInternalData = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && - ((this._bitField & 2097152) !== 0)) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } - - var domain = getDomain(); - if (!((bitField & 50397184) === 0)) { - var handler, value, settler = target._settlePromiseCtx; - if (((bitField & 33554432) !== 0)) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if (((bitField & 16777216) !== 0)) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); - } - - return promise; -}; - -Promise.prototype._length = function () { - return this._bitField & 65535; -}; - -Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; -}; - -Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; -}; - -Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | - (len & 65535); -}; - -Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); -}; - -Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); -}; - -Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); -}; - -Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; -}; - -Promise.prototype._unsetCancelled = function() { - this._bitField = this._bitField & (~65536); -}; - -Promise.prototype._setCancelled = function() { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); -}; - -Promise.prototype._setWillBeCancelled = function() { - this._bitField = this._bitField | 8388608; -}; - -Promise.prototype._setAsyncGuaranteed = function() { - if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; -}; - -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[ - index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); - } - return ret; -}; - -Promise.prototype._promiseAt = function (index) { - return this[ - index * 4 - 4 + 2]; -}; - -Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[ - index * 4 - 4 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = function (index) { - return this[ - index * 4 - 4 + 1]; -}; - -Promise.prototype._boundValue = function() {}; - -Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._addCallbacks = function ( - fulfill, - reject, - promise, - receiver, - domain -) { - var index = this._length(); - - if (index >= 65535 - 4) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, reject); - } - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); -}; - -Promise.prototype._resolveCallback = function(value, shouldBind) { - if (((this._bitField & 117506048) !== 0)) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); - - if (shouldBind) this._propagateFrom(maybePromise, 2); - - var promise = maybePromise._target(); - - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } - - var bitField = promise._bitField; - if (((bitField & 50397184) === 0)) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(promise); - } else if (((bitField & 33554432) !== 0)) { - this._fulfill(promise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); - } -}; - -Promise.prototype._rejectCallback = -function(reason, synchronous, ignoreNonErrorWarnings) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); - } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); -}; - -Promise.prototype._resolveFromExecutor = function (executor) { - if (executor === INTERNAL) return; - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute(executor, function(value) { - promise._resolveCallback(value); - }, function (reason) { - promise._rejectCallback(reason, synchronous); - }); - synchronous = false; - this._popContext(); - - if (r !== undefined) { - promise._rejectCallback(r, true); - } -}; - -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - var bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError("cannot .spread() a non-array: " + - util.classString(value)); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } -}; - -Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; -}; - -Promise.prototype._followee = function() { - return this._rejectionHandler0; -}; - -Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; -}; - -Promise.prototype._settlePromise = function(promise, handler, receiver, value) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = ((bitField & 134217728) !== 0); - if (((bitField & 65536) !== 0)) { - if (isPromise) promise._invokeInternalOnCancel(); - - if (receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler()) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if (((bitField & 33554432) !== 0)) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if (((bitField & 33554432) !== 0)) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } -}; - -Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } -}; - -Promise.prototype._settlePromiseCtx = function(ctx) { - this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); -}; - -Promise.prototype._settlePromise0 = function(handler, value, bitField) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); -}; - -Promise.prototype._clearCallbackDataAtIndex = function(index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = undefined; -}; - -Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; - - if ((bitField & 65535) > 0) { - if (((bitField & 134217728) !== 0)) { - this._settlePromises(); - } else { - async.settlePromises(this); - } - } -}; - -Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; - - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } - - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } -}; - -Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } -}; - -Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = (bitField & 65535); - - if (len > 0) { - if (((bitField & 16842752) !== 0)) { - var reason = this._fulfillmentHandler0; - this._settlePromise0(this._rejectionHandler0, reason, bitField); - this._rejectPromises(len, reason); - } else { - var value = this._rejectionHandler0; - this._settlePromise0(this._fulfillmentHandler0, value, bitField); - this._fulfillPromises(len, value); - } - this._setLength(0); - } - this._clearCancellationData(); -}; - -Promise.prototype._settledValue = function() { - var bitField = this._bitField; - if (((bitField & 33554432) !== 0)) { - return this._rejectionHandler0; - } else if (((bitField & 16777216) !== 0)) { - return this._fulfillmentHandler0; - } -}; - -function deferResolve(v) {this.promise._resolveCallback(v);} -function deferReject(v) {this.promise._rejectCallback(v, false);} - -Promise.defer = Promise.pending = function() { - debug.deprecated("Promise.defer", "new Promise"); - var promise = new Promise(INTERNAL); - return { - promise: promise, - resolve: deferResolve, - reject: deferReject - }; -}; - -util.notEnumerableProp(Promise, - "_makeSelfResolutionError", - makeSelfResolutionError); - -_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, - debug); -_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); -_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); -_dereq_("./direct_resolve")(Promise); -_dereq_("./synchronous_inspection")(Promise); -_dereq_("./join")( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); -Promise.Promise = Promise; -Promise.version = "3.5.1"; - - util.toFastProperties(Promise); - util.toFastProperties(Promise.prototype); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return Promise; - -}; - -},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = _dereq_("./util"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - case -6: return new Map(); - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -util.inherits(PromiseArray, Proxyable); - -PromiseArray.prototype.length = function () { - return this._length; -}; - -PromiseArray.prototype.promise = function () { - return this._promise; -}; - -PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - var values = tryConvertToPromise(this._values, this._promise); - if (values instanceof Promise) { - values = values._target(); - var bitField = values._bitField; - ; - this._values = values; - - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - this._iterate(values); -}; - -PromiseArray.prototype._iterate = function(values) { - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() ? new Array(len) : this._values; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); - - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } - - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); -}; - -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); -}; - -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; -}; - -PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; -}; - -PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } -}; - -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; - -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; - -return PromiseArray; -}; - -},{"./util":21}],17:[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.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; - -},{}],18:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var schedule; -var noAsyncScheduler = function() { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var NativePromise = util.getNativePromise(); -if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function(fn) { GlobalSetImmediate.call(global, fn); } - : function(fn) { ProcessNextTick.call(process, fn); }; -} else if (typeof NativePromise === "function" && - typeof NativePromise.resolve === "function") { - var nativePromise = NativePromise.resolve(); - schedule = function(fn) { - nativePromise.then(fn); - }; -} else if ((typeof MutationObserver !== "undefined") && - !(typeof window !== "undefined" && - window.navigator && - (window.navigator.standalone || window.cordova))) { - schedule = (function() { - var div = document.createElement("div"); - var opts = {attributes: true}; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function() { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); - - var scheduleToggle = function() { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; - - return function schedule(fn) { - var o = new MutationObserver(function() { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); -} else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; -} else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; -} else { - schedule = noAsyncScheduler; -} -module.exports = schedule; - -},{"./util":21}],19:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() : undefined; - } - else { - this._bitField = 0; - this._settledValueField = undefined; - } -} - -PromiseInspection.prototype._settledValue = function() { - return this._settledValueField; -}; - -var value = PromiseInspection.prototype.value = function () { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var reason = PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { - return (this._bitField & 33554432) !== 0; -}; - -var isRejected = PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; -}; - -var isPending = PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; -}; - -var isResolved = PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; -}; - -PromiseInspection.prototype.isCancelled = function() { - return (this._bitField & 8454144) !== 0; -}; - -Promise.prototype.__isCancelled = function() { - return (this._bitField & 65536) === 65536; -}; - -Promise.prototype._isCancelled = function() { - return this._target().__isCancelled(); -}; - -Promise.prototype.isCancelled = function() { - return (this._target()._bitField & 8454144) !== 0; -}; - -Promise.prototype.isPending = function() { - return isPending.call(this._target()); -}; - -Promise.prototype.isRejected = function() { - return isRejected.call(this._target()); -}; - -Promise.prototype.isFulfilled = function() { - return isFulfilled.call(this._target()); -}; - -Promise.prototype.isResolved = function() { - return isResolved.call(this._target()); -}; - -Promise.prototype.value = function() { - return value.call(this._target()); -}; - -Promise.prototype.reason = function() { - var target = this._target(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); -}; - -Promise.prototype._value = function() { - return this._settledValue(); -}; - -Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); -}; - -Promise.PromiseInspection = PromiseInspection; -}; - -},{}],20:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var isObject = util.isObject; - -function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; -} - -function doGetThen(obj) { - return obj.then; -} - -function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } -} - -function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; - - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } - - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } - - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; -} - -return tryConvertToPromise; -}; - -},{"./util":21}],21:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var canEvaluate = typeof navigator == "undefined"; - -var errorObj = {e: {}}; -var tryCatchTarget; -var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; - -function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(safeToString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; - - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; - - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } - -})(); - -var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); - - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; - - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var l = 8; - while (l--) new FakeConstructor(); - return obj; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } -} - -function isError(obj) { - return obj instanceof Error || - (obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"); -} - -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 isError(obj) && es5.propertyIsWritable(obj, "stack"); -} - -var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } -})(); - -function classString(obj) { - return {}.toString.call(obj); -} - -function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } - } -} - -var asArray = function(v) { - if (es5.isArray(v)) { - return v; - } - return null; -}; - -if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; - - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; -} - -var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; - -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; - -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} - -function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -function domainBind(self, cb) { - return self.bind(cb); -} - -var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; - -},{"./es5":10}]},{},[3])(3) -}); ;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/mquery/node_modules/bluebird/js/browser/bluebird.core.min.js b/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.core.min.js deleted file mode 100644 index 6aca6aa3fd37e88c6e2263f967c2c3dc0b23928d..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.core.min.js +++ /dev/null @@ -1,31 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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 3.5.1 - * Features enabled: core - * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each -*/ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,n;return function r(t,e,n){function i(a,s){if(!e[a]){if(!t[a]){var c="function"==typeof _dereq_&&_dereq_;if(!s&&c)return c(a,!0);if(o)return o(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[a]={exports:{}};t[a][0].call(u.exports,function(e){var n=t[a][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[a].exports}for(var o="function"==typeof _dereq_&&_dereq_,a=0;a<n.length;a++)i(n[a]);return i}({1:[function(t,e,n){"use strict";function r(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new u(16),this._normalQueue=new u(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var t=this;this.drainQueues=function(){t._drainQueues()},this._schedule=l}function i(t,e,n){this._lateQueue.push(t,e,n),this._queueTick()}function o(t,e,n){this._normalQueue.push(t,e,n),this._queueTick()}function a(t){this._normalQueue._pushOne(t),this._queueTick()}var s;try{throw new Error}catch(c){s=c}var l=t("./schedule"),u=t("./queue"),p=t("./util");r.prototype.setScheduler=function(t){var e=this._schedule;return this._schedule=t,this._customScheduler=!0,e},r.prototype.hasCustomScheduler=function(){return this._customScheduler},r.prototype.enableTrampoline=function(){this._trampolineEnabled=!0},r.prototype.disableTrampolineIfNecessary=function(){p.hasDevTools&&(this._trampolineEnabled=!1)},r.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},r.prototype.fatalError=function(t,e){e?(process.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),process.exit(2)):this.throwLater(t)},r.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(n){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}},p.hasDevTools?(r.prototype.invokeLater=function(t,e,n){this._trampolineEnabled?i.call(this,t,e,n):this._schedule(function(){setTimeout(function(){t.call(e,n)},100)})},r.prototype.invoke=function(t,e,n){this._trampolineEnabled?o.call(this,t,e,n):this._schedule(function(){t.call(e,n)})},r.prototype.settlePromises=function(t){this._trampolineEnabled?a.call(this,t):this._schedule(function(){t._settlePromises()})}):(r.prototype.invokeLater=i,r.prototype.invoke=o,r.prototype.settlePromises=a),r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,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=r,e.exports.firstLineError=s},{"./queue":17,"./schedule":18,"./util":21}],2:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},a=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},s=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var f={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,a,void 0,u,f),l._then(s,c,void 0,u,f),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],3:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":15}],4:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),a=o.tryCatch,s=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n<t.length;++n)this._doInvokeOnCancel(t[n],e);else if(void 0!==t)if("function"==typeof t){if(!e){var r=a(t).call(this._boundValue());r===s&&(this._attachExtraTrace(r.e),c.throwLater(r.e))}}else t._resultCancelled(this)},e.prototype._invokeOnCancel=function(){var t=this._onCancel();this._unsetOnCancel(),c.invoke(this._doInvokeOnCancel,this,t)},e.prototype._invokeInternalOnCancel=function(){this._isCancellable()&&(this._doInvokeOnCancel(this._onCancel(),!0),this._unsetOnCancel())},e.prototype._resultCancelled=function(){this.cancel()}}},{"./util":21}],5:[function(t,e,n){"use strict";e.exports=function(e){function n(t,n,s){return function(c){var l=s._boundValue();t:for(var u=0;u<t.length;++u){var p=t[u];if(p===Error||null!=p&&p.prototype instanceof Error){if(c instanceof p)return o(n).call(l,c)}else if("function"==typeof p){var f=o(p).call(l,c);if(f===a)return f;if(f)return o(n).call(l,c)}else if(r.isObject(c)){for(var h=i(p),_=0;_<h.length;++_){var d=h[_];if(p[d]!=c[d])continue t}return o(n).call(l,c)}}return e}}var r=t("./util"),i=t("./es5").keys,o=r.tryCatch,a=r.errorObj;return n}},{"./es5":10,"./util":21}],6:[function(t,e,n){"use strict";e.exports=function(t){function e(){this._trace=new e.CapturedTrace(r())}function n(){return i?new e:void 0}function r(){var t=o.length-1;return t>=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,a=t._peekContext,s=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=a,t.prototype._peekContext=s,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],7:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+I.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function a(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?I.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function s(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function f(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function h(){this._trace=new x(this._peekContext())}function _(t,e){if(H(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=E(t);I.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),I.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&X){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="",a="";if(e._trace){for(var s=e._trace.stack.split("\n"),c=C(s),l=c.length-1;l>=0;--l){var u=c[l];if(!V.test(u)){var p=u.match(Q);p&&(o="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var f=c[0],l=0;l<s.length;++l)if(s[l]===f){l>0&&(a="\n"+s[l-1]);break}}var h="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+a;r._warn(h,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new U(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var a=E(o);o.stack=a.message+"\n"+a.stack.join("\n")}tt("warning",o)||k(o,"",!0)}}function g(t,e){for(var n=0;n<e.length-1;++n)e[n].push("From previous event:"),e[n]=e[n].join("\n");return n<e.length&&(e[n]=e[n].join("\n")),t+"\n"+e.join("\n")}function m(t){for(var e=0;e<t.length;++e)(0===t[e].length||e+1<t.length&&t[e][0]===t[e+1][0])&&(t.splice(e,1),e--)}function b(t){for(var e=t[0],n=1;n<t.length;++n){for(var r=t[n],i=e.length-1,o=e[i],a=-1,s=r.length-1;s>=0;--s)if(r[s]===o){a=s;break}for(var s=a;s>=0;--s){var c=r[s];if(e[i]!==c)break;e.pop(),i--}e=r}}function C(t){for(var e=[],n=0;n<t.length;++n){var r=t[n],i=" (No stack trace)"===r||q.test(r),o=i&&nt(r);i&&!o&&(M&&" "!==r.charAt(0)&&(r=" "+r),e.push(r))}return e}function w(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),n=0;n<e.length;++n){var r=e[n];if(" (No stack trace)"===r||q.test(r))break}return n>0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function E(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?w(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:C(e)}}function k(t,e,n){if("undefined"!=typeof console){var r;if(I.isObject(t)){var i=t.stack;r=e+G(i,t)}else r=e+String(t);"function"==typeof N?N(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function j(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){B.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||k(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():I.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+T(e)+">, no stack trace)"}function T(t){var e=41;return t.length<e?t:t.substr(0,e-3)+"..."}function P(){return"function"==typeof it}function R(t){var e=t.match(rt);return e?{fileName:e[1],line:parseInt(e[2],10)}:void 0}function S(t,e){if(P()){for(var n,r,i=t.stack.split("\n"),o=e.stack.split("\n"),a=-1,s=-1,c=0;c<i.length;++c){var l=R(i[c]);if(l){n=l.fileName,a=l.line;break}}for(var c=0;c<o.length;++c){var l=R(o[c]);if(l){r=l.fileName,s=l.line;break}}0>a||0>s||!n||!r||n!==r||a>=s||(nt=function(t){if(D.test(t))return!0;var e=R(t);return e&&e.fileName===n&&a<=e.line&&e.line<=s?!0:!1})}}function x(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,x),e>32&&this.uncycle()}var O,A,N,L=e._getDomain,B=e._async,U=t("./errors").Warning,I=t("./util"),H=I.canAttachTrace,D=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,V=/\((?:timers\.js):\d+:\d+\)/,Q=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,G=null,M=!1,W=!(0==I.env("BLUEBIRD_DEBUG")||!I.env("BLUEBIRD_DEBUG")&&"development"!==I.env("NODE_ENV")),$=!(0==I.env("BLUEBIRD_WARNINGS")||!W&&!I.env("BLUEBIRD_WARNINGS")),z=!(0==I.env("BLUEBIRD_LONG_STACK_TRACES")||!W&&!I.env("BLUEBIRD_LONG_STACK_TRACES")),X=0!=I.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&($||!!I.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0===(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout(function(){t._notifyUnhandledRejection()},1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){j("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),j("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=L();A="function"==typeof t?null===e?t:I.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=L();O="function"==typeof t?null===e?t:I.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(B.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&P()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(B.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),B.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=h,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),B.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&P()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return I.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!I.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return I.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!I.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),I.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!I.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return I.isNode?function(){return process.emit.apply(process,arguments)}:I.global?function(t){var e="on"+t.toLowerCase(),n=I.global[e];return n?(n.apply(I.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){B.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[t].apply(null,arguments))}catch(n){B.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,X=ot.warnings,I.isObject(n)&&"wForgottenReturn"in n&&(X=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(B.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=s,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=a,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;I.inherits(x,Error),n.CapturedTrace=x,x.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var a=e[r].stack,s=n[a];if(void 0!==s&&s!==r){s>0&&(e[s-1]._parent=void 0,e[s-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>s?(c._parent=e[s+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},x.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=E(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(C(i.stack.split("\n"))),i=i._parent;b(r),m(r),I.notEnumerableProp(t,"stack",g(n,r)),I.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=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():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,G=e;var n=Error.captureStackTrace;return nt=function(t){return D.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return q=/@/,G=e,M=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(G=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,G=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(N=function(t){console.warn(t)},I.isNode&&process.stderr.isTTY?N=function(t,e){var n=e?"[33m":"[31m";console.warn(n+t+"[0m\n")}:I.isNode||"string"!=typeof(new Error).stack||(N=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:$,longStackTraces:!1,cancellation:!1,monitoring:!1};return z&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return f},checkForgottenReturns:d,setBounds:S,warn:y,deprecated:v,CapturedTrace:x,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":9,"./util":21}],8:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],9:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return u(n,Error),n}function i(t){return this instanceof i?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,a,s=t("./es5"),c=s.freeze,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,f=r("Warning","warning"),h=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,a=RangeError}catch(v){o=r("TypeError","type error"),a=r("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),g=0;g<y.length;++g)"function"==typeof Array.prototype[y[g]]&&(d.prototype[y[g]]=Array.prototype[y[g]]);s.defineProperty(d.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),d.prototype.isOperational=!0;var m=0;d.prototype.toString=function(){var t=Array(4*m+1).join(" "),e="\n"+t+"AggregateError of:\n";m++,t=Array(4*m+1).join(" ");for(var n=0;n<this.length;++n){for(var r=this[n]===this?"[Circular AggregateError]":this[n]+"",i=r.split("\n"),o=0;o<i.length;++o)i[o]=t+i[o];r=i.join("\n"),e+=r+"\n"}return m--,e},u(i,Error);var b=Error.__BluebirdErrorTypes__;b||(b=c({CancellationError:h,TimeoutError:_,OperationalError:i,RejectionError:i,AggregateError:d}),s.defineProperty(Error,"__BluebirdErrorTypes__",{value:b,writable:!1,enumerable:!1,configurable:!1})),e.exports={Error:Error,TypeError:o,RangeError:a,CancellationError:b.CancellationError,OperationalError:b.OperationalError,TimeoutError:b.TimeoutError,AggregateError:b.AggregateError,Warning:f}},{"./es5":10,"./util":21}],10:[function(t,e,n){var r=function(){"use strict";return void 0===this}();if(r)e.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:r,propertyIsWritable:function(t,e){var n=Object.getOwnPropertyDescriptor(t,e);return!(n&&!n.writable&&!n.set)}};else{var i={}.hasOwnProperty,o={}.toString,a={}.constructor.prototype,s=function(t){var e=[];for(var n in t)i.call(t,n)&&e.push(n);return e},c=function(t,e){return{value:t[e]}},l=function(t,e,n){return t[e]=n.value,t},u=function(t){return t},p=function(t){try{return Object(t).constructor.prototype}catch(e){return a}},f=function(t){try{return"[object Array]"===o.call(t)}catch(e){return!1}};e.exports={isArray:f,keys:s,names:s,defineProperty:l,getDescriptor:c,freeze:u,getPrototypeOf:p,isES5:r,propertyIsWritable:function(){return!0}}}},{}],11:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t,e,n){this.promise=t,this.type=e,this.handler=n,this.called=!1,this.cancelPromise=null}function o(t){this.finallyHandler=t}function a(t,e){return null!=t.cancelPromise?(arguments.length>1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function s(){return l.call(this,this.promise._target()._settledValue())}function c(t){return a(this,t)?void 0:(f.e=t,f)}function l(t){var i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var h=n(u,i);if(h instanceof e){if(null!=this.cancelPromise){if(h._isCancelled()){var _=new p("late cancellation observer");return i._attachExtraTrace(_),f.e=_,f}h.isPending()&&h._attachCancellationCallback(new o(this))}return h._then(s,c,void 0,this,void 0)}}}return i.isRejected()?(a(this),f.e=t,f):(a(this),t)}var u=t("./util"),p=e.CancellationError,f=u.errorObj,h=t("./catch_filter")(r);return i.prototype.isFinallyHandler=function(){return 0===this.type},o.prototype._resultCancelled=function(){a(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,new i(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,l,l)},e.prototype.tap=function(t){return this._passThrough(t,1,l)},e.prototype.tapCatch=function(t){var n=arguments.length;if(1===n)return this._passThrough(t,1,void 0,l);var r,i=new Array(n-1),o=0;for(r=0;n-1>r;++r){var a=arguments[r];if(!u.isObject(a))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+u.classString(a)));i[o++]=a}i.length=o;var s=arguments[r];return this._passThrough(h(i,s,this),1,void 0,l)},i}},{"./catch_filter":5,"./util":21}],12:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,a){var s=t("./util");s.canEvaluate,s.tryCatch,s.errorObj;e.join=function(){var t,e=arguments.length-1;if(e>0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":21}],13:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var a=t("./util"),s=a.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+a.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=s(t).apply(this,arguments),a=r._popContext();return o.checkForgottenReturns(i,a,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+a.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=a.isArray(l)?s(t).apply(u,l):s(t).call(u,l)}else c=s(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===a.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":21}],14:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&u.getPrototypeOf(t)===Error.prototype}function i(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=u.keys(t),i=0;i<n.length;++i){var o=n[i];p.test(o)||(e[o]=t[o])}return e}return a.markAsOriginatingFromRejection(t),t}function o(t,e){return function(n,r){if(null!==t){if(n){var o=i(s(n));t._attachExtraTrace(o),t._reject(o)}else if(e){var a=[].slice.call(arguments,1);t._fulfill(a)}else t._fulfill(r);t=null}}}var a=t("./util"),s=a.maybeWrapAsError,c=t("./errors"),l=c.OperationalError,u=t("./es5"),p=/^(?:name|message|stack|cause)$/;e.exports=o},{"./errors":9,"./es5":10,"./util":21}],15:[function(t,e,n){"use strict";e.exports=function(){function n(){}function r(t,e){if(null==t||t.constructor!==i)throw new g("the promise constructor cannot be invoked directly\n\n See http://goo.gl/MqrFmX\n");if("function"!=typeof e)throw new g("expecting a function but got "+h.classString(e))}function i(t){t!==b&&r(this,t),this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._resolveFromExecutor(t),this._promiseCreated(),this._fireEvent("promiseCreated",this)}function o(t){this.promise._resolveCallback(t)}function a(t){this.promise._rejectCallback(t,!1)}function s(t){var e=new i(b);e._fulfillmentHandler0=t,e._rejectionHandler0=t,e._promise0=t,e._receiver0=t}var c,l=function(){return new g("circular promise resolution chain\n\n See http://goo.gl/MqrFmX\n")},u=function(){return new i.PromiseInspection(this._target())},p=function(t){return i.reject(new g(t))},f={},h=t("./util");c=h.isNode?function(){var t=process.domain;return void 0===t&&(t=null),t}:function(){return null},h.notEnumerableProp(i,"_getDomain",c);var _=t("./es5"),d=t("./async"),v=new d;_.defineProperty(i,"_async",{value:v});var y=t("./errors"),g=i.TypeError=y.TypeError;i.RangeError=y.RangeError;var m=i.CancellationError=y.CancellationError;i.TimeoutError=y.TimeoutError,i.OperationalError=y.OperationalError,i.RejectionError=y.OperationalError,i.AggregateError=y.AggregateError;var b=function(){},C={},w={},E=t("./thenables")(i,b),k=t("./promise_array")(i,b,E,p,n),j=t("./context")(i),F=(j.create,t("./debuggability")(i,j)),T=(F.CapturedTrace,t("./finally")(i,E,w)),P=t("./catch_filter")(w),R=t("./nodeback"),S=h.errorObj,x=h.tryCatch;return i.prototype.toString=function(){return"[object Promise]"},i.prototype.caught=i.prototype["catch"]=function(t){var e=arguments.length;if(e>1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!h.isObject(o))return p("Catch statement predicate: expecting an object but got "+h.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(r,t,this))}return this.then(void 0,t)},i.prototype.reflect=function(){return this._then(u,u,void 0,this,void 0)},i.prototype.then=function(t,e){if(F.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+h.classString(t);arguments.length>1&&(n+=", "+h.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},i.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},i.prototype.spread=function(t){return"function"!=typeof t?p("expecting a function but got "+h.classString(t)):this.all()._then(t,void 0,void 0,C,void 0); -},i.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},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new k(this).promise()},i.prototype.error=function(t){return this.caught(h.originatesFromRejection,t)},i.getNewLibraryCopy=e.exports,i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=x(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new k(t).promise()},i.cast=function(t){var e=E(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new g("expecting a function but got "+h.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var a=void 0!==o,s=a?o:new i(b),l=this._target(),u=l._bitField;a||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var p=c();if(0!==(50397184&u)){var f,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,f=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,f=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new m("late cancellation observer"),l._attachExtraTrace(_),f=e),v.invoke(d,l,{handler:null===p?f:"function"==typeof f&&h.domainBind(p,f),promise:s,receiver:r,value:_})}else l._addCallbacks(t,e,s,r,p);return s},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},i.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},i.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},i.prototype._setAsyncGuaranteed=function(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===f?void 0:void 0===e&&this._isBound()?this._boundValue():e},i.prototype._promiseAt=function(t){return this[4*t-4+2]},i.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},i.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=f),this._addCallbacks(e,n,r,i,null)},i.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=f),this._addCallbacks(n,r,i,o,null)},i.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:h.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:h.domainBind(i,e));else{var a=4*o-4;this[a+2]=n,this[a+3]=r,"function"==typeof t&&(this[a+0]=null===i?t:h.domainBind(i,t)),"function"==typeof e&&(this[a+1]=null===i?e:h.domainBind(i,e))}return this._setLength(o+1),o},i.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},i.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(l(),!1);var n=E(t,this);if(!(n instanceof i))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target();if(r===this)return void this._reject(l());var o=r._bitField;if(0===(50397184&o)){var a=this._length();a>0&&r._migrateCallback0(this);for(var s=1;a>s;++s)r._migrateCallbackAt(this,s);this._setFollowing(),this._setLength(0),this._setFollowee(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new m("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=h.ensureErrorObject(t),i=r===t;if(!i&&!n&&F.warnings()){var o="a promise was rejected with a non-error: "+h.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){if(t!==b){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)}},i.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===C?n&&"number"==typeof n.length?o=x(t).apply(this._boundValue(),n):(o=S,o.e=new g("cannot .spread() a non-array: "+h.classString(n))):o=x(t).call(e,n);var a=r._popContext();i=r._bitField,0===(65536&i)&&(o===w?r._reject(n):o===S?r._rejectCallback(o.e,!1):(F.checkForgottenReturns(o,a,"",r,this),r._resolveCallback(o)))}},i.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},i.prototype._followee=function(){return this._rejectionHandler0},i.prototype._setFollowee=function(t){this._rejectionHandler0=t},i.prototype._settlePromise=function(t,e,r,o){var a=t instanceof i,s=this._bitField,c=0!==(134217728&s);0!==(65536&s)?(a&&t._invokeInternalOnCancel(),r instanceof T&&r.isFinallyHandler()?(r.cancelPromise=t,x(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):a||t instanceof k?t._cancel():r.cancel()):"function"==typeof e?a?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&s)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):a&&(c&&t._setAsyncGuaranteed(),0!==(33554432&s)?t._fulfill(o):t._reject(o))},i.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,o=t.value;"function"==typeof e?n instanceof i?this._settlePromiseFromHandler(e,r,o,n):e.call(r,o,n):n instanceof i&&n._reject(o)},i.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},i.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},i.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},i.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,h.isNode):void((65535&e)>0?v.settlePromises(this):this._ensurePossibleRejectionHandled())},i.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},i.defer=i.pending=function(){F.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:a}},h.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,E,p,F),t("./bind")(i,b,E,F),t("./cancel")(i,k,p,F),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,k,E,b,v,c),i.Promise=i,i.version="3.5.1",h.toFastProperties(i),h.toFastProperties(i.prototype),s({a:1}),s({b:2}),s({c:3}),s(1),s(function(){}),s(void 0),s(!1),s(new i(b)),F.setBounds(d.firstLineError,h.lastLineError),i}},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function a(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}function s(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(s,o),s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var s=o._bitField;if(this._values=o,0===(50397184&s))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&s))return 0!==(16777216&s)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(a(n))):void this._iterate(o)},s.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,a=null,s=0;n>s;++s){var c=r(t[s],i);c instanceof e?(c=c._target(),a=c._bitField):a=null,o?null!==a&&c.suppressUnhandledRejections():null!==a?0===(50397184&a)?(c._proxy(this,s),this._values[s]=c):o=0!==(33554432&a)?this._promiseFulfilled(c._value(),s):0!==(16777216&a)?this._promiseRejected(c._reason(),s):this._promiseCancelled(s):o=this._promiseFulfilled(c,s)}o||i._setAsyncGuaranteed()},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},s.prototype._promiseCancelled=function(){return this._cancel(),!0},s.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},s.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;n<t.length;++n)t[n]instanceof e&&t[n].cancel()}},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}},{"./util":21}],17:[function(t,e,n){"use strict";function r(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacity<t},i.prototype._pushOne=function(t){var e=this.length();this._checkCapacity(e+1);var n=this._front+e&this._capacity-1;this[n]=t,this._length=e+1},i.prototype.push=function(t,e,n){var r=this.length()+3;if(this._willBeOverCapacity(r))return this._pushOne(t),this._pushOne(e),void this._pushOne(n);var i=this._front+r-3;this._checkCapacity(r);var o=this._capacity-1;this[i+0&o]=t,this[i+1&o]=e,this[i+2&o]=n,this._length=r},i.prototype.shift=function(){var t=this._front,e=this[t];return this[t]=void 0,this._front=t+1&this._capacity-1,this._length--,e},i.prototype.length=function(){return this._length},i.prototype._checkCapacity=function(t){this._capacity<t&&this._resizeTo(this._capacity<<1)},i.prototype._resizeTo=function(t){var e=this._capacity;this._capacity=t;var n=this._front,i=this._length,o=n+i&e-1;r(this,0,this,e,o)},e.exports=i},{}],18:[function(t,e,n){"use strict";var r,i=t("./util"),o=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")},a=i.getNativePromise();if(i.isNode&&"undefined"==typeof MutationObserver){var s=global.setImmediate,c=process.nextTick;r=i.isRecentNode?function(t){s.call(global,t)}:function(t){c.call(process,t)}}else if("function"==typeof a&&"function"==typeof a.resolve){var l=a.resolve();r=function(t){l.then(t)}}else r="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&(window.navigator.standalone||window.cordova)?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:o:function(){var t=document.createElement("div"),e={attributes:!0},n=!1,r=document.createElement("div"),i=new MutationObserver(function(){t.classList.toggle("foo"),n=!1});i.observe(r,e);var o=function(){n||(n=!0,r.classList.toggle("foo"))};return function(n){var r=new MutationObserver(function(){r.disconnect(),n()});r.observe(t,e),o()}}();e.exports=r},{"./util":21}],19:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},a=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},s=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=function(){return 0!==(8454144&this._bitField)},t.prototype.__isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return 0!==(8454144&this._target()._bitField)},t.prototype.isPending=function(){return a.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return s.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],20:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,r){if(u(t)){if(t instanceof e)return t;var i=o(t);if(i===l){r&&r._pushContext();var c=e.reject(i.e);return r&&r._popContext(),c}if("function"==typeof i){if(a(t)){var c=new e(n);return t._then(c._fulfill,c._reject,void 0,c,null),c}return s(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(e){return l.e=e,l}}function a(t){try{return p.call(t,"_promise0")}catch(e){return!1}}function s(t,r,i){function o(t){s&&(s._resolveCallback(t),s=null)}function a(t){s&&(s._rejectCallback(t,p,!0),s=null)}var s=new e(n),u=s;i&&i._pushContext(),s._captureStackTrace(),i&&i._popContext();var p=!0,f=c.tryCatch(r).call(t,o,a);return p=!1,s&&f===l&&(s._rejectCallback(f.e,!0,!0),s=null),u}var c=t("./util"),l=c.errorObj,u=c.isObject,p={}.hasOwnProperty;return r}},{"./util":21}],21:[function(t,e,n){"use strict";function r(){try{var t=R;return R=null,t.apply(this,arguments)}catch(e){return P.e=e,P}}function i(t){return R=t,r}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function a(t){return"function"==typeof t||"object"==typeof t&&null!==t}function s(t){return o(t)?new Error(v(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function p(t){throw t}function f(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=A.test(t+"")&&F.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function h(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return N.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return t instanceof Error||null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function g(t){try{u(t,"isOperational",!0)}catch(e){}}function m(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&F.propertyIsWritable(t,"stack")}function C(t){return{}.toString.call(t)}function w(t,e,n){for(var r=F.names(t),i=0;i<r.length;++i){var o=r[i];if(n(o))try{F.defineProperty(e,o,F.getDescriptor(t,o))}catch(a){}}}function E(t){return H?process.env[t]:void 0}function k(){if("function"==typeof Promise)try{var t=new Promise(function(){});if("[object Promise]"==={}.toString.call(t))return Promise}catch(e){}}function j(t,e){return t.bind(e)}var F=t("./es5"),T="undefined"==typeof navigator,P={e:{}},R,S="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0!==this?this:null,x=function(t,e){function n(){this.constructor=t,this.constructor$=e;for(var n in e.prototype)r.call(e.prototype,n)&&"$"!==n.charAt(n.length-1)&&(this[n+"$"]=e.prototype[n])}var r={}.hasOwnProperty;return n.prototype=e.prototype,t.prototype=new n,t.prototype},O=function(){var t=[Array.prototype,Object.prototype,Function.prototype],e=function(e){for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1};if(F.isES5){var n=Object.getOwnPropertyNames;return function(t){for(var r=[],i=Object.create(null);null!=t&&!e(t);){var o;try{o=n(t)}catch(a){return r}for(var s=0;s<o.length;++s){var c=o[s];if(!i[c]){i[c]=!0;var l=Object.getOwnPropertyDescriptor(t,c);null!=l&&null==l.get&&null==l.set&&r.push(c)}}t=F.getPrototypeOf(t)}return r}}var r={}.hasOwnProperty;return function(n){if(e(n))return[];var i=[];t:for(var o in n)if(r.call(n,o))i.push(o);else{for(var a=0;a<t.length;++a)if(r.call(t[a],o))continue t;i.push(o)}return i}}(),A=/this\s*\.\s*\S+\s*=/,N=/^[a-z$_][a-z$_0-9]*$/i,L=function(){return"stack"in new Error?function(t){return b(t)?t:new Error(v(t))}:function(t){if(b(t))return t;try{throw new Error(v(t))}catch(e){return e}}}(),B=function(t){return F.isArray(t)?t:null};if("undefined"!=typeof Symbol&&Symbol.iterator){var U="function"==typeof Array.from?function(t){return Array.from(t)}:function(t){for(var e,n=[],r=t[Symbol.iterator]();!(e=r.next()).done;)n.push(e.value);return n};B=function(t){return F.isArray(t)?t:null!=t&&"function"==typeof t[Symbol.iterator]?U(t):null}}var I="undefined"!=typeof process&&"[object process]"===C(process).toLowerCase(),H="undefined"!=typeof process&&"undefined"!=typeof process.env,D={isClass:f,isIdentifier:_,inheritedDataKeys:O,getDataPropertyOrDefault:l,thrower:p,isArray:F.isArray,asArray:B,notEnumerableProp:u,isPrimitive:o,isObject:a,isError:y,canEvaluate:T,errorObj:P,tryCatch:i,inherits:x,withAppended:c,maybeWrapAsError:s,toFastProperties:h,filledRange:d,toString:v,canAttachTrace:b,ensureErrorObject:L,originatesFromRejection:m,markAsOriginatingFromRejection:g,classString:C,copyDescriptors:w,hasDevTools:"undefined"!=typeof chrome&&chrome&&"function"==typeof chrome.loadTimes,isNode:I,hasEnvVariables:H,env:E,global:S,getNativePromise:k,domainBind:j};D.isRecentNode=D.isNode&&function(){var t=process.versions.node.split(".").map(Number);return 0===t[0]&&t[1]>10||t[0]>0}(),D.isNode&&D.toFastProperties(process);try{throw new Error}catch(V){D.lastLineError=V}e.exports=D},{"./es5":10}]},{},[3])(3)}),"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/mquery/node_modules/bluebird/js/browser/bluebird.js b/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js deleted file mode 100644 index 2bc524b5fc390741d5e3ac05365358b9a0121767..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js +++ /dev/null @@ -1,5623 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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 3.5.1 - * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each -*/ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ -"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); -}; - -}; - -},{}],2:[function(_dereq_,module,exports){ -"use strict"; -var firstLineError; -try {throw new Error(); } catch (e) {firstLineError = e;} -var schedule = _dereq_("./schedule"); -var Queue = _dereq_("./queue"); -var util = _dereq_("./util"); - -function Async() { - this._customScheduler = false; - this._isTickUsed = false; - this._lateQueue = new Queue(16); - this._normalQueue = new Queue(16); - this._haveDrainedQueues = false; - this._trampolineEnabled = true; - var self = this; - this.drainQueues = function () { - self._drainQueues(); - }; - this._schedule = schedule; -} - -Async.prototype.setScheduler = function(fn) { - var prev = this._schedule; - this._schedule = fn; - this._customScheduler = true; - return prev; -}; - -Async.prototype.hasCustomScheduler = function() { - return this._customScheduler; -}; - -Async.prototype.enableTrampoline = function() { - this._trampolineEnabled = true; -}; - -Async.prototype.disableTrampolineIfNecessary = function() { - if (util.hasDevTools) { - this._trampolineEnabled = false; - } -}; - -Async.prototype.haveItemsQueued = function () { - return this._isTickUsed || this._haveDrainedQueues; -}; - - -Async.prototype.fatalError = function(e, isNode) { - if (isNode) { - process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + - "\n"); - process.exit(2); - } else { - this.throwLater(e); - } -}; - -Async.prototype.throwLater = function(fn, arg) { - if (arguments.length === 1) { - arg = fn; - fn = function () { throw arg; }; - } - if (typeof setTimeout !== "undefined") { - setTimeout(function() { - fn(arg); - }, 0); - } else try { - this._schedule(function() { - fn(arg); - }); - } catch (e) { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } -}; - -function AsyncInvokeLater(fn, receiver, arg) { - this._lateQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncInvoke(fn, receiver, arg) { - this._normalQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncSettlePromises(promise) { - this._normalQueue._pushOne(promise); - this._queueTick(); -} - -if (!util.hasDevTools) { - Async.prototype.invokeLater = AsyncInvokeLater; - Async.prototype.invoke = AsyncInvoke; - Async.prototype.settlePromises = AsyncSettlePromises; -} else { - Async.prototype.invokeLater = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvokeLater.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - setTimeout(function() { - fn.call(receiver, arg); - }, 100); - }); - } - }; - - Async.prototype.invoke = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvoke.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - fn.call(receiver, arg); - }); - } - }; - - Async.prototype.settlePromises = function(promise) { - if (this._trampolineEnabled) { - AsyncSettlePromises.call(this, promise); - } else { - this._schedule(function() { - promise._settlePromises(); - }); - } - }; -} - -Async.prototype._drainQueue = function(queue) { - while (queue.length() > 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -}; - -Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; - -},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { -var calledBind = false; -var rejectThis = function(_, e) { - this._reject(e); -}; - -var targetRejected = function(e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); -}; - -var bindingResolved = function(thisArg, context) { - if (((this._bitField & 50397184) === 0)) { - this._resolveCallback(context.target); - } -}; - -var bindingRejected = function(e, context) { - if (!context.promiseRejectionQueued) this._reject(e); -}; - -Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, bindingRejected, undefined, ret, context); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; -}; - -Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~2097152); - } -}; - -Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; -}; - -Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); -}; -}; - -},{}],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")(); -bluebird.noConflict = noConflict; -module.exports = bluebird; - -},{"./promise":22}],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"); -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 args = [].slice.call(arguments, 1);; - 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":36}],6:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -Promise.prototype["break"] = Promise.prototype.cancel = function() { - if (!debug.cancellation()) return this._warn("cancellation is disabled"); - - var promise = this; - var child = promise; - while (promise._isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } - - var parent = promise._cancellationParent; - if (parent == null || !parent._isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - promise._setWillBeCancelled(); - child = promise; - promise = parent; - } - } -}; - -Promise.prototype._branchHasCancelled = function() { - this._branchesRemainingToCancel--; -}; - -Promise.prototype._enoughBranchesHaveCancelled = function() { - return this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0; -}; - -Promise.prototype._cancelBy = function(canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; - } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; - } - } - return false; -}; - -Promise.prototype._cancelBranched = function() { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } -}; - -Promise.prototype._cancel = function() { - if (!this._isCancellable()) return; - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); -}; - -Promise.prototype._cancelPromises = function() { - if (this._length() > 0) this._settlePromises(); -}; - -Promise.prototype._unsetOnCancel = function() { - this._onCancelField = undefined; -}; - -Promise.prototype._isCancellable = function() { - return this.isPending() && !this._isCancelled(); -}; - -Promise.prototype.isCancellable = function() { - return this.isPending() && !this.isCancelled(); -}; - -Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { - if (util.isArray(onCancelCallback)) { - for (var i = 0; i < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); - } - } - } else { - onCancelCallback._resultCancelled(this); - } - } -}; - -Promise.prototype._invokeOnCancel = function() { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); -}; - -Promise.prototype._invokeInternalOnCancel = function() { - if (this._isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); - } -}; - -Promise.prototype._resultCancelled = function() { - this.cancel(); -}; - -}; - -},{"./util":36}],7:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = _dereq_("./util"); -var getKeys = _dereq_("./es5").keys; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } - } - return NEXT_FILTER; - }; -} - -return catchFilter; -}; - -},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var longStackTraces = false; -var contextStack = []; - -Promise.prototype._promiseCreated = function() {}; -Promise.prototype._pushContext = function() {}; -Promise.prototype._popContext = function() {return null;}; -Promise._peekContext = Promise.prototype._peekContext = function() {}; - -function Context() { - this._trace = new Context.CapturedTrace(peekContext()); -} -Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); - } -}; - -Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; - } - return null; -}; - -function createContext() { - if (longStackTraces) return new Context(); -} - -function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; -} -Context.CapturedTrace = null; -Context.create = createContext; -Context.deactivateLongStackTraces = function() {}; -Context.activateLongStackTraces = function() { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var Promise_promiseCreated = Promise.prototype._promiseCreated; - Context.deactivateLongStackTraces = function() { - Promise.prototype._pushContext = Promise_pushContext; - Promise.prototype._popContext = Promise_popContext; - Promise._peekContext = Promise_PeekContext; - Promise.prototype._peekContext = Promise_peekContext; - Promise.prototype._promiseCreated = Promise_promiseCreated; - longStackTraces = false; - }; - longStackTraces = true; - Promise.prototype._pushContext = Context.prototype._pushContext; - Promise.prototype._popContext = Context.prototype._popContext; - Promise._peekContext = Promise.prototype._peekContext = peekContext; - Promise.prototype._promiseCreated = function() { - var ctx = this._peekContext(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; -}; -return Context; -}; - -},{}],9:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = _dereq_("./errors").Warning; -var util = _dereq_("./util"); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; -var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; -var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; -var stackFramePattern = null; -var formatStack = null; -var indentStackFrames = false; -var printWarning; -var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - (true || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); - -var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); - -var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - -var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - -Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); -}; - -Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; - -Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } -}; - -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); -}; - -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; -}; - -Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; -}; - -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); -}; - -Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -var disableLongStackTraces = function() {}; -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - -var fireDomEvent = (function() { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, - event); - return !util.global.dispatchEvent(domEvent); - }; - } - } catch (e) {} - return function() { - return false; - }; -})(); - -var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function() { - return false; - }; - } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } -})(); - -function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; -} - -var eventToObjectGenerator = { - promiseCreated: generatePromiseLifecycleEventObject, - promiseFulfilled: generatePromiseLifecycleEventObject, - promiseRejected: generatePromiseLifecycleEventObject, - promiseResolved: generatePromiseLifecycleEventObject, - promiseCancelled: generatePromiseLifecycleEventObject, - promiseChained: function(name, promise, child) { - return {promise: promise, child: child}; - }, - warning: function(name, warning) { - return {warning: warning}; - }, - unhandledRejection: function (name, reason, promise) { - return {reason: reason, promise: promise}; - }, - rejectionHandled: generatePromiseLifecycleEventObject -}; - -var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; - } - - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; - } - - return domEventFired || globalEventFired; -}; - -Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - - if (util.isObject(warningsOption)) { - if ("wForgottenReturn" in warningsOption) { - wForgottenReturn = !!warningsOption.wForgottenReturn; - } - } - } - if ("cancellation" in opts && opts.cancellation && !config.cancellation) { - if (async.haveItemsQueued()) { - throw new Error( - "cannot enable cancellation after promises are in use"); - } - Promise.prototype._clearCancellationData = - cancellationClearCancellationData; - Promise.prototype._propagateFrom = cancellationPropagateFrom; - Promise.prototype._onCancel = cancellationOnCancel; - Promise.prototype._setOnCancel = cancellationSetOnCancel; - Promise.prototype._attachCancellationCallback = - cancellationAttachCancellationCallback; - Promise.prototype._execute = cancellationExecute; - propagateFromFunction = cancellationPropagateFrom; - config.cancellation = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } - return Promise; -}; - -function defaultFireEvent() { return false; } - -Promise.prototype._fireEvent = defaultFireEvent; -Promise.prototype._execute = function(executor, resolve, reject) { - try { - executor(resolve, reject); - } catch (e) { - return e; - } -}; -Promise.prototype._onCancel = function () {}; -Promise.prototype._setOnCancel = function (handler) { ; }; -Promise.prototype._attachCancellationCallback = function(onCancel) { - ; -}; -Promise.prototype._captureStackTrace = function () {}; -Promise.prototype._attachExtraTrace = function () {}; -Promise.prototype._clearCancellationData = function() {}; -Promise.prototype._propagateFrom = function (parent, flags) { - ; - ; -}; - -function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - throw new TypeError("onCancel must be a function, got: " + - util.toString(onCancel)); - } - promise._attachCancellationCallback(onCancel); - }); - } catch (e) { - return e; - } -} - -function cancellationAttachCancellationCallback(onCancel) { - if (!this._isCancellable()) return this; - - var previousOnCancel = this._onCancel(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); - } -} - -function cancellationOnCancel() { - return this._onCancelField; -} - -function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; -} - -function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; -} - -function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} - -function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} -var propagateFromFunction = bindingPropagateFrom; - -function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; -} - -function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); -} - -function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = parseStackAndMessage(error); - util.notEnumerableProp(error, "stack", - parsed.message + "\n" + parsed.stack.join("\n")); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } -} - -function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = "at " + lineMatches[1] + - ":" + lineMatches[2] + ":" + lineMatches[3] + " "; - } - break; - } - } - - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { - - if (traceLines[i] === firstUserLine) { - if (i > 0) { - creatorLine = "\n" + traceLines[i - 1]; - } - break; - } - } - - } - } - var msg = "a promise was created in a " + name + - "handler " + handlerLine + "but was not returned from it, " + - "see http://goo.gl/rRqMUw" + - creatorLine; - promise._warn(msg, true, promiseCreated); - } -} - -function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); -} - -function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - if (shouldUseOwnTrace) { - promise._attachExtraTrace(warning); - } else if (config.longStackTraces && (ctx = Promise._peekContext())) { - ctx.attachExtraTrace(warning); - } else { - var parsed = parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } - - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } -} - -function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); -} - -function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; - } - } -} - -function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } - - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } -} - -function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; -} - -function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0 && error.name != "SyntaxError") { - stack = stack.slice(i); - } - return stack; -} - -function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: error.name == "SyntaxError" ? stack : cleanStack(stack) - }; -} - -function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -} - -function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } - - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } -} - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? obj.toString() : util.toString(obj); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; -} - -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } -} - -function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; -} - -function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); -} -util.inherits(CapturedTrace, Error); -Context.CapturedTrace = CapturedTrace; - -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } -}; - -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; - } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); - util.notEnumerableProp(error, "__stackCleaned__", true); -}; - -var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } - - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } - - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - return null; - -})([]); - -if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; - } -} - -var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - longStackTraces: function() { - return config.longStackTraces; - }, - warnings: function() { - return config.warnings; - }, - cancellation: function() { - return config.cancellation; - }, - monitoring: function() { - return config.monitoring; - }, - propagateFromFunction: function() { - return propagateFromFunction; - }, - boundValueFunction: function() { - return boundValueFunction; - }, - checkForgottenReturns: checkForgottenReturns, - setBounds: setBounds, - warn: warn, - deprecated: deprecated, - CapturedTrace: CapturedTrace, - fireDomEvent: fireDomEvent, - fireGlobalEvent: fireGlobalEvent -}; -}; - -},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -function returner() { - return this.value; -} -function thrower() { - throw this.reason; -} - -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); -}; - -Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } -}; - -Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } -}; -}; - -},{}],11:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; -var PromiseAll = Promise.all; - -function promiseAllThis() { - return PromiseAll(this); -} - -function PromiseMapSeries(promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, INTERNAL); -} - -Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, this, undefined); -}; - -Promise.prototype.mapSeries = function (fn) { - return PromiseReduce(this, fn, INTERNAL, INTERNAL); -}; - -Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, promises, undefined); -}; - -Promise.mapSeries = PromiseMapSeries; -}; - - -},{}],12:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var Objectfreeze = es5.freeze; -var util = _dereq_("./util"); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; -} - -var _TypeError, _RangeError; -var Warning = subError("Warning", "warning"); -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); -} - -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} - -es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true -}); -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; - -function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - -} -inherits(OperationalError, Error); - -var errorTypes = Error["__BluebirdErrorTypes__"]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false - }); -} - -module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - Warning: Warning -}; - -},{"./es5":13,"./util":36}],13:[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; - } - }; -} - -},{}],14:[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); -}; -}; - -},{}],15:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { -var util = _dereq_("./util"); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); - -function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; -} - -PassThroughHandlerContext.prototype.isFinallyHandler = function() { - return this.type === 0; -}; - -function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; -} - -FinallyHandlerCancelReaction.prototype._resultCancelled = function() { - checkCancel(this.finallyHandler); -}; - -function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; -} - -function succeed() { - return finallyHandler.call(this, this.promise._target()._settledValue()); -} -function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; -} -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret === NEXT_FILTER) { - return ret; - } else if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise._isCancelled()) { - var reason = - new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this)); - } - } - return maybePromise._then( - succeed, fail, undefined, this, undefined); - } - } - } - - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } -} - -Promise.prototype._passThrough = function(handler, type, success, fail) { - if (typeof handler !== "function") return this.then(); - return this._then(success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined); -}; - -Promise.prototype.lastly = -Promise.prototype["finally"] = function (handler) { - return this._passThrough(handler, - 0, - finallyHandler, - finallyHandler); -}; - - -Promise.prototype.tap = function (handler) { - return this._passThrough(handler, 1, finallyHandler); -}; - -Promise.prototype.tapCatch = function (handlerOrPredicate) { - var len = arguments.length; - if(len === 1) { - return this._passThrough(handlerOrPredicate, - 1, - undefined, - finallyHandler); - } else { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return Promise.reject(new TypeError( - "tapCatch statement predicate: " - + "expecting an object but got " + util.classString(item) - )); - } - } - catchInstances.length = j; - var handler = arguments[i]; - return this._passThrough(catchFilter(catchInstances, handler, this), - 1, - undefined, - finallyHandler); - } - -}; - -return PassThroughHandlerContext; -}; - -},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { -var errors = _dereq_("./errors"); -var TypeError = errors.TypeError; -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - for (var i = 0; i < yieldHandlers.length; ++i) { - traceParent._pushContext(); - var result = tryCatch(yieldHandlers[i])(value); - traceParent._popContext(); - if (result === errorObj) { - traceParent._pushContext(); - var ret = Promise.reject(errorObj.e); - traceParent._popContext(); - return ret; - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { - if (debug.cancellation()) { - var internal = new Promise(INTERNAL); - var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); - this._promise = internal.lastly(function() { - return _finallyPromise; - }); - internal._captureStackTrace(); - internal._setOnCancel(this); - } else { - 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; - this._yieldedPromise = null; - this._cancellationPhase = false; -} -util.inherits(PromiseSpawn, Proxyable); - -PromiseSpawn.prototype._isResolved = function() { - return this._promise === null; -}; - -PromiseSpawn.prototype._cleanup = function() { - this._promise = this._generator = null; - if (debug.cancellation() && this._finallyPromise !== null) { - this._finallyPromise._fulfill(); - this._finallyPromise = null; - } -}; - -PromiseSpawn.prototype._promiseCancelled = function() { - if (this._isResolved()) return; - var implementsReturn = typeof this._generator["return"] !== "undefined"; - - var result; - if (!implementsReturn) { - var reason = new Promise.CancellationError( - "generator .return() sentinel"); - Promise.coroutine.returnSentinel = reason; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - result = tryCatch(this._generator["throw"]).call(this._generator, - reason); - this._promise._popContext(); - } else { - this._promise._pushContext(); - result = tryCatch(this._generator["return"]).call(this._generator, - undefined); - this._promise._popContext(); - } - this._cancellationPhase = true; - this._yieldedPromise = null; - this._continue(result); -}; - -PromiseSpawn.prototype._promiseFulfilled = function(value) { - this._yieldedPromise = null; - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call(this._generator, value); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._promiseRejected = function(reason) { - this._yieldedPromise = null; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]) - .call(this._generator, reason); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._resultCancelled = function() { - if (this._yieldedPromise instanceof Promise) { - var promise = this._yieldedPromise; - this._yieldedPromise = null; - promise.cancel(); - } -}; - -PromiseSpawn.prototype.promise = function () { - return this._promise; -}; - -PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = undefined; - this._promiseFulfilled(undefined); -}; - -PromiseSpawn.prototype._continue = function (result) { - var promise = this._promise; - if (result === errorObj) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._rejectCallback(result.e, false); - } - } - - var value = result.value; - if (result.done === true) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._resolveCallback(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, - this._yieldHandlers, - this._promise); - if (maybePromise === null) { - this._promiseRejected( - new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + - "From coroutine:\u000a" + - this._stack.split("\n").slice(1, -7).join("\n") - ) - ); - return; - } - } - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - this._yieldedPromise = maybePromise; - maybePromise._proxy(this, null); - } else if (((bitField & 33554432) !== 0)) { - Promise._async.invoke( - this._promiseFulfilled, this, maybePromise._value() - ); - } else if (((bitField & 16777216) !== 0)) { - Promise._async.invoke( - this._promiseRejected, this, maybePromise._reason() - ); - } else { - this._promiseCancelled(); - } - } -}; - -Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - var stack = new Error().stack; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, - stack); - var ret = spawn.promise(); - spawn._generator = generator; - spawn._promiseFulfilled(undefined); - return ret; - }; -}; - -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - yieldHandlers.push(fn); -}; - -Promise.spawn = function (generatorFunction) { - debug.deprecated("Promise.spawn()", "Promise.coroutine()"); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; - -},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { -var util = _dereq_("./util"); -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 promiseSetter = function(i) { - return new Function("promise", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = promise; \n\ - ".replace(/Index/g, i)); - }; - - var generateHolderClass = function(total) { - var props = new Array(total); - for (var i = 0; i < props.length; ++i) { - props[i] = "this.p" + (i+1); - } - var assignment = props.join(" = ") + " = null;"; - var cancellationCode= "var promise;\n" + props.map(function(prop) { - return " \n\ - promise = " + prop + "; \n\ - if (promise instanceof Promise) { \n\ - promise.cancel(); \n\ - } \n\ - "; - }).join("\n"); - var passedArguments = props.join(", "); - var name = "Holder$" + total; - - - var code = "return function(tryCatch, errorObj, Promise, async) { \n\ - 'use strict'; \n\ - function [TheName](fn) { \n\ - [TheProperties] \n\ - this.fn = fn; \n\ - this.asyncNeeded = true; \n\ - this.now = 0; \n\ - } \n\ - \n\ - [TheName].prototype._callFunction = function(promise) { \n\ - promise._pushContext(); \n\ - var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ - promise._popContext(); \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(ret.e, false); \n\ - } else { \n\ - promise._resolveCallback(ret); \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype.checkFulfillment = function(promise) { \n\ - var now = ++this.now; \n\ - if (now === [TheTotal]) { \n\ - if (this.asyncNeeded) { \n\ - async.invoke(this._callFunction, this, promise); \n\ - } else { \n\ - this._callFunction(promise); \n\ - } \n\ - \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype._resultCancelled = function() { \n\ - [CancellationCode] \n\ - }; \n\ - \n\ - return [TheName]; \n\ - }(tryCatch, errorObj, Promise, async); \n\ - "; - - code = code.replace(/\[TheName\]/g, name) - .replace(/\[TheTotal\]/g, total) - .replace(/\[ThePassedArguments\]/g, passedArguments) - .replace(/\[TheProperties\]/g, assignment) - .replace(/\[CancellationCode\]/g, cancellationCode); - - return new Function("tryCatch", "errorObj", "Promise", "async", code) - (tryCatch, errorObj, Promise, async); - }; - - var holderClasses = []; - var thenCallbacks = []; - var promiseSetters = []; - - for (var i = 0; i < 8; ++i) { - holderClasses.push(generateHolderClass(i + 1)); - thenCallbacks.push(thenCallback(i + 1)); - promiseSetters.push(promiseSetter(i + 1)); - } - - reject = function (reason) { - this._reject(reason); - }; -}} - -Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (!true) { - if (last <= 8 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var HolderClass = holderClasses[last - 1]; - var holder = new HolderClass(fn); - var callbacks = thenCallbacks; - - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], ret); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - maybePromise._then(callbacks[i], reject, - undefined, ret, holder); - promiseSetters[i](maybePromise, holder); - holder.asyncNeeded = false; - } else if (((bitField & 33554432) !== 0)) { - callbacks[i].call(ret, - maybePromise._value(), holder); - } else if (((bitField & 16777216) !== 0)) { - ret._reject(maybePromise._reason()); - } else { - ret._cancel(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - - if (!ret._isFateSealed()) { - if (holder.asyncNeeded) { - var domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, holder.fn); - } - } - ret._setAsyncGuaranteed(); - ret._setOnCancel(holder); - } - return ret; - } - } - } - var args = [].slice.call(arguments);; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; - -}; - -},{"./util":36}],18:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var domain = getDomain(); - this._callback = domain === null ? fn : util.domainBind(domain, fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); -} -util.inherits(MappingPromiseArray, PromiseArray); - -MappingPromiseArray.prototype._asyncInit = function() { - 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 (index < 0) { - index = (index * -1) - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; - - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } - - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if (((bitField & 33554432) !== 0)) { - ret = maybePromise._value(); - } else if (((bitField & 16777216) !== 0)) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; - } - return false; -}; - -MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } -}; - -MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); -}; - -MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; -}; - -function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError("'concurrency' must be a number but it is " + - util.classString(options.concurrency))); - } - limit = options.concurrency; - } else { - return Promise.reject(new TypeError( - "options argument must be an object but it is " + - util.classString(options))); - } - } - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter).promise(); -} - -Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); -}; - -Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); -}; - - -}; - -},{"./util":36}],19:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.method", ret); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var ctx = arguments[2]; - value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) - : tryCatch(fn).call(ctx, arg); - } else { - value = tryCatch(fn)(); - } - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.try", ret); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); - } -}; -}; - -},{"./util":36}],20:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = _dereq_("./errors"); -var OperationalError = errors.OperationalError; -var es5 = _dereq_("./es5"); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -var rErrorKey = /^(?:name|message|stack|cause)$/; -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - util.markAsOriginatingFromRejection(obj); - return obj; -} - -function nodebackForPromise(promise, multiArgs) { - return function(err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); - } else { - var args = [].slice.call(arguments, 1);; - promise._fulfill(args); - } - promise = null; - }; -} - -module.exports = nodebackForPromise; - -},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var util = _dereq_("./util"); -var async = Promise._async; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = - tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundValue(); - var ret = val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} -function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var newReason = new Error(reason + ""); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundValue(), reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, - options) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then( - adapter, - errorAdapter, - undefined, - this, - nodeback - ); - } - return this; -}; -}; - -},{"./util":36}],22:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function() { -var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var reflectHandler = function() { - return new Promise.PromiseInspection(this._target()); -}; -var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); -}; -function Proxyable() {} -var UNDEFINED_BINDING = {}; -var util = _dereq_("./util"); - -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { - return null; - }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); - -var es5 = _dereq_("./es5"); -var Async = _dereq_("./async"); -var async = new Async(); -es5.defineProperty(Promise, "_async", {value: async}); -var errors = _dereq_("./errors"); -var TypeError = Promise.TypeError = errors.TypeError; -Promise.RangeError = errors.RangeError; -var CancellationError = Promise.CancellationError = errors.CancellationError; -Promise.TimeoutError = errors.TimeoutError; -Promise.OperationalError = errors.OperationalError; -Promise.RejectionError = errors.OperationalError; -Promise.AggregateError = errors.AggregateError; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {}; -var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); -var PromiseArray = - _dereq_("./promise_array")(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); -var Context = _dereq_("./context")(Promise); - /*jshint unused:false*/ -var createContext = Context.create; -var debug = _dereq_("./debuggability")(Promise, Context); -var CapturedTrace = debug.CapturedTrace; -var PassThroughHandlerContext = - _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); -var nodebackForPromise = _dereq_("./nodeback"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (self == null || self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - -} - -function Promise(executor) { - if (executor !== INTERNAL) { - check(this, executor); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - this._resolveFromExecutor(executor); - this._promiseCreated(); - this._fireEvent("promiseCreated", this); -} - -Promise.prototype.toString = function () { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection("Catch statement predicate: " + - "expecting an object but got " + util.classString(item)); - } - } - catchInstances.length = j; - fn = arguments[i]; - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); -}; - -Promise.prototype.reflect = function () { - return this._then(reflectHandler, - reflectHandler, undefined, this, undefined); -}; - -Promise.prototype.then = function (didFulfill, didReject) { - if (debug.warnings() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then(didFulfill, didReject, undefined, undefined, undefined); -}; - -Promise.prototype.done = function (didFulfill, didReject) { - var promise = - this._then(didFulfill, didReject, undefined, undefined, undefined); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); -}; - -Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return new PromiseArray(this).promise(); -}; - -Promise.prototype.error = function (fn) { - return this.caught(util.originatesFromRejection, fn); -}; - -Promise.getNewLibraryCopy = module.exports; - -Promise.is = function (val) { - return val instanceof Promise; -}; - -Promise.fromNode = Promise.fromCallback = function(fn) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs - : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); - } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - return async.setScheduler(fn); -}; - -Promise.prototype._then = function ( - didFulfill, - didReject, - _, receiver, - internalData -) { - var haveInternalData = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && - ((this._bitField & 2097152) !== 0)) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } - - var domain = getDomain(); - if (!((bitField & 50397184) === 0)) { - var handler, value, settler = target._settlePromiseCtx; - if (((bitField & 33554432) !== 0)) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if (((bitField & 16777216) !== 0)) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); - } - - return promise; -}; - -Promise.prototype._length = function () { - return this._bitField & 65535; -}; - -Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; -}; - -Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; -}; - -Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | - (len & 65535); -}; - -Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); -}; - -Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); -}; - -Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); -}; - -Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; -}; - -Promise.prototype._unsetCancelled = function() { - this._bitField = this._bitField & (~65536); -}; - -Promise.prototype._setCancelled = function() { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); -}; - -Promise.prototype._setWillBeCancelled = function() { - this._bitField = this._bitField | 8388608; -}; - -Promise.prototype._setAsyncGuaranteed = function() { - if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; -}; - -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[ - index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); - } - return ret; -}; - -Promise.prototype._promiseAt = function (index) { - return this[ - index * 4 - 4 + 2]; -}; - -Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[ - index * 4 - 4 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = function (index) { - return this[ - index * 4 - 4 + 1]; -}; - -Promise.prototype._boundValue = function() {}; - -Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._addCallbacks = function ( - fulfill, - reject, - promise, - receiver, - domain -) { - var index = this._length(); - - if (index >= 65535 - 4) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, reject); - } - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); -}; - -Promise.prototype._resolveCallback = function(value, shouldBind) { - if (((this._bitField & 117506048) !== 0)) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); - - if (shouldBind) this._propagateFrom(maybePromise, 2); - - var promise = maybePromise._target(); - - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } - - var bitField = promise._bitField; - if (((bitField & 50397184) === 0)) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(promise); - } else if (((bitField & 33554432) !== 0)) { - this._fulfill(promise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); - } -}; - -Promise.prototype._rejectCallback = -function(reason, synchronous, ignoreNonErrorWarnings) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); - } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); -}; - -Promise.prototype._resolveFromExecutor = function (executor) { - if (executor === INTERNAL) return; - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute(executor, function(value) { - promise._resolveCallback(value); - }, function (reason) { - promise._rejectCallback(reason, synchronous); - }); - synchronous = false; - this._popContext(); - - if (r !== undefined) { - promise._rejectCallback(r, true); - } -}; - -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - var bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError("cannot .spread() a non-array: " + - util.classString(value)); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } -}; - -Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; -}; - -Promise.prototype._followee = function() { - return this._rejectionHandler0; -}; - -Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; -}; - -Promise.prototype._settlePromise = function(promise, handler, receiver, value) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = ((bitField & 134217728) !== 0); - if (((bitField & 65536) !== 0)) { - if (isPromise) promise._invokeInternalOnCancel(); - - if (receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler()) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if (((bitField & 33554432) !== 0)) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if (((bitField & 33554432) !== 0)) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } -}; - -Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } -}; - -Promise.prototype._settlePromiseCtx = function(ctx) { - this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); -}; - -Promise.prototype._settlePromise0 = function(handler, value, bitField) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); -}; - -Promise.prototype._clearCallbackDataAtIndex = function(index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = undefined; -}; - -Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; - - if ((bitField & 65535) > 0) { - if (((bitField & 134217728) !== 0)) { - this._settlePromises(); - } else { - async.settlePromises(this); - } - } -}; - -Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; - - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } - - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } -}; - -Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } -}; - -Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = (bitField & 65535); - - if (len > 0) { - if (((bitField & 16842752) !== 0)) { - var reason = this._fulfillmentHandler0; - this._settlePromise0(this._rejectionHandler0, reason, bitField); - this._rejectPromises(len, reason); - } else { - var value = this._rejectionHandler0; - this._settlePromise0(this._fulfillmentHandler0, value, bitField); - this._fulfillPromises(len, value); - } - this._setLength(0); - } - this._clearCancellationData(); -}; - -Promise.prototype._settledValue = function() { - var bitField = this._bitField; - if (((bitField & 33554432) !== 0)) { - return this._rejectionHandler0; - } else if (((bitField & 16777216) !== 0)) { - return this._fulfillmentHandler0; - } -}; - -function deferResolve(v) {this.promise._resolveCallback(v);} -function deferReject(v) {this.promise._rejectCallback(v, false);} - -Promise.defer = Promise.pending = function() { - debug.deprecated("Promise.defer", "new Promise"); - var promise = new Promise(INTERNAL); - return { - promise: promise, - resolve: deferResolve, - reject: deferReject - }; -}; - -util.notEnumerableProp(Promise, - "_makeSelfResolutionError", - makeSelfResolutionError); - -_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, - debug); -_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); -_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); -_dereq_("./direct_resolve")(Promise); -_dereq_("./synchronous_inspection")(Promise); -_dereq_("./join")( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); -Promise.Promise = Promise; -Promise.version = "3.5.1"; -_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -_dereq_('./call_get.js')(Promise); -_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -_dereq_('./timers.js')(Promise, INTERNAL, debug); -_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); -_dereq_('./nodeify.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, debug); -_dereq_('./settle.js')(Promise, PromiseArray, debug); -_dereq_('./some.js')(Promise, PromiseArray, apiRejection); -_dereq_('./filter.js')(Promise, INTERNAL); -_dereq_('./each.js')(Promise, INTERNAL); -_dereq_('./any.js')(Promise); - - util.toFastProperties(Promise); - util.toFastProperties(Promise.prototype); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return Promise; - -}; - -},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = _dereq_("./util"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - case -6: return new Map(); - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -util.inherits(PromiseArray, Proxyable); - -PromiseArray.prototype.length = function () { - return this._length; -}; - -PromiseArray.prototype.promise = function () { - return this._promise; -}; - -PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - var values = tryConvertToPromise(this._values, this._promise); - if (values instanceof Promise) { - values = values._target(); - var bitField = values._bitField; - ; - this._values = values; - - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - this._iterate(values); -}; - -PromiseArray.prototype._iterate = function(values) { - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() ? new Array(len) : this._values; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); - - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } - - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); -}; - -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); -}; - -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; -}; - -PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; -}; - -PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } -}; - -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; - -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; - -return PromiseArray; -}; - -},{"./util":36}],24:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = _dereq_("./util"); -var nodebackForPromise = _dereq_("./nodeback"); -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var TypeError = _dereq_("./errors").TypeError; -var defaultSuffix = "Async"; -var defaultPromisified = {__isPromisified__: true}; -var noCopyProps = [ - "arity", "length", - "name", - "arguments", - "caller", - "callee", - "prototype", - "__isPromisified__" -]; -var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); - -var defaultFilter = function(name) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - name !== "constructor"; -}; - -function propsFilter(key) { - return !noCopyPropsPattern.test(key); -} - -function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } -} - -function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; -} -function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" - .replace("%s", suffix)); - } - } - } - } -} - -function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - var passesDefaultFilter = filter === defaultFilter - ? true : defaultFilter(key, value, obj); - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj, passesDefaultFilter)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; -} - -var escapeIdentRegex = function(str) { - return str.replace(/([$])/, "\\$"); -}; - -var makeNodePromisifiedEval; -if (!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, _, multiArgs) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var shouldProxyThis = typeof callback === "string" || receiver === THIS; - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (shouldProxyThis) { - ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; - } else { - ret = receiver === undefined - ? "ret = callback({{args}}, nodeback); break;\n" - : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; - } - return ret.replace("{{args}}", args).replace(", ", comma); - } - - function generateArgumentSwitchCase() { - var ret = ""; - for (var i = 0; i < argumentOrder.length; ++i) { - ret += "case " + argumentOrder[i] +":" + - generateCallForArgumentCount(argumentOrder[i]); - } - - ret += " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = nodeback; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace("[CodeForCall]", (shouldProxyThis - ? "ret = callback.apply(this, args);\n" - : "ret = callback.apply(receiver, args);\n")); - return ret; - } - - var getFunctionCode = typeof callback === "string" - ? ("this != null ? this['"+callback+"'] : fn") - : "fn"; - var body = "'use strict'; \n\ - var ret = function (Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._captureStackTrace(); \n\ - var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ - var ret; \n\ - var callback = tryCatch([GetFunctionCode]); \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ - } \n\ - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ - return promise; \n\ - }; \n\ - notEnumerableProp(ret, '__isPromisified__', true); \n\ - return ret; \n\ - ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) - .replace("[GetFunctionCode]", getFunctionCode); - body = body.replace("Parameters", parameterDeclaration(newParameterCount)); - return new Function("Promise", - "fn", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "tryCatch", - "errorObj", - "notEnumerableProp", - "INTERNAL", - body)( - Promise, - fn, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - util.tryCatch, - util.errorObj, - util.notEnumerableProp, - INTERNAL); -}; -} - -function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { - var defaultThis = (function() {return this;})(); - var method = callback; - if (typeof method === "string") { - callback = fn; - } - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - var promise = new Promise(INTERNAL); - promise._captureStackTrace(); - var cb = typeof method === "string" && this !== defaultThis - ? this[method] : callback; - var fn = nodebackForPromise(promise, multiArgs); - try { - cb.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - promise._rejectCallback(maybeWrapAsError(e), true, true); - } - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); - return promise; - } - util.notEnumerableProp(promisified, "__isPromisified__", true); - return promisified; -} - -var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - -function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - if (promisifier === makeNodePromisified) { - obj[promisifiedKey] = - makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); - } else { - var promisified = promisifier(fn, function() { - return makeNodePromisified(key, THIS, key, - fn, suffix, multiArgs); - }); - util.notEnumerableProp(promisified, "__isPromisified__", true); - obj[promisifiedKey] = promisified; - } - } - util.toFastProperties(obj); - return obj; -} - -function promisify(callback, receiver, multiArgs) { - return makeNodePromisified(callback, receiver, undefined, - callback, null, multiArgs); -} - -Promise.promisify = function (fn, options) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - if (isPromisified(fn)) { - return fn; - } - options = Object(options); - var receiver = options.context === undefined ? THIS : options.context; - var multiArgs = !!options.multiArgs; - var ret = promisify(fn, receiver, multiArgs); - util.copyDescriptors(fn, ret, propsFilter); - return ret; -}; - -Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - options = Object(options); - var multiArgs = !!options.multiArgs; - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - - var keys = util.inheritedDataKeys(target); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier, - multiArgs); - promisifyAll(value, suffix, filter, promisifier, multiArgs); - } - } - - return promisifyAll(target, suffix, filter, promisifier, multiArgs); -}; -}; - - -},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util"); -var isObject = util.isObject; -var es5 = _dereq_("./es5"); -var Es6Map; -if (typeof Map === "function") Es6Map = Map; - -var mapToEntries = (function() { - var index = 0; - var size = 0; - - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; - } - - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; -})(); - -var entriesToMap = function(entries) { - var ret = new Es6Map(); - var length = entries.length / 2 | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); - } - return ret; -}; - -function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; - } - } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, isMap ? -6 : -3); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = function () {}; - -PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - } - this._resolve(val); - return true; - } - return false; -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; -}; - -function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; -} - -Promise.prototype.props = function () { - return props(this); -}; - -Promise.props = function (promises) { - return props(promises); -}; -}; - -},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ -"use strict"; -function arrayMove(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - 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.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; - -},{}],27:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function( - Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util"); - -var raceLater = function (promise) { - return promise.then(function(array) { - return race(array, promise); - }); -}; - -function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else { - promises = util.asArray(promises); - if (promises === null) - return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); - } - - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 3); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === undefined && !(i in promises)) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; -} - -Promise.race = function (promises) { - return race(promises, undefined); -}; - -Promise.prototype.race = function () { - return race(this, undefined); -}; - -}; - -},{"./util":36}],28:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, fn); - if (initialValue !== undefined) { - initialValue = Promise.resolve(initialValue); - initialValue._attachCancellationCallback(this); - } - this._initialValue = initialValue; - this._currentCancellable = null; - if(_each === INTERNAL) { - this._eachValues = Array(this._length); - } else if (_each === 0) { - this._eachValues = null; - } else { - this._eachValues = undefined; - } - this._promise._captureStackTrace(); - this._init$(undefined, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && - this._eachValues !== null && - accum !== INTERNAL) { - this._eachValues.push(accum); - } -}; - -ReductionPromiseArray.prototype._eachComplete = function(value) { - if (this._eachValues !== null) { - this._eachValues.push(value); - } - return this._eachValues; -}; - -ReductionPromiseArray.prototype._init = function() {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = function() { - this._resolve(this._eachValues !== undefined ? this._eachValues - : this._initialValue); -}; - -ReductionPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -ReductionPromiseArray.prototype._resolve = function(value) { - this._promise._resolveCallback(value); - this._values = null; -}; - -ReductionPromiseArray.prototype._resultCancelled = function(sender) { - if (sender === this._initialValue) return this._cancel(); - if (this._isResolved()) return; - this._resultCancelled$(); - if (this._currentCancellable instanceof Promise) { - this._currentCancellable.cancel(); - } - if (this._initialValue instanceof Promise) { - this._initialValue.cancel(); - } -}; - -ReductionPromiseArray.prototype._iterate = function (values) { - this._values = values; - var value; - var i; - var length = values.length; - if (this._initialValue !== undefined) { - value = this._initialValue; - i = 0; - } else { - value = Promise.resolve(values[0]); - i = 1; - } - - this._currentCancellable = value; - - if (!value.isRejected()) { - for (; i < length; ++i) { - var ctx = { - accum: null, - value: values[i], - index: i, - length: length, - array: this - }; - value = value._then(gotAccum, undefined, undefined, ctx, undefined); - } - } - - if (this._eachValues !== undefined) { - value = value - ._then(this._eachComplete, undefined, undefined, this, undefined); - } - value._then(completed, completed, undefined, value, this); -}; - -Promise.prototype.reduce = function (fn, initialValue) { - return reduce(this, fn, initialValue, null); -}; - -Promise.reduce = function (promises, fn, initialValue, _each) { - return reduce(promises, fn, initialValue, _each); -}; - -function completed(valueOrReason, array) { - if (this.isFulfilled()) { - array._resolve(valueOrReason); - } else { - array._reject(valueOrReason); - } -} - -function reduce(promises, fn, initialValue, _each) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var array = new ReductionPromiseArray(promises, fn, initialValue, _each); - return array.promise(); -} - -function gotAccum(accum) { - this.accum = accum; - this.array._gotAccum(accum); - var value = tryConvertToPromise(this.value, this.array._promise); - if (value instanceof Promise) { - this.array._currentCancellable = value; - return value._then(gotValue, undefined, undefined, this, undefined); - } else { - return gotValue.call(this, value); - } -} - -function gotValue(value) { - var array = this.array; - var promise = array._promise; - var fn = tryCatch(array._fn); - promise._pushContext(); - var ret; - if (array._eachValues !== undefined) { - ret = fn.call(promise._boundValue(), value, this.index, this.length); - } else { - ret = fn.call(promise._boundValue(), - this.accum, value, this.index, this.length); - } - if (ret instanceof Promise) { - array._currentCancellable = ret; - } - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", - promise - ); - return ret; -} -}; - -},{"./util":36}],29:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var schedule; -var noAsyncScheduler = function() { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var NativePromise = util.getNativePromise(); -if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function(fn) { GlobalSetImmediate.call(global, fn); } - : function(fn) { ProcessNextTick.call(process, fn); }; -} else if (typeof NativePromise === "function" && - typeof NativePromise.resolve === "function") { - var nativePromise = NativePromise.resolve(); - schedule = function(fn) { - nativePromise.then(fn); - }; -} else if ((typeof MutationObserver !== "undefined") && - !(typeof window !== "undefined" && - window.navigator && - (window.navigator.standalone || window.cordova))) { - schedule = (function() { - var div = document.createElement("div"); - var opts = {attributes: true}; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function() { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); - - var scheduleToggle = function() { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; - - return function schedule(fn) { - var o = new MutationObserver(function() { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); -} else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; -} else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; -} else { - schedule = noAsyncScheduler; -} -module.exports = schedule; - -},{"./util":36}],30:[function(_dereq_,module,exports){ -"use strict"; -module.exports = - function(Promise, PromiseArray, debug) { -var PromiseInspection = Promise.PromiseInspection; -var util = _dereq_("./util"); - -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); - -SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { - var ret = new PromiseInspection(); - ret._bitField = 33554432; - ret._settledValueField = value; - return this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = function (reason, index) { - var ret = new PromiseInspection(); - ret._bitField = 16777216; - ret._settledValueField = reason; - return this._promiseResolved(index, ret); -}; - -Promise.settle = function (promises) { - debug.deprecated(".settle()", ".reflect()"); - return new SettledPromiseArray(promises).promise(); -}; - -Promise.prototype.settle = function () { - return Promise.settle(this); -}; -}; - -},{"./util":36}],31:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = _dereq_("./util"); -var RangeError = _dereq_("./errors").RangeError; -var AggregateError = _dereq_("./errors").AggregateError; -var isArray = util.isArray; -var CANCELLATION = {}; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; - -SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function () { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - return true; - } - return false; - -}; -SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._checkOutcome = function() { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; -}; - -SomePromiseArray.prototype._fulfilled = function () { - return this._totalResolved; -}; - -SomePromiseArray.prototype._rejected = function () { - return this._values.length - this.length(); -}; - -SomePromiseArray.prototype._addRejected = function (reason) { - this._values.push(reason); -}; - -SomePromiseArray.prototype._addFulfilled = function (value) { - this._values[this._totalResolved++] = value; -}; - -SomePromiseArray.prototype._canPossiblyFulfill = function () { - return this.length() - this._rejected(); -}; - -SomePromiseArray.prototype._getRangeError = function (count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; - -SomePromiseArray.prototype._resolveEmptyArray = function () { - this._reject(this._getRangeError(0)); -}; - -function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -Promise.some = function (promises, howMany) { - return some(promises, howMany); -}; - -Promise.prototype.some = function (howMany) { - return some(this, howMany); -}; - -Promise._SomePromiseArray = SomePromiseArray; -}; - -},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() : undefined; - } - else { - this._bitField = 0; - this._settledValueField = undefined; - } -} - -PromiseInspection.prototype._settledValue = function() { - return this._settledValueField; -}; - -var value = PromiseInspection.prototype.value = function () { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var reason = PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { - return (this._bitField & 33554432) !== 0; -}; - -var isRejected = PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; -}; - -var isPending = PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; -}; - -var isResolved = PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; -}; - -PromiseInspection.prototype.isCancelled = function() { - return (this._bitField & 8454144) !== 0; -}; - -Promise.prototype.__isCancelled = function() { - return (this._bitField & 65536) === 65536; -}; - -Promise.prototype._isCancelled = function() { - return this._target().__isCancelled(); -}; - -Promise.prototype.isCancelled = function() { - return (this._target()._bitField & 8454144) !== 0; -}; - -Promise.prototype.isPending = function() { - return isPending.call(this._target()); -}; - -Promise.prototype.isRejected = function() { - return isRejected.call(this._target()); -}; - -Promise.prototype.isFulfilled = function() { - return isFulfilled.call(this._target()); -}; - -Promise.prototype.isResolved = function() { - return isResolved.call(this._target()); -}; - -Promise.prototype.value = function() { - return value.call(this._target()); -}; - -Promise.prototype.reason = function() { - var target = this._target(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); -}; - -Promise.prototype._value = function() { - return this._settledValue(); -}; - -Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); -}; - -Promise.PromiseInspection = PromiseInspection; -}; - -},{}],33:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var isObject = util.isObject; - -function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; -} - -function doGetThen(obj) { - return obj.then; -} - -function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } -} - -function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; - - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } - - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } - - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; -} - -return tryConvertToPromise; -}; - -},{"./util":36}],34:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, debug) { -var util = _dereq_("./util"); -var TimeoutError = Promise.TimeoutError; - -function HandleWrapper(handle) { - this.handle = handle; -} - -HandleWrapper.prototype._resultCancelled = function() { - clearTimeout(this.handle); -}; - -var afterValue = function(value) { return delay(+this).thenReturn(value); }; -var delay = Promise.delay = function (ms, value) { - var ret; - var handle; - if (value !== undefined) { - ret = Promise.resolve(value) - ._then(afterValue, null, null, ms, undefined); - if (debug.cancellation() && value instanceof Promise) { - ret._setOnCancel(value); - } - } else { - ret = new Promise(INTERNAL); - handle = setTimeout(function() { ret._fulfill(); }, +ms); - if (debug.cancellation()) { - ret._setOnCancel(new HandleWrapper(handle)); - } - ret._captureStackTrace(); - } - ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.prototype.delay = function (ms) { - return delay(ms, this); -}; - -var afterTimeout = function (promise, message, parent) { - var err; - if (typeof message !== "string") { - if (message instanceof Error) { - err = message; - } else { - err = new TimeoutError("operation timed out"); - } - } else { - err = new TimeoutError(message); - } - util.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._reject(err); - - if (parent != null) { - parent.cancel(); - } -}; - -function successClear(value) { - clearTimeout(this.handle); - return value; -} - -function failureClear(reason) { - clearTimeout(this.handle); - throw reason; -} - -Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret, parent; - - var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { - if (ret.isPending()) { - afterTimeout(ret, message, parent); - } - }, ms)); - - if (debug.cancellation()) { - parent = this.then(); - ret = parent._then(successClear, failureClear, - undefined, handleWrapper, undefined); - ret._setOnCancel(handleWrapper); - } else { - ret = this._then(successClear, failureClear, - undefined, handleWrapper, undefined); - } - - return ret; -}; - -}; - -},{"./util":36}],35:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL, debug) { - var util = _dereq_("./util"); - var TypeError = _dereq_("./errors").TypeError; - var inherits = _dereq_("./util").inherits; - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var NULL = {}; - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = new Promise(INTERNAL); - function iterator() { - if (i >= len) return ret._fulfill(); - var maybePromise = castPreservingDisposable(resources[i++]); - if (maybePromise instanceof Promise && - maybePromise._isDisposable()) { - try { - maybePromise = tryConvertToPromise( - maybePromise._getDisposer().tryDispose(inspection), - resources.promise); - } catch (e) { - return thrower(e); - } - if (maybePromise instanceof Promise) { - return maybePromise._then(iterator, thrower, - null, null, null); - } - } - iterator(); - } - iterator(); - return ret; - } - - function Disposer(data, promise, context) { - this._data = data; - this._promise = promise; - this._context = context; - } - - Disposer.prototype.data = function () { - return this._data; - }; - - Disposer.prototype.promise = function () { - return this._promise; - }; - - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return NULL; - }; - - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var context = this._context; - if (context !== undefined) context._pushContext(); - var ret = resource !== NULL - ? this.doDispose(resource, inspection) : null; - if (context !== undefined) context._popContext(); - this._promise._unsetDisposable(); - this._data = null; - return ret; - }; - - Disposer.isDisposer = function (d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; - - function FunctionDisposer(fn, promise, context) { - this.constructor$(fn, promise, context); - } - inherits(FunctionDisposer, Disposer); - - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; - - function maybeUnwrapDisposer(value) { - if (Disposer.isDisposer(value)) { - this.resources[this.index]._setDisposable(value); - return value.promise(); - } - return value; - } - - function ResourceList(length) { - this.length = length; - this.promise = null; - this[length-1] = null; - } - - ResourceList.prototype._resultCancelled = function() { - var len = this.length; - for (var i = 0; i < len; ++i) { - var item = this[i]; - if (item instanceof Promise) { - item.cancel(); - } - } - }; - - Promise.using = function () { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var input; - var spreadArgs = true; - if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; - spreadArgs = false; - } else { - input = arguments; - len--; - } - var resources = new ResourceList(len); - for (var i = 0; i < len; ++i) { - var resource = input[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } else { - var maybePromise = tryConvertToPromise(resource); - if (maybePromise instanceof Promise) { - resource = - maybePromise._then(maybeUnwrapDisposer, null, null, { - resources: resources, - index: i - }, undefined); - } - } - resources[i] = resource; - } - - var reflectedResources = new Array(resources.length); - for (var i = 0; i < reflectedResources.length; ++i) { - reflectedResources[i] = Promise.resolve(resources[i]).reflect(); - } - - var resultPromise = Promise.all(reflectedResources) - .then(function(inspections) { - for (var i = 0; i < inspections.length; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - errorObj.e = inspection.error(); - return errorObj; - } else if (!inspection.isFulfilled()) { - resultPromise.cancel(); - return; - } - inspections[i] = inspection.value(); - } - promise._pushContext(); - - fn = tryCatch(fn); - var ret = spreadArgs - ? fn.apply(undefined, inspections) : fn(inspections); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, promiseCreated, "Promise.using", promise); - return ret; - }); - - var promise = resultPromise.lastly(function() { - var inspection = new Promise.PromiseInspection(resultPromise); - return dispose(resources, inspection); - }); - resources.promise = promise; - promise._setOnCancel(resources); - return promise; - }; - - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 131072; - this._disposer = disposer; - }; - - Promise.prototype._isDisposable = function () { - return (this._bitField & 131072) > 0; - }; - - Promise.prototype._getDisposer = function () { - return this._disposer; - }; - - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~131072); - this._disposer = undefined; - }; - - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this, createContext()); - } - throw new TypeError(); - }; - -}; - -},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var canEvaluate = typeof navigator == "undefined"; - -var errorObj = {e: {}}; -var tryCatchTarget; -var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; - -function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(safeToString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; - - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; - - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } - -})(); - -var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); - - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; - - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var l = 8; - while (l--) new FakeConstructor(); - return obj; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } -} - -function isError(obj) { - return obj instanceof Error || - (obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"); -} - -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 isError(obj) && es5.propertyIsWritable(obj, "stack"); -} - -var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } -})(); - -function classString(obj) { - return {}.toString.call(obj); -} - -function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } - } -} - -var asArray = function(v) { - if (es5.isArray(v)) { - return v; - } - return null; -}; - -if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; - - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; -} - -var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; - -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; - -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} - -function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -function domainBind(self, cb) { - return self.bind(cb); -} - -var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; - -},{"./es5":13}]},{},[4])(4) -}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } \ No newline at end of file diff --git a/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js b/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js deleted file mode 100644 index e02a9cddc505e788224c3c57556c11a16be35804..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js +++ /dev/null @@ -1,31 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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 3.5.1 - * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each -*/ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,n;return function r(t,e,n){function i(s,a){if(!e[s]){if(!t[s]){var c="function"==typeof _dereq_&&_dereq_;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s<n.length;s++)i(n[s]);return i}({1:[function(t,e,n){"use strict";e.exports=function(t){function e(t){var e=new n(t),r=e.promise();return e.setHowMany(1),e.setUnwrap(),e.init(),r}var n=t._SomePromiseArray;t.any=function(t){return e(t)},t.prototype.any=function(){return e(this)}}},{}],2:[function(t,e,n){"use strict";function r(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new u(16),this._normalQueue=new u(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var t=this;this.drainQueues=function(){t._drainQueues()},this._schedule=l}function i(t,e,n){this._lateQueue.push(t,e,n),this._queueTick()}function o(t,e,n){this._normalQueue.push(t,e,n),this._queueTick()}function s(t){this._normalQueue._pushOne(t),this._queueTick()}var a;try{throw new Error}catch(c){a=c}var l=t("./schedule"),u=t("./queue"),p=t("./util");r.prototype.setScheduler=function(t){var e=this._schedule;return this._schedule=t,this._customScheduler=!0,e},r.prototype.hasCustomScheduler=function(){return this._customScheduler},r.prototype.enableTrampoline=function(){this._trampolineEnabled=!0},r.prototype.disableTrampolineIfNecessary=function(){p.hasDevTools&&(this._trampolineEnabled=!1)},r.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},r.prototype.fatalError=function(t,e){e?(process.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),process.exit(2)):this.throwLater(t)},r.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(n){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}},p.hasDevTools?(r.prototype.invokeLater=function(t,e,n){this._trampolineEnabled?i.call(this,t,e,n):this._schedule(function(){setTimeout(function(){t.call(e,n)},100)})},r.prototype.invoke=function(t,e,n){this._trampolineEnabled?o.call(this,t,e,n):this._schedule(function(){t.call(e,n)})},r.prototype.settlePromises=function(t){this._trampolineEnabled?s.call(this,t):this._schedule(function(){t._settlePromises()})}):(r.prototype.invokeLater=i,r.prototype.invoke=o,r.prototype.settlePromises=s),r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,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=r,e.exports.firstLineError=a},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var h={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,s,void 0,u,h),l._then(a,c,void 0,u,h),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":22}],5:[function(t,e,n){"use strict";var r=Object.create;if(r){var i=r(null),o=r(null);i[" size"]=o[" size"]=0}e.exports=function(e){function n(t,n){var r;if(null!=t&&(r=t[n]),"function"!=typeof r){var i="Object "+a.classString(t)+" has no method '"+a.toString(n)+"'";throw new e.TypeError(i)}return r}function r(t){var e=this.pop(),r=n(t,e);return r.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}var s,a=t("./util"),c=a.canEvaluate;a.isIdentifier;e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e,n="number"==typeof t;if(n)e=o;else if(c){var r=s(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n<t.length;++n)this._doInvokeOnCancel(t[n],e);else if(void 0!==t)if("function"==typeof t){if(!e){var r=s(t).call(this._boundValue());r===a&&(this._attachExtraTrace(r.e),c.throwLater(r.e))}}else t._resultCancelled(this)},e.prototype._invokeOnCancel=function(){var t=this._onCancel();this._unsetOnCancel(),c.invoke(this._doInvokeOnCancel,this,t)},e.prototype._invokeInternalOnCancel=function(){this._isCancellable()&&(this._doInvokeOnCancel(this._onCancel(),!0),this._unsetOnCancel())},e.prototype._resultCancelled=function(){this.cancel()}}},{"./util":36}],7:[function(t,e,n){"use strict";e.exports=function(e){function n(t,n,a){return function(c){var l=a._boundValue();t:for(var u=0;u<t.length;++u){var p=t[u];if(p===Error||null!=p&&p.prototype instanceof Error){if(c instanceof p)return o(n).call(l,c)}else if("function"==typeof p){var h=o(p).call(l,c);if(h===s)return h;if(h)return o(n).call(l,c)}else if(r.isObject(c)){for(var f=i(p),_=0;_<f.length;++_){var d=f[_];if(p[d]!=c[d])continue t}return o(n).call(l,c)}}return e}}var r=t("./util"),i=t("./es5").keys,o=r.tryCatch,s=r.errorObj;return n}},{"./es5":13,"./util":36}],8:[function(t,e,n){"use strict";e.exports=function(t){function e(){this._trace=new e.CapturedTrace(r())}function n(){return i?new e:void 0}function r(){var t=o.length-1;return t>=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],9:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+H.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function s(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function a(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function f(){this._trace=new S(this._peekContext())}function _(t,e){if(N(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=j(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&W){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="",s="";if(e._trace){for(var a=e._trace.stack.split("\n"),c=w(a),l=c.length-1;l>=0;--l){var u=c[l];if(!U.test(u)){var p=u.match(M);p&&(o="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var h=c[0],l=0;l<a.length;++l)if(a[l]===h){l>0&&(s="\n"+a[l-1]);break}}var f="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;r._warn(f,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new L(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=j(o);o.stack=s.message+"\n"+s.stack.join("\n")}tt("warning",o)||E(o,"",!0)}}function m(t,e){for(var n=0;n<e.length-1;++n)e[n].push("From previous event:"),e[n]=e[n].join("\n");return n<e.length&&(e[n]=e[n].join("\n")),t+"\n"+e.join("\n")}function g(t){for(var e=0;e<t.length;++e)(0===t[e].length||e+1<t.length&&t[e][0]===t[e+1][0])&&(t.splice(e,1),e--)}function b(t){for(var e=t[0],n=1;n<t.length;++n){for(var r=t[n],i=e.length-1,o=e[i],s=-1,a=r.length-1;a>=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var c=r[a];if(e[i]!==c)break;e.pop(),i--}e=r}}function w(t){for(var e=[],n=0;n<t.length;++n){var r=t[n],i=" (No stack trace)"===r||q.test(r),o=i&&nt(r);i&&!o&&($&&" "!==r.charAt(0)&&(r=" "+r),e.push(r))}return e}function C(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),n=0;n<e.length;++n){var r=e[n];if(" (No stack trace)"===r||q.test(r))break}return n>0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function j(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?C(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:w(e)}}function E(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+Q(i,t)}else r=e+String(t);"function"==typeof D?D(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function k(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){I.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||E(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+x(e)+">, no stack trace)"}function x(t){var e=41;return t.length<e?t:t.substr(0,e-3)+"..."}function T(){return"function"==typeof it}function P(t){var e=t.match(rt);return e?{fileName:e[1],line:parseInt(e[2],10)}:void 0}function R(t,e){if(T()){for(var n,r,i=t.stack.split("\n"),o=e.stack.split("\n"),s=-1,a=-1,c=0;c<i.length;++c){var l=P(i[c]);if(l){n=l.fileName,s=l.line;break}}for(var c=0;c<o.length;++c){var l=P(o[c]);if(l){r=l.fileName,a=l.line;break}}0>s||0>a||!n||!r||n!==r||s>=a||(nt=function(t){if(B.test(t))return!0;var e=P(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function S(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,S),e>32&&this.uncycle()}var O,A,D,V=e._getDomain,I=e._async,L=t("./errors").Warning,H=t("./util"),N=H.canAttachTrace,B=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,U=/\((?:timers\.js):\d+:\d+\)/,M=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,Q=null,$=!1,G=!(0==H.env("BLUEBIRD_DEBUG")||!H.env("BLUEBIRD_DEBUG")&&"development"!==H.env("NODE_ENV")),z=!(0==H.env("BLUEBIRD_WARNINGS")||!G&&!H.env("BLUEBIRD_WARNINGS")),X=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!G&&!H.env("BLUEBIRD_LONG_STACK_TRACES")),W=0!=H.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(z||!!H.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0===(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout(function(){t._notifyUnhandledRejection()},1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){k("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),k("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=V();A="function"==typeof t?null===e?t:H.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=V();O="function"==typeof t?null===e?t:H.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(I.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&T()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(I.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),I.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=f,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),I.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&T()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!H.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!H.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),H.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!H.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return H.isNode?function(){return process.emit.apply(process,arguments)}:H.global?function(t){var e="on"+t.toLowerCase(),n=H.global[e];return n?(n.apply(H.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){I.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[t].apply(null,arguments))}catch(n){I.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,W=ot.warnings,H.isObject(n)&&"wForgottenReturn"in n&&(W=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(I.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=a,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=s,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(S,Error),n.CapturedTrace=S,S.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var s=e[r].stack,a=n[s];if(void 0!==a&&a!==r){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>a?(c._parent=e[a+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},S.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=j(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(w(i.stack.split("\n"))),i=i._parent;b(r),g(r),H.notEnumerableProp(t,"stack",m(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=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():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,Q=e;var n=Error.captureStackTrace;return nt=function(t){return B.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return q=/@/,Q=e,$=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(Q=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,Q=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(D=function(t){console.warn(t)},H.isNode&&process.stderr.isTTY?D=function(t,e){var n=e?"[33m":"[31m";console.warn(n+t+"[0m\n")}:H.isNode||"string"!=typeof(new Error).stack||(D=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:z,longStackTraces:!1,cancellation:!1,monitoring:!1};return X&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return h},checkForgottenReturns:d,setBounds:R,warn:y,deprecated:v,CapturedTrace:S,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":12,"./util":36}],10:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(t,e,n){"use strict";e.exports=function(t,e){function n(){return o(this)}function r(t,n){return i(t,n,e,e)}var i=t.reduce,o=t.all;t.prototype.each=function(t){return i(this,t,e,0)._then(n,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return i(this,t,e,e)},t.each=function(t,r){return i(t,r,e,0)._then(n,void 0,void 0,t,void 0)},t.mapSeries=r}},{}],12:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return u(n,Error),n}function i(t){return this instanceof i?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,s,a=t("./es5"),c=a.freeze,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,h=r("Warning","warning"),f=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(v){o=r("TypeError","type error"),s=r("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),m=0;m<y.length;++m)"function"==typeof Array.prototype[y[m]]&&(d.prototype[y[m]]=Array.prototype[y[m]]);a.defineProperty(d.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0}),d.prototype.isOperational=!0;var g=0;d.prototype.toString=function(){var t=Array(4*g+1).join(" "),e="\n"+t+"AggregateError of:\n";g++,t=Array(4*g+1).join(" ");for(var n=0;n<this.length;++n){for(var r=this[n]===this?"[Circular AggregateError]":this[n]+"",i=r.split("\n"),o=0;o<i.length;++o)i[o]=t+i[o];r=i.join("\n"),e+=r+"\n"}return g--,e},u(i,Error);var b=Error.__BluebirdErrorTypes__;b||(b=c({CancellationError:f,TimeoutError:_,OperationalError:i,RejectionError:i,AggregateError:d}),a.defineProperty(Error,"__BluebirdErrorTypes__",{value:b,writable:!1,enumerable:!1,configurable:!1})),e.exports={Error:Error,TypeError:o,RangeError:s,CancellationError:b.CancellationError,OperationalError:b.OperationalError,TimeoutError:b.TimeoutError,AggregateError:b.AggregateError,Warning:h}},{"./es5":13,"./util":36}],13:[function(t,e,n){var r=function(){"use strict";return void 0===this}();if(r)e.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,getDescriptor:Object.getOwnPropertyDescriptor,keys:Object.keys,names:Object.getOwnPropertyNames,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:r,propertyIsWritable:function(t,e){var n=Object.getOwnPropertyDescriptor(t,e);return!(n&&!n.writable&&!n.set)}};else{var i={}.hasOwnProperty,o={}.toString,s={}.constructor.prototype,a=function(t){var e=[];for(var n in t)i.call(t,n)&&e.push(n);return e},c=function(t,e){return{value:t[e]}},l=function(t,e,n){return t[e]=n.value,t},u=function(t){return t},p=function(t){try{return Object(t).constructor.prototype}catch(e){return s}},h=function(t){try{return"[object Array]"===o.call(t)}catch(e){return!1}};e.exports={isArray:h,keys:a,names:a,defineProperty:l,getDescriptor:c,freeze:u,getPrototypeOf:p,isES5:r,propertyIsWritable:function(){return!0}}}},{}],14:[function(t,e,n){"use strict";e.exports=function(t,e){var n=t.map;t.prototype.filter=function(t,r){return n(this,t,r,e)},t.filter=function(t,r,i){return n(t,r,i,e)}}},{}],15:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t,e,n){this.promise=t,this.type=e,this.handler=n,this.called=!1,this.cancelPromise=null}function o(t){this.finallyHandler=t}function s(t,e){return null!=t.cancelPromise?(arguments.length>1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function a(){return l.call(this,this.promise._target()._settledValue())}function c(t){return s(this,t)?void 0:(h.e=t,h)}function l(t){var i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var f=n(u,i);if(f instanceof e){if(null!=this.cancelPromise){if(f._isCancelled()){var _=new p("late cancellation observer");return i._attachExtraTrace(_),h.e=_,h}f.isPending()&&f._attachCancellationCallback(new o(this))}return f._then(a,c,void 0,this,void 0)}}}return i.isRejected()?(s(this),h.e=t,h):(s(this),t)}var u=t("./util"),p=e.CancellationError,h=u.errorObj,f=t("./catch_filter")(r);return i.prototype.isFinallyHandler=function(){return 0===this.type},o.prototype._resultCancelled=function(){s(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,new i(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,l,l)},e.prototype.tap=function(t){return this._passThrough(t,1,l)},e.prototype.tapCatch=function(t){var n=arguments.length;if(1===n)return this._passThrough(t,1,void 0,l);var r,i=new Array(n-1),o=0;for(r=0;n-1>r;++r){var s=arguments[r];if(!u.isObject(s))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+u.classString(s)));i[o++]=s}i.length=o;var a=arguments[r];return this._passThrough(f(i,a,this),1,void 0,l)},i}},{"./catch_filter":7,"./util":36}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r){for(var o=0;o<n.length;++o){r._pushContext();var s=f(n[o])(t);if(r._popContext(),s===h){r._pushContext();var a=e.reject(h.e);return r._popContext(),a}var c=i(s,r);if(c instanceof e)return c}return null}function c(t,n,i,o){if(s.cancellation()){var a=new e(r),c=this._finallyPromise=new e(r);this._promise=a.lastly(function(){return c}),a._captureStackTrace(),a._setOnCancel(this)}else{var l=this._promise=new e(r);l._captureStackTrace()}this._stack=o,this._generatorFunction=t,this._receiver=n,this._generator=void 0,this._yieldHandlers="function"==typeof i?[i].concat(_):_,this._yieldedPromise=null,this._cancellationPhase=!1}var l=t("./errors"),u=l.TypeError,p=t("./util"),h=p.errorObj,f=p.tryCatch,_=[];p.inherits(c,o),c.prototype._isResolved=function(){return null===this._promise},c.prototype._cleanup=function(){this._promise=this._generator=null,s.cancellation()&&null!==this._finallyPromise&&(this._finallyPromise._fulfill(),this._finallyPromise=null)},c.prototype._promiseCancelled=function(){if(!this._isResolved()){var t,n="undefined"!=typeof this._generator["return"];if(n)this._promise._pushContext(),t=f(this._generator["return"]).call(this._generator,void 0),this._promise._popContext();else{var r=new e.CancellationError("generator .return() sentinel");e.coroutine.returnSentinel=r,this._promise._attachExtraTrace(r),this._promise._pushContext(),t=f(this._generator["throw"]).call(this._generator,r),this._promise._popContext()}this._cancellationPhase=!0,this._yieldedPromise=null,this._continue(t)}},c.prototype._promiseFulfilled=function(t){this._yieldedPromise=null,this._promise._pushContext();var e=f(this._generator.next).call(this._generator,t);this._promise._popContext(),this._continue(e)},c.prototype._promiseRejected=function(t){this._yieldedPromise=null,this._promise._attachExtraTrace(t),this._promise._pushContext();var e=f(this._generator["throw"]).call(this._generator,t);this._promise._popContext(),this._continue(e)},c.prototype._resultCancelled=function(){if(this._yieldedPromise instanceof e){var t=this._yieldedPromise;this._yieldedPromise=null,t.cancel()}},c.prototype.promise=function(){return this._promise},c.prototype._run=function(){this._generator=this._generatorFunction.call(this._receiver),this._receiver=this._generatorFunction=void 0,this._promiseFulfilled(void 0)},c.prototype._continue=function(t){var n=this._promise;if(t===h)return this._cleanup(),this._cancellationPhase?n.cancel():n._rejectCallback(t.e,!1);var r=t.value;if(t.done===!0)return this._cleanup(),this._cancellationPhase?n.cancel():n._resolveCallback(r);var o=i(r,this._promise);if(!(o instanceof e)&&(o=a(o,this._yieldHandlers,this._promise),null===o))return void this._promiseRejected(new u("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/MqrFmX\n\n".replace("%s",String(r))+"From coroutine:\n"+this._stack.split("\n").slice(1,-7).join("\n")));o=o._target();var s=o._bitField;0===(50397184&s)?(this._yieldedPromise=o,o._proxy(this,null)):0!==(33554432&s)?e._async.invoke(this._promiseFulfilled,this,o._value()):0!==(16777216&s)?e._async.invoke(this._promiseRejected,this,o._reason()):this._promiseCancelled(); -},e.coroutine=function(t,e){if("function"!=typeof t)throw new u("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n");var n=Object(e).yieldHandler,r=c,i=(new Error).stack;return function(){var e=t.apply(this,arguments),o=new r(void 0,void 0,n,i),s=o.promise();return o._generator=e,o._promiseFulfilled(void 0),s}},e.coroutine.addYieldHandler=function(t){if("function"!=typeof t)throw new u("expecting a function but got "+p.classString(t));_.push(t)},e.spawn=function(t){if(s.deprecated("Promise.spawn()","Promise.coroutine()"),"function"!=typeof t)return n("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n");var r=new c(t,this),i=r.promise();return r._run(e.spawn),i}}},{"./errors":12,"./util":36}],17:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){var a=t("./util");a.canEvaluate,a.tryCatch,a.errorObj;e.join=function(){var t,e=arguments.length-1;if(e>0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=l();this._callback=null===i?e:u.domainBind(i,e),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],f.invoke(this._asyncInit,this,void 0)}function c(t,n,i,o){if("function"!=typeof n)return r("expecting a function but got "+u.classString(n));var s=0;if(void 0!==i){if("object"!=typeof i||null===i)return e.reject(new TypeError("options argument must be an object but it is "+u.classString(i)));if("number"!=typeof i.concurrency)return e.reject(new TypeError("'concurrency' must be a number but it is "+u.classString(i.concurrency)));s=i.concurrency}return s="number"==typeof s&&isFinite(s)&&s>=1?s:0,new a(t,n,s,o).promise()}var l=e._getDomain,u=t("./util"),p=u.tryCatch,h=u.errorObj,f=e._async;u.inherits(a,n),a.prototype._asyncInit=function(){this._init$(void 0,-2)},a.prototype._init=function(){},a.prototype._promiseFulfilled=function(t,n){var r=this._values,o=this.length(),a=this._preservedValues,c=this._limit;if(0>n){if(n=-1*n-1,r[n]=t,c>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(c>=1&&this._inFlight>=c)return r[n]=t,this._queue.push(n),!1;null!==a&&(a[n]=t);var l=this._promise,u=this._callback,f=l._boundValue();l._pushContext();var _=p(u).call(f,t,n,o),d=l._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",l),_===h)return this._reject(_.e),!0;var v=i(_,this._promise);if(v instanceof e){v=v._target();var y=v._bitField;if(0===(50397184&y))return c>=1&&this._inFlight++,r[n]=v,v._proxy(this,-1*(n+1)),!1;if(0===(33554432&y))return 0!==(16777216&y)?(this._reject(v._reason()),!0):(this._cancel(),!0);_=v._value()}r[n]=_}var m=++this._totalResolved;return m>=o?(null!==a?this._filter(r,a):this._resolve(r),!0):!1},a.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlight<e;){if(this._isResolved())return;var r=t.pop();this._promiseFulfilled(n[r],r)}},a.prototype._filter=function(t,e){for(var n=e.length,r=new Array(n),i=0,o=0;n>o;++o)t[o]&&(r[i++]=e[o]);r.length=i,this._resolve(r)},a.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return c(this,t,e,null)},e.map=function(t,e,n,r){return c(t,e,n,r)}}},{"./util":36}],19:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var s=t("./util"),a=s.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+s.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=a(t).apply(this,arguments),s=r._popContext();return o.checkForgottenReturns(i,s,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+s.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=s.isArray(l)?a(t).apply(u,l):a(t).call(u,l)}else c=a(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&u.getPrototypeOf(t)===Error.prototype}function i(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=u.keys(t),i=0;i<n.length;++i){var o=n[i];p.test(o)||(e[o]=t[o])}return e}return s.markAsOriginatingFromRejection(t),t}function o(t,e){return function(n,r){if(null!==t){if(n){var o=i(a(n));t._attachExtraTrace(o),t._reject(o)}else if(e){var s=[].slice.call(arguments,1);t._fulfill(s)}else t._fulfill(r);t=null}}}var s=t("./util"),a=s.maybeWrapAsError,c=t("./errors"),l=c.OperationalError,u=t("./es5"),p=/^(?:name|message|stack|cause)$/;e.exports=o},{"./errors":12,"./es5":13,"./util":36}],21:[function(t,e,n){"use strict";e.exports=function(e){function n(t,e){var n=this;if(!o.isArray(t))return r.call(n,t,e);var i=a(e).apply(n._boundValue(),[null].concat(t));i===c&&s.throwLater(i.e)}function r(t,e){var n=this,r=n._boundValue(),i=void 0===t?a(e).call(r,null):a(e).call(r,null,t);i===c&&s.throwLater(i.e)}function i(t,e){var n=this;if(!t){var r=new Error(t+"");r.cause=t,t=r}var i=a(e).call(n._boundValue(),t);i===c&&s.throwLater(i.e)}var o=t("./util"),s=e._async,a=o.tryCatch,c=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=r;void 0!==e&&Object(e).spread&&(o=n),this._then(o,i,void 0,this,t)}return this}}},{"./util":36}],22:[function(t,e,n){"use strict";e.exports=function(){function n(){}function r(t,e){if(null==t||t.constructor!==i)throw new m("the promise constructor cannot be invoked directly\n\n See http://goo.gl/MqrFmX\n");if("function"!=typeof e)throw new m("expecting a function but got "+f.classString(e))}function i(t){t!==b&&r(this,t),this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._resolveFromExecutor(t),this._promiseCreated(),this._fireEvent("promiseCreated",this)}function o(t){this.promise._resolveCallback(t)}function s(t){this.promise._rejectCallback(t,!1)}function a(t){var e=new i(b);e._fulfillmentHandler0=t,e._rejectionHandler0=t,e._promise0=t,e._receiver0=t}var c,l=function(){return new m("circular promise resolution chain\n\n See http://goo.gl/MqrFmX\n")},u=function(){return new i.PromiseInspection(this._target())},p=function(t){return i.reject(new m(t))},h={},f=t("./util");c=f.isNode?function(){var t=process.domain;return void 0===t&&(t=null),t}:function(){return null},f.notEnumerableProp(i,"_getDomain",c);var _=t("./es5"),d=t("./async"),v=new d;_.defineProperty(i,"_async",{value:v});var y=t("./errors"),m=i.TypeError=y.TypeError;i.RangeError=y.RangeError;var g=i.CancellationError=y.CancellationError;i.TimeoutError=y.TimeoutError,i.OperationalError=y.OperationalError,i.RejectionError=y.OperationalError,i.AggregateError=y.AggregateError;var b=function(){},w={},C={},j=t("./thenables")(i,b),E=t("./promise_array")(i,b,j,p,n),k=t("./context")(i),F=k.create,x=t("./debuggability")(i,k),T=(x.CapturedTrace,t("./finally")(i,j,C)),P=t("./catch_filter")(C),R=t("./nodeback"),S=f.errorObj,O=f.tryCatch;return i.prototype.toString=function(){return"[object Promise]"},i.prototype.caught=i.prototype["catch"]=function(t){var e=arguments.length;if(e>1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!f.isObject(o))return p("Catch statement predicate: expecting an object but got "+f.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(r,t,this))}return this.then(void 0,t)},i.prototype.reflect=function(){return this._then(u,u,void 0,this,void 0)},i.prototype.then=function(t,e){if(x.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+f.classString(t);arguments.length>1&&(n+=", "+f.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},i.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},i.prototype.spread=function(t){return"function"!=typeof t?p("expecting a function but got "+f.classString(t)):this.all()._then(t,void 0,void 0,w,void 0)},i.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},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new E(this).promise()},i.prototype.error=function(t){return this.caught(f.originatesFromRejection,t)},i.getNewLibraryCopy=e.exports,i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=O(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new E(t).promise()},i.cast=function(t){var e=j(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var s=void 0!==o,a=s?o:new i(b),l=this._target(),u=l._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var p=c();if(0!==(50397184&u)){var h,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,h=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,h=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new g("late cancellation observer"),l._attachExtraTrace(_),h=e),v.invoke(d,l,{handler:null===p?h:"function"==typeof h&&f.domainBind(p,h),promise:a,receiver:r,value:_})}else l._addCallbacks(t,e,a,r,p);return a},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},i.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},i.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},i.prototype._setAsyncGuaranteed=function(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===h?void 0:void 0===e&&this._isBound()?this._boundValue():e},i.prototype._promiseAt=function(t){return this[4*t-4+2]},i.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},i.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=h),this._addCallbacks(e,n,r,i,null)},i.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=h),this._addCallbacks(n,r,i,o,null)},i.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:f.domainBind(i,e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this[s+1]=null===i?e:f.domainBind(i,e))}return this._setLength(o+1),o},i.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},i.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(l(),!1);var n=j(t,this);if(!(n instanceof i))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target();if(r===this)return void this._reject(l());var o=r._bitField;if(0===(50397184&o)){var s=this._length();s>0&&r._migrateCallback0(this);for(var a=1;s>a;++a)r._migrateCallbackAt(this,a);this._setFollowing(),this._setLength(0),this._setFollowee(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new g("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=f.ensureErrorObject(t),i=r===t;if(!i&&!n&&x.warnings()){var o="a promise was rejected with a non-error: "+f.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){if(t!==b){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)}},i.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===w?n&&"number"==typeof n.length?o=O(t).apply(this._boundValue(),n):(o=S,o.e=new m("cannot .spread() a non-array: "+f.classString(n))):o=O(t).call(e,n);var s=r._popContext();i=r._bitField,0===(65536&i)&&(o===C?r._reject(n):o===S?r._rejectCallback(o.e,!1):(x.checkForgottenReturns(o,s,"",r,this),r._resolveCallback(o)))}},i.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},i.prototype._followee=function(){return this._rejectionHandler0},i.prototype._setFollowee=function(t){this._rejectionHandler0=t},i.prototype._settlePromise=function(t,e,r,o){var s=t instanceof i,a=this._bitField,c=0!==(134217728&a);0!==(65536&a)?(s&&t._invokeInternalOnCancel(),r instanceof T&&r.isFinallyHandler()?(r.cancelPromise=t,O(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):s||t instanceof E?t._cancel():r.cancel()):"function"==typeof e?s?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&a)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):s&&(c&&t._setAsyncGuaranteed(),0!==(33554432&a)?t._fulfill(o):t._reject(o))},i.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,o=t.value;"function"==typeof e?n instanceof i?this._settlePromiseFromHandler(e,r,o,n):e.call(r,o,n):n instanceof i&&n._reject(o)},i.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},i.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},i.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},i.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,f.isNode):void((65535&e)>0?v.settlePromises(this):this._ensurePossibleRejectionHandled())},i.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},i.defer=i.pending=function(){x.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:s}},f.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,j,p,x),t("./bind")(i,b,j,x),t("./cancel")(i,E,p,x),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,E,j,b,v,c),i.Promise=i,i.version="3.5.1",t("./map.js")(i,E,p,j,b,x),t("./call_get.js")(i),t("./using.js")(i,p,j,F,b,x),t("./timers.js")(i,b,x),t("./generators.js")(i,p,b,j,n,x),t("./nodeify.js")(i),t("./promisify.js")(i,b),t("./props.js")(i,E,j,p),t("./race.js")(i,b,j,p),t("./reduce.js")(i,E,p,j,b,x),t("./settle.js")(i,E,x),t("./some.js")(i,E,p),t("./filter.js")(i,b),t("./each.js")(i,b),t("./any.js")(i),f.toFastProperties(i),f.toFastProperties(i.prototype),a({a:1}),a({b:2}),a({c:3}),a(1),a(function(){}),a(void 0),a(!1),a(new i(b)),x.setBounds(d.firstLineError,f.lastLineError),i}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function s(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}function a(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var a=o._bitField;if(this._values=o,0===(50397184&a))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&a))return 0!==(16777216&a)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(s(n))):void this._iterate(o)},a.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;n>a;++a){var c=r(t[a],i);c instanceof e?(c=c._target(),s=c._bitField):s=null,o?null!==s&&c.suppressUnhandledRejections():null!==s?0===(50397184&s)?(c._proxy(this,a),this._values[a]=c):o=0!==(33554432&s)?this._promiseFulfilled(c._value(),a):0!==(16777216&s)?this._promiseRejected(c._reason(),a):this._promiseCancelled(a):o=this._promiseFulfilled(c,a)}o||i._setAsyncGuaranteed()},a.prototype._isResolved=function(){return null===this._values},a.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},a.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},a.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},a.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;n<t.length;++n)t[n]instanceof e&&t[n].cancel()}},a.prototype.shouldCopyValues=function(){return!0},a.prototype.getActualLength=function(t){return t},a}},{"./util":36}],24:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t){return!C.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(e){return!1}}function o(t,e,n){var r=f.getDataPropertyOrDefault(t,e+n,b);return r?i(r):!1}function s(t,e,n){for(var r=0;r<t.length;r+=2){var i=t[r];if(n.test(i))for(var o=i.replace(n,""),s=0;s<t.length;s+=2)if(t[s]===o)throw new m("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/MqrFmX\n".replace("%s",e))}}function a(t,e,n,r){for(var a=f.inheritedDataKeys(t),c=[],l=0;l<a.length;++l){var u=a[l],p=t[u],h=r===j?!0:j(u,p,t);"function"!=typeof p||i(p)||o(t,u,e)||!r(u,p,t,h)||c.push(u,p)}return s(c,e,n),c}function c(t,r,i,o,s,a){function c(){var i=r;r===h&&(i=this);var o=new e(n);o._captureStackTrace();var s="string"==typeof u&&this!==l?this[u]:t,c=_(o,a);try{s.apply(i,d(arguments,c))}catch(p){o._rejectCallback(v(p),!0,!0)}return o._isFateSealed()||o._setAsyncGuaranteed(),o}var l=function(){return this}(),u=t;return"string"==typeof u&&(t=o),f.notEnumerableProp(c,"__isPromisified__",!0),c}function l(t,e,n,r,i){for(var o=new RegExp(E(e)+"$"),s=a(t,e,o,n),c=0,l=s.length;l>c;c+=2){var u=s[c],p=s[c+1],_=u+e;if(r===k)t[_]=k(u,h,u,p,e,i);else{var d=r(p,function(){return k(u,h,u,p,e,i)});f.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return f.toFastProperties(t),t}function u(t,e,n){return k(t,e,void 0,t,null,n)}var p,h={},f=t("./util"),_=t("./nodeback"),d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,m=t("./errors").TypeError,g="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},E=function(t){return t.replace(/([$])/,"\\$")},k=y?p:c;e.promisify=function(t,e){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?h:e.context,o=!!e.multiArgs,s=u(t,n,o);return f.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new m("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");e=Object(e);var n=!!e.multiArgs,r=e.suffix;"string"!=typeof r&&(r=g);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=k),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=f.inheritedDataKeys(t),a=0;a<s.length;++a){var c=t[s[a]];"constructor"!==s[a]&&f.isClass(c)&&(l(c.prototype,r,i,o,n),l(c,r,i,o,n))}return l(t,r,i,o,n)}}},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){function o(t){var e,n=!1;if(void 0!==a&&t instanceof a)e=p(t),n=!0;else{var r=u.keys(t),i=r.length;e=new Array(2*i);for(var o=0;i>o;++o){var s=r[o];e[o]=t[s],e[o+i]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,n?-6:-3)}function s(t){var n,s=r(t);return l(s)?(n=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&n._propagateFrom(s,2),n):i("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}var a,c=t("./util"),l=c.isObject,u=t("./es5");"function"==typeof Map&&(a=Map);var p=function(){function t(t,r){this[e]=t,this[e+n]=r,e++}var e=0,n=0;return function(r){n=r.size,e=0;var i=new Array(2*r.size);return r.forEach(t,i),i}}(),h=function(t){for(var e=new a,n=t.length/2|0,r=0;n>r;++r){var i=t[n+r],o=t[r];e.set(i,o)}return e};c.inherits(o,n),o.prototype._init=function(){},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;if(n>=this._length){var r;if(this._isMap)r=h(this._values);else{r={};for(var i=this.length(),o=0,s=this.length();s>o;++o)r[this._values[o+i]]=this._values[o]}return this._resolve(r),!0}return!1},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,n){"use strict";function r(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacity<t},i.prototype._pushOne=function(t){var e=this.length();this._checkCapacity(e+1);var n=this._front+e&this._capacity-1;this[n]=t,this._length=e+1},i.prototype.push=function(t,e,n){var r=this.length()+3;if(this._willBeOverCapacity(r))return this._pushOne(t),this._pushOne(e),void this._pushOne(n);var i=this._front+r-3;this._checkCapacity(r);var o=this._capacity-1;this[i+0&o]=t,this[i+1&o]=e,this[i+2&o]=n,this._length=r},i.prototype.shift=function(){var t=this._front,e=this[t];return this[t]=void 0,this._front=t+1&this._capacity-1,this._length--,e},i.prototype.length=function(){return this._length},i.prototype._checkCapacity=function(t){this._capacity<t&&this._resizeTo(this._capacity<<1)},i.prototype._resizeTo=function(t){var e=this._capacity;this._capacity=t;var n=this._front,i=this._length,o=n+i&e-1;r(this,0,this,e,o)},e.exports=i},{}],27:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){function o(t,o){var c=r(t);if(c instanceof e)return a(c);if(t=s.asArray(t),null===t)return i("expecting an array or an iterable object but got "+s.classString(t));var l=new e(n);void 0!==o&&l._propagateFrom(o,3);for(var u=l._fulfill,p=l._reject,h=0,f=t.length;f>h;++h){var _=t[h];(void 0!==_||h in t)&&e.cast(_)._then(u,p,void 0,l,null)}return l}var s=t("./util"),a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util":36}],28:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t);var s=h();this._fn=null===s?n:f.domainBind(s,n),void 0!==r&&(r=e.resolve(r),r._attachCancellationCallback(this)),this._initialValue=r,this._currentCancellable=null,i===o?this._eachValues=Array(this._length):0===i?this._eachValues=null:this._eachValues=void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function c(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function l(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+f.classString(e));var o=new a(t,e,n,i);return o.promise()}function u(t){this.accum=t,this.array._gotAccum(t);var n=i(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(p,void 0,void 0,this,void 0)):p.call(this,n)}function p(t){var n=this.array,r=n._promise,i=_(n._fn);r._pushContext();var o;o=void 0!==n._eachValues?i.call(r._boundValue(),t,this.index,this.length):i.call(r._boundValue(),this.accum,t,this.index,this.length),o instanceof e&&(n._currentCancellable=o);var a=r._popContext();return s.checkForgottenReturns(o,a,void 0!==n._eachValues?"Promise.each":"Promise.reduce",r),o}var h=e._getDomain,f=t("./util"),_=f.tryCatch;f.inherits(a,n),a.prototype._gotAccum=function(t){void 0!==this._eachValues&&null!==this._eachValues&&t!==o&&this._eachValues.push(t)},a.prototype._eachComplete=function(t){return null!==this._eachValues&&this._eachValues.push(t),this._eachValues},a.prototype._init=function(){},a.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},a.prototype.shouldCopyValues=function(){return!1},a.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},a.prototype._resultCancelled=function(t){return t===this._initialValue?this._cancel():void(this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel()))},a.prototype._iterate=function(t){this._values=t;var n,r,i=t.length;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(u,void 0,void 0,o,void 0)}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(c,c,void 0,n,this)},e.prototype.reduce=function(t,e){return l(this,t,e,null)},e.reduce=function(t,e,n,r){return l(t,e,n,r)}}},{"./util":36}],29:[function(t,e,n){"use strict";var r,i=t("./util"),o=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")},s=i.getNativePromise();if(i.isNode&&"undefined"==typeof MutationObserver){var a=global.setImmediate,c=process.nextTick;r=i.isRecentNode?function(t){a.call(global,t)}:function(t){c.call(process,t)}}else if("function"==typeof s&&"function"==typeof s.resolve){var l=s.resolve();r=function(t){l.then(t)}}else r="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&(window.navigator.standalone||window.cordova)?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:o:function(){var t=document.createElement("div"),e={attributes:!0},n=!1,r=document.createElement("div"),i=new MutationObserver(function(){t.classList.toggle("foo"),n=!1});i.observe(r,e);var o=function(){n||(n=!0,r.classList.toggle("foo"))};return function(n){var r=new MutationObserver(function(){r.disconnect(),n()});r.observe(t,e),o()}}();e.exports=r},{"./util":36}],30:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t)}var o=e.PromiseInspection,s=t("./util");s.inherits(i,n),i.prototype._promiseResolved=function(t,e){this._values[t]=e;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},i.prototype._promiseFulfilled=function(t,e){var n=new o;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},i.prototype._promiseRejected=function(t,e){var n=new o;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t), -this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new i(t),o=n.promise();return n.setHowMany(e),n.init(),o}var s=t("./util"),a=t("./errors").RangeError,c=t("./errors").AggregateError,l=s.isArray,u={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=l(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()?(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0):!1},i.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(u),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new c,e=this.length();e<this._values.length;++e)this._values[e]!==u&&t.push(this._values[e]);return t.length>0?this._reject(t):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t)},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=function(){return 0!==(8454144&this._bitField)},t.prototype.__isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return 0!==(8454144&this._target()._bitField)},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,r){if(u(t)){if(t instanceof e)return t;var i=o(t);if(i===l){r&&r._pushContext();var c=e.reject(i.e);return r&&r._popContext(),c}if("function"==typeof i){if(s(t)){var c=new e(n);return t._then(c._fulfill,c._reject,void 0,c,null),c}return a(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(e){return l.e=e,l}}function s(t){try{return p.call(t,"_promise0")}catch(e){return!1}}function a(t,r,i){function o(t){a&&(a._resolveCallback(t),a=null)}function s(t){a&&(a._rejectCallback(t,p,!0),a=null)}var a=new e(n),u=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var p=!0,h=c.tryCatch(r).call(t,o,s);return p=!1,a&&h===l&&(a._rejectCallback(h.e,!0,!0),a=null),u}var c=t("./util"),l=c.errorObj,u=c.isObject,p={}.hasOwnProperty;return r}},{"./util":36}],34:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.handle=t}function o(t){return clearTimeout(this.handle),t}function s(t){throw clearTimeout(this.handle),t}var a=t("./util"),c=e.TimeoutError;i.prototype._resultCancelled=function(){clearTimeout(this.handle)};var l=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,o){var s,a;return void 0!==o?(s=e.resolve(o)._then(l,null,null,t,void 0),r.cancellation()&&o instanceof e&&s._setOnCancel(o)):(s=new e(n),a=setTimeout(function(){s._fulfill()},+t),r.cancellation()&&s._setOnCancel(new i(a)),s._captureStackTrace()),s._setAsyncGuaranteed(),s};e.prototype.delay=function(t){return u(t,this)};var p=function(t,e,n){var r;r="string"!=typeof e?e instanceof Error?e:new c("operation timed out"):new c(e),a.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._reject(r),null!=n&&n.cancel()};e.prototype.timeout=function(t,e){t=+t;var n,a,c=new i(setTimeout(function(){n.isPending()&&p(n,e,a)},t));return r.cancellation()?(a=this.then(),n=a._then(o,s,void 0,c,void 0),n._setOnCancel(c)):n=this._then(o,s,void 0,c,void 0),n}}},{"./util":36}],35:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t){setTimeout(function(){throw t},0)}function c(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function l(t,n){function i(){if(s>=l)return u._fulfill();var o=c(t[s++]);if(o instanceof e&&o._isDisposable()){try{o=r(o._getDisposer().tryDispose(n),t.promise)}catch(p){return a(p)}if(o instanceof e)return o._then(i,a,null,null,null)}i()}var s=0,l=t.length,u=new e(o);return i(),u}function u(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function h(t){return u.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function f(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,m=_.tryCatch,g={};u.prototype.data=function(){return this._data},u.prototype.promise=function(){return this._promise},u.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():g},u.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=e!==g?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},u.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(p,u),p.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},f.prototype._resultCancelled=function(){for(var t=this.length,n=0;t>n;++n){var r=this[n];r instanceof e&&r.cancel()}},e.using=function(){var t=arguments.length;if(2>t)return n("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return n("expecting a function but got "+_.classString(i));var o,a=!0;2===t&&Array.isArray(arguments[0])?(o=arguments[0],t=o.length,a=!1):(o=arguments,t--);for(var c=new f(t),p=0;t>p;++p){var d=o[p];if(u.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var g=r(d);g instanceof e&&(d=g._then(h,null,null,{resources:c,index:p},void 0))}c[p]=d}for(var b=new Array(c.length),p=0;p<b.length;++p)b[p]=e.resolve(c[p]).reflect();var w=e.all(b).then(function(t){for(var e=0;e<t.length;++e){var n=t[e];if(n.isRejected())return y.e=n.error(),y;if(!n.isFulfilled())return void w.cancel();t[e]=n.value()}C._pushContext(),i=m(i);var r=a?i.apply(void 0,t):i(t),o=C._popContext();return s.checkForgottenReturns(r,o,"Promise.using",C),r}),C=w.lastly(function(){var t=new e.PromiseInspection(w);return l(c,t)});return c.promise=C,C._setOnCancel(c),C},e.prototype._setDisposable=function(t){this._bitField=131072|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(131072&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new d}}},{"./errors":12,"./util":36}],36:[function(t,e,n){"use strict";function r(){try{var t=P;return P=null,t.apply(this,arguments)}catch(e){return T.e=e,T}}function i(t){return P=t,r}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return"function"==typeof t||"object"==typeof t&&null!==t}function a(t){return o(t)?new Error(v(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function p(t){throw t}function h(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=A.test(t+"")&&F.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function f(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return D.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return t instanceof Error||null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function m(t){try{u(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&F.propertyIsWritable(t,"stack")}function w(t){return{}.toString.call(t)}function C(t,e,n){for(var r=F.names(t),i=0;i<r.length;++i){var o=r[i];if(n(o))try{F.defineProperty(e,o,F.getDescriptor(t,o))}catch(s){}}}function j(t){return N?process.env[t]:void 0}function E(){if("function"==typeof Promise)try{var t=new Promise(function(){});if("[object Promise]"==={}.toString.call(t))return Promise}catch(e){}}function k(t,e){return t.bind(e)}var F=t("./es5"),x="undefined"==typeof navigator,T={e:{}},P,R="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0!==this?this:null,S=function(t,e){function n(){this.constructor=t,this.constructor$=e;for(var n in e.prototype)r.call(e.prototype,n)&&"$"!==n.charAt(n.length-1)&&(this[n+"$"]=e.prototype[n])}var r={}.hasOwnProperty;return n.prototype=e.prototype,t.prototype=new n,t.prototype},O=function(){var t=[Array.prototype,Object.prototype,Function.prototype],e=function(e){for(var n=0;n<t.length;++n)if(t[n]===e)return!0;return!1};if(F.isES5){var n=Object.getOwnPropertyNames;return function(t){for(var r=[],i=Object.create(null);null!=t&&!e(t);){var o;try{o=n(t)}catch(s){return r}for(var a=0;a<o.length;++a){var c=o[a];if(!i[c]){i[c]=!0;var l=Object.getOwnPropertyDescriptor(t,c);null!=l&&null==l.get&&null==l.set&&r.push(c)}}t=F.getPrototypeOf(t)}return r}}var r={}.hasOwnProperty;return function(n){if(e(n))return[];var i=[];t:for(var o in n)if(r.call(n,o))i.push(o);else{for(var s=0;s<t.length;++s)if(r.call(t[s],o))continue t;i.push(o)}return i}}(),A=/this\s*\.\s*\S+\s*=/,D=/^[a-z$_][a-z$_0-9]*$/i,V=function(){return"stack"in new Error?function(t){return b(t)?t:new Error(v(t))}:function(t){if(b(t))return t;try{throw new Error(v(t))}catch(e){return e}}}(),I=function(t){return F.isArray(t)?t:null};if("undefined"!=typeof Symbol&&Symbol.iterator){var L="function"==typeof Array.from?function(t){return Array.from(t)}:function(t){for(var e,n=[],r=t[Symbol.iterator]();!(e=r.next()).done;)n.push(e.value);return n};I=function(t){return F.isArray(t)?t:null!=t&&"function"==typeof t[Symbol.iterator]?L(t):null}}var H="undefined"!=typeof process&&"[object process]"===w(process).toLowerCase(),N="undefined"!=typeof process&&"undefined"!=typeof process.env,B={isClass:h,isIdentifier:_,inheritedDataKeys:O,getDataPropertyOrDefault:l,thrower:p,isArray:F.isArray,asArray:I,notEnumerableProp:u,isPrimitive:o,isObject:s,isError:y,canEvaluate:x,errorObj:T,tryCatch:i,inherits:S,withAppended:c,maybeWrapAsError:a,toFastProperties:f,filledRange:d,toString:v,canAttachTrace:b,ensureErrorObject:V,originatesFromRejection:g,markAsOriginatingFromRejection:m,classString:w,copyDescriptors:C,hasDevTools:"undefined"!=typeof chrome&&chrome&&"function"==typeof chrome.loadTimes,isNode:H,hasEnvVariables:N,env:j,global:R,getNativePromise:E,domainBind:k};B.isRecentNode=B.isNode&&function(){var t=process.versions.node.split(".").map(Number);return 0===t[0]&&t[1]>10||t[0]>0}(),B.isNode&&B.toFastProperties(process);try{throw new Error}catch(U){B.lastLineError=U}e.exports=B},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/node_modules/mquery/node_modules/bluebird/js/release/any.js b/node_modules/mquery/node_modules/bluebird/js/release/any.js deleted file mode 100644 index 05a6228ef9c9016f6ee42ec9cb1322e120c1961b..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/any.js +++ /dev/null @@ -1,21 +0,0 @@ -"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/mquery/node_modules/bluebird/js/release/assert.js b/node_modules/mquery/node_modules/bluebird/js/release/assert.js deleted file mode 100644 index 4518231a1b496f306f5406358f82a2a236657462..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/assert.js +++ /dev/null @@ -1,55 +0,0 @@ -"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(Math.max($_len - 2, 0)); 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/mquery/node_modules/bluebird/js/release/async.js b/node_modules/mquery/node_modules/bluebird/js/release/async.js deleted file mode 100644 index 41f665564750a6fc51c07067d759e6940a061f9f..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/async.js +++ /dev/null @@ -1,161 +0,0 @@ -"use strict"; -var firstLineError; -try {throw new Error(); } catch (e) {firstLineError = e;} -var schedule = require("./schedule"); -var Queue = require("./queue"); -var util = require("./util"); - -function Async() { - this._customScheduler = false; - this._isTickUsed = false; - this._lateQueue = new Queue(16); - this._normalQueue = new Queue(16); - this._haveDrainedQueues = false; - this._trampolineEnabled = true; - var self = this; - this.drainQueues = function () { - self._drainQueues(); - }; - this._schedule = schedule; -} - -Async.prototype.setScheduler = function(fn) { - var prev = this._schedule; - this._schedule = fn; - this._customScheduler = true; - return prev; -}; - -Async.prototype.hasCustomScheduler = function() { - return this._customScheduler; -}; - -Async.prototype.enableTrampoline = function() { - this._trampolineEnabled = true; -}; - -Async.prototype.disableTrampolineIfNecessary = function() { - if (util.hasDevTools) { - this._trampolineEnabled = false; - } -}; - -Async.prototype.haveItemsQueued = function () { - return this._isTickUsed || this._haveDrainedQueues; -}; - - -Async.prototype.fatalError = function(e, isNode) { - if (isNode) { - process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + - "\n"); - process.exit(2); - } else { - this.throwLater(e); - } -}; - -Async.prototype.throwLater = function(fn, arg) { - if (arguments.length === 1) { - arg = fn; - fn = function () { throw arg; }; - } - if (typeof setTimeout !== "undefined") { - setTimeout(function() { - fn(arg); - }, 0); - } else try { - this._schedule(function() { - fn(arg); - }); - } catch (e) { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } -}; - -function AsyncInvokeLater(fn, receiver, arg) { - this._lateQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncInvoke(fn, receiver, arg) { - this._normalQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncSettlePromises(promise) { - this._normalQueue._pushOne(promise); - this._queueTick(); -} - -if (!util.hasDevTools) { - Async.prototype.invokeLater = AsyncInvokeLater; - Async.prototype.invoke = AsyncInvoke; - Async.prototype.settlePromises = AsyncSettlePromises; -} else { - Async.prototype.invokeLater = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvokeLater.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - setTimeout(function() { - fn.call(receiver, arg); - }, 100); - }); - } - }; - - Async.prototype.invoke = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvoke.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - fn.call(receiver, arg); - }); - } - }; - - Async.prototype.settlePromises = function(promise) { - if (this._trampolineEnabled) { - AsyncSettlePromises.call(this, promise); - } else { - this._schedule(function() { - promise._settlePromises(); - }); - } - }; -} - -Async.prototype._drainQueue = function(queue) { - while (queue.length() > 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -}; - -Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/bind.js b/node_modules/mquery/node_modules/bluebird/js/release/bind.js deleted file mode 100644 index fc3379db28c259ba329de6617f355225c86e926c..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/bind.js +++ /dev/null @@ -1,67 +0,0 @@ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { -var calledBind = false; -var rejectThis = function(_, e) { - this._reject(e); -}; - -var targetRejected = function(e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); -}; - -var bindingResolved = function(thisArg, context) { - if (((this._bitField & 50397184) === 0)) { - this._resolveCallback(context.target); - } -}; - -var bindingRejected = function(e, context) { - if (!context.promiseRejectionQueued) this._reject(e); -}; - -Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, bindingRejected, undefined, ret, context); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; -}; - -Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~2097152); - } -}; - -Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; -}; - -Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); -}; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/bluebird.js b/node_modules/mquery/node_modules/bluebird/js/release/bluebird.js deleted file mode 100644 index 1c36cf36446be3d393dd705a97f34c992312da07..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/bluebird.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict() { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -var bluebird = require("./promise")(); -bluebird.noConflict = noConflict; -module.exports = bluebird; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/call_get.js b/node_modules/mquery/node_modules/bluebird/js/release/call_get.js deleted file mode 100644 index 0ed7714ac11e0d84a6debb289a6df06b17cac6e1..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/call_get.js +++ /dev/null @@ -1,123 +0,0 @@ -"use strict"; -var cr = Object.create; -if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; -} - -module.exports = function(Promise) { -var util = require("./util"); -var canEvaluate = util.canEvaluate; -var isIdentifier = util.isIdentifier; - -var getMethodCaller; -var getGetter; -if (!false) { -var makeMethodCaller = function (methodName) { - return new Function("ensureMethod", " \n\ - return function(obj) { \n\ - 'use strict' \n\ - var len = this.length; \n\ - ensureMethod(obj, 'methodName'); \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: \n\ - return obj.methodName.apply(obj, this); \n\ - } \n\ - }; \n\ - ".replace(/methodName/g, methodName))(ensureMethod); -}; - -var makeGetter = function (propertyName) { - return new Function("obj", " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace("propertyName", propertyName)); -}; - -var getCompiled = function(name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; -}; - -getMethodCaller = function(name) { - return getCompiled(name, makeMethodCaller, callerCache); -}; - -getGetter = function(name) { - return getCompiled(name, makeGetter, getterCache); -}; -} - -function ensureMethod(obj, methodName) { - var fn; - if (obj != null) fn = obj[methodName]; - if (typeof fn !== "function") { - var message = "Object " + util.classString(obj) + " has no method '" + - util.toString(methodName) + "'"; - throw new Promise.TypeError(message); - } - return fn; -} - -function caller(obj) { - var methodName = this.pop(); - var fn = ensureMethod(obj, methodName); - return fn.apply(obj, this); -} -Promise.prototype.call = function (methodName) { - var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); 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/mquery/node_modules/bluebird/js/release/cancel.js b/node_modules/mquery/node_modules/bluebird/js/release/cancel.js deleted file mode 100644 index 7a12415ee5852ce66e78598d429903addb99cc02..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/cancel.js +++ /dev/null @@ -1,129 +0,0 @@ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = require("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -Promise.prototype["break"] = Promise.prototype.cancel = function() { - if (!debug.cancellation()) return this._warn("cancellation is disabled"); - - var promise = this; - var child = promise; - while (promise._isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } - - var parent = promise._cancellationParent; - if (parent == null || !parent._isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - promise._setWillBeCancelled(); - child = promise; - promise = parent; - } - } -}; - -Promise.prototype._branchHasCancelled = function() { - this._branchesRemainingToCancel--; -}; - -Promise.prototype._enoughBranchesHaveCancelled = function() { - return this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0; -}; - -Promise.prototype._cancelBy = function(canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; - } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; - } - } - return false; -}; - -Promise.prototype._cancelBranched = function() { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } -}; - -Promise.prototype._cancel = function() { - if (!this._isCancellable()) return; - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); -}; - -Promise.prototype._cancelPromises = function() { - if (this._length() > 0) this._settlePromises(); -}; - -Promise.prototype._unsetOnCancel = function() { - this._onCancelField = undefined; -}; - -Promise.prototype._isCancellable = function() { - return this.isPending() && !this._isCancelled(); -}; - -Promise.prototype.isCancellable = function() { - return this.isPending() && !this.isCancelled(); -}; - -Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { - if (util.isArray(onCancelCallback)) { - for (var i = 0; i < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); - } - } - } else { - onCancelCallback._resultCancelled(this); - } - } -}; - -Promise.prototype._invokeOnCancel = function() { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); -}; - -Promise.prototype._invokeInternalOnCancel = function() { - if (this._isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); - } -}; - -Promise.prototype._resultCancelled = function() { - this.cancel(); -}; - -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/catch_filter.js b/node_modules/mquery/node_modules/bluebird/js/release/catch_filter.js deleted file mode 100644 index 0f24ce23eca23ff193a3040d8fdfb394fdb76ccf..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/catch_filter.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = require("./util"); -var getKeys = require("./es5").keys; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } - } - return NEXT_FILTER; - }; -} - -return catchFilter; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/context.js b/node_modules/mquery/node_modules/bluebird/js/release/context.js deleted file mode 100644 index c307414fc627c9a75b95ee2fdad408f9e47d2fa3..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/context.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -module.exports = function(Promise) { -var longStackTraces = false; -var contextStack = []; - -Promise.prototype._promiseCreated = function() {}; -Promise.prototype._pushContext = function() {}; -Promise.prototype._popContext = function() {return null;}; -Promise._peekContext = Promise.prototype._peekContext = function() {}; - -function Context() { - this._trace = new Context.CapturedTrace(peekContext()); -} -Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); - } -}; - -Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; - } - return null; -}; - -function createContext() { - if (longStackTraces) return new Context(); -} - -function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; -} -Context.CapturedTrace = null; -Context.create = createContext; -Context.deactivateLongStackTraces = function() {}; -Context.activateLongStackTraces = function() { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var Promise_promiseCreated = Promise.prototype._promiseCreated; - Context.deactivateLongStackTraces = function() { - Promise.prototype._pushContext = Promise_pushContext; - Promise.prototype._popContext = Promise_popContext; - Promise._peekContext = Promise_PeekContext; - Promise.prototype._peekContext = Promise_peekContext; - Promise.prototype._promiseCreated = Promise_promiseCreated; - longStackTraces = false; - }; - longStackTraces = true; - Promise.prototype._pushContext = Context.prototype._pushContext; - Promise.prototype._popContext = Context.prototype._popContext; - Promise._peekContext = Promise.prototype._peekContext = peekContext; - Promise.prototype._promiseCreated = function() { - var ctx = this._peekContext(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; -}; -return Context; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/debuggability.js b/node_modules/mquery/node_modules/bluebird/js/release/debuggability.js deleted file mode 100644 index 6956804131112fe030ae6b265c68b9215d3049d9..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/debuggability.js +++ /dev/null @@ -1,919 +0,0 @@ -"use strict"; -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = require("./errors").Warning; -var util = require("./util"); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; -var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; -var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; -var stackFramePattern = null; -var formatStack = null; -var indentStackFrames = false; -var printWarning; -var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - (false || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); - -var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); - -var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - -var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - -Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); -}; - -Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; - -Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } -}; - -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); -}; - -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; -}; - -Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; -}; - -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); -}; - -Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -var disableLongStackTraces = function() {}; -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - -var fireDomEvent = (function() { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, - event); - return !util.global.dispatchEvent(domEvent); - }; - } - } catch (e) {} - return function() { - return false; - }; -})(); - -var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function() { - return false; - }; - } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } -})(); - -function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; -} - -var eventToObjectGenerator = { - promiseCreated: generatePromiseLifecycleEventObject, - promiseFulfilled: generatePromiseLifecycleEventObject, - promiseRejected: generatePromiseLifecycleEventObject, - promiseResolved: generatePromiseLifecycleEventObject, - promiseCancelled: generatePromiseLifecycleEventObject, - promiseChained: function(name, promise, child) { - return {promise: promise, child: child}; - }, - warning: function(name, warning) { - return {warning: warning}; - }, - unhandledRejection: function (name, reason, promise) { - return {reason: reason, promise: promise}; - }, - rejectionHandled: generatePromiseLifecycleEventObject -}; - -var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; - } - - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; - } - - return domEventFired || globalEventFired; -}; - -Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - - if (util.isObject(warningsOption)) { - if ("wForgottenReturn" in warningsOption) { - wForgottenReturn = !!warningsOption.wForgottenReturn; - } - } - } - if ("cancellation" in opts && opts.cancellation && !config.cancellation) { - if (async.haveItemsQueued()) { - throw new Error( - "cannot enable cancellation after promises are in use"); - } - Promise.prototype._clearCancellationData = - cancellationClearCancellationData; - Promise.prototype._propagateFrom = cancellationPropagateFrom; - Promise.prototype._onCancel = cancellationOnCancel; - Promise.prototype._setOnCancel = cancellationSetOnCancel; - Promise.prototype._attachCancellationCallback = - cancellationAttachCancellationCallback; - Promise.prototype._execute = cancellationExecute; - propagateFromFunction = cancellationPropagateFrom; - config.cancellation = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } - return Promise; -}; - -function defaultFireEvent() { return false; } - -Promise.prototype._fireEvent = defaultFireEvent; -Promise.prototype._execute = function(executor, resolve, reject) { - try { - executor(resolve, reject); - } catch (e) { - return e; - } -}; -Promise.prototype._onCancel = function () {}; -Promise.prototype._setOnCancel = function (handler) { ; }; -Promise.prototype._attachCancellationCallback = function(onCancel) { - ; -}; -Promise.prototype._captureStackTrace = function () {}; -Promise.prototype._attachExtraTrace = function () {}; -Promise.prototype._clearCancellationData = function() {}; -Promise.prototype._propagateFrom = function (parent, flags) { - ; - ; -}; - -function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - throw new TypeError("onCancel must be a function, got: " + - util.toString(onCancel)); - } - promise._attachCancellationCallback(onCancel); - }); - } catch (e) { - return e; - } -} - -function cancellationAttachCancellationCallback(onCancel) { - if (!this._isCancellable()) return this; - - var previousOnCancel = this._onCancel(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); - } -} - -function cancellationOnCancel() { - return this._onCancelField; -} - -function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; -} - -function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; -} - -function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} - -function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} -var propagateFromFunction = bindingPropagateFrom; - -function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; -} - -function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); -} - -function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = parseStackAndMessage(error); - util.notEnumerableProp(error, "stack", - parsed.message + "\n" + parsed.stack.join("\n")); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } -} - -function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = "at " + lineMatches[1] + - ":" + lineMatches[2] + ":" + lineMatches[3] + " "; - } - break; - } - } - - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { - - if (traceLines[i] === firstUserLine) { - if (i > 0) { - creatorLine = "\n" + traceLines[i - 1]; - } - break; - } - } - - } - } - var msg = "a promise was created in a " + name + - "handler " + handlerLine + "but was not returned from it, " + - "see http://goo.gl/rRqMUw" + - creatorLine; - promise._warn(msg, true, promiseCreated); - } -} - -function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); -} - -function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - if (shouldUseOwnTrace) { - promise._attachExtraTrace(warning); - } else if (config.longStackTraces && (ctx = Promise._peekContext())) { - ctx.attachExtraTrace(warning); - } else { - var parsed = parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } - - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } -} - -function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); -} - -function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; - } - } -} - -function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } - - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } -} - -function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; -} - -function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0 && error.name != "SyntaxError") { - stack = stack.slice(i); - } - return stack; -} - -function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: error.name == "SyntaxError" ? stack : cleanStack(stack) - }; -} - -function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -} - -function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } - - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } -} - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? obj.toString() : util.toString(obj); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; -} - -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } -} - -function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; -} - -function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); -} -util.inherits(CapturedTrace, Error); -Context.CapturedTrace = CapturedTrace; - -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } -}; - -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; - } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); - util.notEnumerableProp(error, "__stackCleaned__", true); -}; - -var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } - - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } - - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - return null; - -})([]); - -if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; - } -} - -var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - longStackTraces: function() { - return config.longStackTraces; - }, - warnings: function() { - return config.warnings; - }, - cancellation: function() { - return config.cancellation; - }, - monitoring: function() { - return config.monitoring; - }, - propagateFromFunction: function() { - return propagateFromFunction; - }, - boundValueFunction: function() { - return boundValueFunction; - }, - checkForgottenReturns: checkForgottenReturns, - setBounds: setBounds, - warn: warn, - deprecated: deprecated, - CapturedTrace: CapturedTrace, - fireDomEvent: fireDomEvent, - fireGlobalEvent: fireGlobalEvent -}; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/direct_resolve.js b/node_modules/mquery/node_modules/bluebird/js/release/direct_resolve.js deleted file mode 100644 index a89029826142e8fe632f6dc1192788b737b4781a..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/direct_resolve.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -module.exports = function(Promise) { -function returner() { - return this.value; -} -function thrower() { - throw this.reason; -} - -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); -}; - -Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } -}; - -Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } -}; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/each.js b/node_modules/mquery/node_modules/bluebird/js/release/each.js deleted file mode 100644 index e4f3d05ba3477be74d89cbf092523cb2d6dd900f..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/each.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; -var PromiseAll = Promise.all; - -function promiseAllThis() { - return PromiseAll(this); -} - -function PromiseMapSeries(promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, INTERNAL); -} - -Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, this, undefined); -}; - -Promise.prototype.mapSeries = function (fn) { - return PromiseReduce(this, fn, INTERNAL, INTERNAL); -}; - -Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, promises, undefined); -}; - -Promise.mapSeries = PromiseMapSeries; -}; - diff --git a/node_modules/mquery/node_modules/bluebird/js/release/errors.js b/node_modules/mquery/node_modules/bluebird/js/release/errors.js deleted file mode 100644 index f62f323eb8ffd6c036c4dfd2ba039ed471bd25fd..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/errors.js +++ /dev/null @@ -1,116 +0,0 @@ -"use strict"; -var es5 = require("./es5"); -var Objectfreeze = es5.freeze; -var util = require("./util"); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; -} - -var _TypeError, _RangeError; -var Warning = subError("Warning", "warning"); -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); -} - -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} - -es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true -}); -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; - -function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - -} -inherits(OperationalError, Error); - -var errorTypes = Error["__BluebirdErrorTypes__"]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false - }); -} - -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/mquery/node_modules/bluebird/js/release/es5.js b/node_modules/mquery/node_modules/bluebird/js/release/es5.js deleted file mode 100644 index ea41d5a566921d91aa77ea549d569a96782a4bfc..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/es5.js +++ /dev/null @@ -1,80 +0,0 @@ -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/mquery/node_modules/bluebird/js/release/filter.js b/node_modules/mquery/node_modules/bluebird/js/release/filter.js deleted file mode 100644 index ed57bf0159212ea42c9c8b76f07a2f3dac9f36cb..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/filter.js +++ /dev/null @@ -1,12 +0,0 @@ -"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/mquery/node_modules/bluebird/js/release/finally.js b/node_modules/mquery/node_modules/bluebird/js/release/finally.js deleted file mode 100644 index d57444bed4fa8e8703ba5f234882f9a3adc94406..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/finally.js +++ /dev/null @@ -1,146 +0,0 @@ -"use strict"; -module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { -var util = require("./util"); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; -var catchFilter = require("./catch_filter")(NEXT_FILTER); - -function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; -} - -PassThroughHandlerContext.prototype.isFinallyHandler = function() { - return this.type === 0; -}; - -function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; -} - -FinallyHandlerCancelReaction.prototype._resultCancelled = function() { - checkCancel(this.finallyHandler); -}; - -function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; -} - -function succeed() { - return finallyHandler.call(this, this.promise._target()._settledValue()); -} -function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; -} -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret === NEXT_FILTER) { - return ret; - } else if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise._isCancelled()) { - var reason = - new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this)); - } - } - return maybePromise._then( - succeed, fail, undefined, this, undefined); - } - } - } - - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } -} - -Promise.prototype._passThrough = function(handler, type, success, fail) { - if (typeof handler !== "function") return this.then(); - return this._then(success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined); -}; - -Promise.prototype.lastly = -Promise.prototype["finally"] = function (handler) { - return this._passThrough(handler, - 0, - finallyHandler, - finallyHandler); -}; - - -Promise.prototype.tap = function (handler) { - return this._passThrough(handler, 1, finallyHandler); -}; - -Promise.prototype.tapCatch = function (handlerOrPredicate) { - var len = arguments.length; - if(len === 1) { - return this._passThrough(handlerOrPredicate, - 1, - undefined, - finallyHandler); - } else { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return Promise.reject(new TypeError( - "tapCatch statement predicate: " - + "expecting an object but got " + util.classString(item) - )); - } - } - catchInstances.length = j; - var handler = arguments[i]; - return this._passThrough(catchFilter(catchInstances, handler, this), - 1, - undefined, - finallyHandler); - } - -}; - -return PassThroughHandlerContext; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/generators.js b/node_modules/mquery/node_modules/bluebird/js/release/generators.js deleted file mode 100644 index 500c280c0b075932e6a6dadf003ed5728a51b3a4..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/generators.js +++ /dev/null @@ -1,223 +0,0 @@ -"use strict"; -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { -var errors = require("./errors"); -var TypeError = errors.TypeError; -var util = require("./util"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - for (var i = 0; i < yieldHandlers.length; ++i) { - traceParent._pushContext(); - var result = tryCatch(yieldHandlers[i])(value); - traceParent._popContext(); - if (result === errorObj) { - traceParent._pushContext(); - var ret = Promise.reject(errorObj.e); - traceParent._popContext(); - return ret; - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { - if (debug.cancellation()) { - var internal = new Promise(INTERNAL); - var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); - this._promise = internal.lastly(function() { - return _finallyPromise; - }); - internal._captureStackTrace(); - internal._setOnCancel(this); - } else { - 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; - this._yieldedPromise = null; - this._cancellationPhase = false; -} -util.inherits(PromiseSpawn, Proxyable); - -PromiseSpawn.prototype._isResolved = function() { - return this._promise === null; -}; - -PromiseSpawn.prototype._cleanup = function() { - this._promise = this._generator = null; - if (debug.cancellation() && this._finallyPromise !== null) { - this._finallyPromise._fulfill(); - this._finallyPromise = null; - } -}; - -PromiseSpawn.prototype._promiseCancelled = function() { - if (this._isResolved()) return; - var implementsReturn = typeof this._generator["return"] !== "undefined"; - - var result; - if (!implementsReturn) { - var reason = new Promise.CancellationError( - "generator .return() sentinel"); - Promise.coroutine.returnSentinel = reason; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - result = tryCatch(this._generator["throw"]).call(this._generator, - reason); - this._promise._popContext(); - } else { - this._promise._pushContext(); - result = tryCatch(this._generator["return"]).call(this._generator, - undefined); - this._promise._popContext(); - } - this._cancellationPhase = true; - this._yieldedPromise = null; - this._continue(result); -}; - -PromiseSpawn.prototype._promiseFulfilled = function(value) { - this._yieldedPromise = null; - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call(this._generator, value); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._promiseRejected = function(reason) { - this._yieldedPromise = null; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]) - .call(this._generator, reason); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._resultCancelled = function() { - if (this._yieldedPromise instanceof Promise) { - var promise = this._yieldedPromise; - this._yieldedPromise = null; - promise.cancel(); - } -}; - -PromiseSpawn.prototype.promise = function () { - return this._promise; -}; - -PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = undefined; - this._promiseFulfilled(undefined); -}; - -PromiseSpawn.prototype._continue = function (result) { - var promise = this._promise; - if (result === errorObj) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._rejectCallback(result.e, false); - } - } - - var value = result.value; - if (result.done === true) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._resolveCallback(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, - this._yieldHandlers, - this._promise); - if (maybePromise === null) { - this._promiseRejected( - new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + - "From coroutine:\u000a" + - this._stack.split("\n").slice(1, -7).join("\n") - ) - ); - return; - } - } - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - this._yieldedPromise = maybePromise; - maybePromise._proxy(this, null); - } else if (((bitField & 33554432) !== 0)) { - Promise._async.invoke( - this._promiseFulfilled, this, maybePromise._value() - ); - } else if (((bitField & 16777216) !== 0)) { - Promise._async.invoke( - this._promiseRejected, this, maybePromise._reason() - ); - } else { - this._promiseCancelled(); - } - } -}; - -Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - var stack = new Error().stack; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, - stack); - var ret = spawn.promise(); - spawn._generator = generator; - spawn._promiseFulfilled(undefined); - return ret; - }; -}; - -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - yieldHandlers.push(fn); -}; - -Promise.spawn = function (generatorFunction) { - debug.deprecated("Promise.spawn()", "Promise.coroutine()"); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/join.js b/node_modules/mquery/node_modules/bluebird/js/release/join.js deleted file mode 100644 index 4945e3f782268623a39b720d0da32ea6d31456b5..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/join.js +++ /dev/null @@ -1,168 +0,0 @@ -"use strict"; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { -var util = require("./util"); -var canEvaluate = util.canEvaluate; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var reject; - -if (!false) { -if (canEvaluate) { - var thenCallback = function(i) { - return new Function("value", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace(/Index/g, i)); - }; - - var promiseSetter = function(i) { - return new Function("promise", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = promise; \n\ - ".replace(/Index/g, i)); - }; - - var generateHolderClass = function(total) { - var props = new Array(total); - for (var i = 0; i < props.length; ++i) { - props[i] = "this.p" + (i+1); - } - var assignment = props.join(" = ") + " = null;"; - var cancellationCode= "var promise;\n" + props.map(function(prop) { - return " \n\ - promise = " + prop + "; \n\ - if (promise instanceof Promise) { \n\ - promise.cancel(); \n\ - } \n\ - "; - }).join("\n"); - var passedArguments = props.join(", "); - var name = "Holder$" + total; - - - var code = "return function(tryCatch, errorObj, Promise, async) { \n\ - 'use strict'; \n\ - function [TheName](fn) { \n\ - [TheProperties] \n\ - this.fn = fn; \n\ - this.asyncNeeded = true; \n\ - this.now = 0; \n\ - } \n\ - \n\ - [TheName].prototype._callFunction = function(promise) { \n\ - promise._pushContext(); \n\ - var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ - promise._popContext(); \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(ret.e, false); \n\ - } else { \n\ - promise._resolveCallback(ret); \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype.checkFulfillment = function(promise) { \n\ - var now = ++this.now; \n\ - if (now === [TheTotal]) { \n\ - if (this.asyncNeeded) { \n\ - async.invoke(this._callFunction, this, promise); \n\ - } else { \n\ - this._callFunction(promise); \n\ - } \n\ - \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype._resultCancelled = function() { \n\ - [CancellationCode] \n\ - }; \n\ - \n\ - return [TheName]; \n\ - }(tryCatch, errorObj, Promise, async); \n\ - "; - - code = code.replace(/\[TheName\]/g, name) - .replace(/\[TheTotal\]/g, total) - .replace(/\[ThePassedArguments\]/g, passedArguments) - .replace(/\[TheProperties\]/g, assignment) - .replace(/\[CancellationCode\]/g, cancellationCode); - - return new Function("tryCatch", "errorObj", "Promise", "async", code) - (tryCatch, errorObj, Promise, async); - }; - - var holderClasses = []; - var thenCallbacks = []; - var promiseSetters = []; - - for (var i = 0; i < 8; ++i) { - holderClasses.push(generateHolderClass(i + 1)); - thenCallbacks.push(thenCallback(i + 1)); - promiseSetters.push(promiseSetter(i + 1)); - } - - reject = function (reason) { - this._reject(reason); - }; -}} - -Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (!false) { - if (last <= 8 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var HolderClass = holderClasses[last - 1]; - var holder = new HolderClass(fn); - var callbacks = thenCallbacks; - - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], ret); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - maybePromise._then(callbacks[i], reject, - undefined, ret, holder); - promiseSetters[i](maybePromise, holder); - holder.asyncNeeded = false; - } else if (((bitField & 33554432) !== 0)) { - callbacks[i].call(ret, - maybePromise._value(), holder); - } else if (((bitField & 16777216) !== 0)) { - ret._reject(maybePromise._reason()); - } else { - ret._cancel(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - - if (!ret._isFateSealed()) { - if (holder.asyncNeeded) { - var domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, holder.fn); - } - } - ret._setAsyncGuaranteed(); - ret._setOnCancel(holder); - } - return ret; - } - } - } - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; - -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/map.js b/node_modules/mquery/node_modules/bluebird/js/release/map.js deleted file mode 100644 index 976f15ef2930bd14e7fceadab4fc33adb0a6118c..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/map.js +++ /dev/null @@ -1,168 +0,0 @@ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = require("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var domain = getDomain(); - this._callback = domain === null ? fn : util.domainBind(domain, fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); -} -util.inherits(MappingPromiseArray, PromiseArray); - -MappingPromiseArray.prototype._asyncInit = function() { - 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 (index < 0) { - index = (index * -1) - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; - - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } - - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if (((bitField & 33554432) !== 0)) { - ret = maybePromise._value(); - } else if (((bitField & 16777216) !== 0)) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; - } - return false; -}; - -MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } -}; - -MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); -}; - -MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; -}; - -function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError("'concurrency' must be a number but it is " + - util.classString(options.concurrency))); - } - limit = options.concurrency; - } else { - return Promise.reject(new TypeError( - "options argument must be an object but it is " + - util.classString(options))); - } - } - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter).promise(); -} - -Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); -}; - -Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); -}; - - -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/method.js b/node_modules/mquery/node_modules/bluebird/js/release/method.js deleted file mode 100644 index ce9e4db7edf42aa9e2ac12c89a854e89052b978c..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/method.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = require("./util"); -var tryCatch = util.tryCatch; - -Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.method", ret); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var ctx = arguments[2]; - value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) - : tryCatch(fn).call(ctx, arg); - } else { - value = tryCatch(fn)(); - } - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.try", ret); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); - } -}; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/nodeback.js b/node_modules/mquery/node_modules/bluebird/js/release/nodeback.js deleted file mode 100644 index 71e69ebdbec9478c85e865dbce01b385de38f4de..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/nodeback.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; -var util = require("./util"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = require("./errors"); -var OperationalError = errors.OperationalError; -var es5 = require("./es5"); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -var rErrorKey = /^(?:name|message|stack|cause)$/; -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - util.markAsOriginatingFromRejection(obj); - return obj; -} - -function nodebackForPromise(promise, multiArgs) { - return function(err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); - } else { - var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; - promise._fulfill(args); - } - promise = null; - }; -} - -module.exports = nodebackForPromise; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/nodeify.js b/node_modules/mquery/node_modules/bluebird/js/release/nodeify.js deleted file mode 100644 index ce2b19004e5bae49f986e9041cd47dab58775d30..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/nodeify.js +++ /dev/null @@ -1,58 +0,0 @@ -"use strict"; -module.exports = function(Promise) { -var util = require("./util"); -var async = Promise._async; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = - tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundValue(); - var ret = val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} -function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var newReason = new Error(reason + ""); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundValue(), reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, - options) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then( - adapter, - errorAdapter, - undefined, - this, - nodeback - ); - } - return this; -}; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/promise.js b/node_modules/mquery/node_modules/bluebird/js/release/promise.js deleted file mode 100644 index f4a641c3360c24119a356a8a4c8da6e259440b41..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/promise.js +++ /dev/null @@ -1,775 +0,0 @@ -"use strict"; -module.exports = function() { -var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var reflectHandler = function() { - return new Promise.PromiseInspection(this._target()); -}; -var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); -}; -function Proxyable() {} -var UNDEFINED_BINDING = {}; -var util = require("./util"); - -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { - return null; - }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); - -var es5 = require("./es5"); -var Async = require("./async"); -var async = new Async(); -es5.defineProperty(Promise, "_async", {value: async}); -var errors = require("./errors"); -var TypeError = Promise.TypeError = errors.TypeError; -Promise.RangeError = errors.RangeError; -var CancellationError = Promise.CancellationError = errors.CancellationError; -Promise.TimeoutError = errors.TimeoutError; -Promise.OperationalError = errors.OperationalError; -Promise.RejectionError = errors.OperationalError; -Promise.AggregateError = errors.AggregateError; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {}; -var tryConvertToPromise = require("./thenables")(Promise, INTERNAL); -var PromiseArray = - require("./promise_array")(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); -var Context = require("./context")(Promise); - /*jshint unused:false*/ -var createContext = Context.create; -var debug = require("./debuggability")(Promise, Context); -var CapturedTrace = debug.CapturedTrace; -var PassThroughHandlerContext = - require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); -var catchFilter = require("./catch_filter")(NEXT_FILTER); -var nodebackForPromise = require("./nodeback"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (self == null || self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - -} - -function Promise(executor) { - if (executor !== INTERNAL) { - check(this, executor); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - this._resolveFromExecutor(executor); - this._promiseCreated(); - this._fireEvent("promiseCreated", this); -} - -Promise.prototype.toString = function () { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection("Catch statement predicate: " + - "expecting an object but got " + util.classString(item)); - } - } - catchInstances.length = j; - fn = arguments[i]; - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); -}; - -Promise.prototype.reflect = function () { - return this._then(reflectHandler, - reflectHandler, undefined, this, undefined); -}; - -Promise.prototype.then = function (didFulfill, didReject) { - if (debug.warnings() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then(didFulfill, didReject, undefined, undefined, undefined); -}; - -Promise.prototype.done = function (didFulfill, didReject) { - var promise = - this._then(didFulfill, didReject, undefined, undefined, undefined); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); -}; - -Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return new PromiseArray(this).promise(); -}; - -Promise.prototype.error = function (fn) { - return this.caught(util.originatesFromRejection, fn); -}; - -Promise.getNewLibraryCopy = module.exports; - -Promise.is = function (val) { - return val instanceof Promise; -}; - -Promise.fromNode = Promise.fromCallback = function(fn) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs - : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); - } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - return async.setScheduler(fn); -}; - -Promise.prototype._then = function ( - didFulfill, - didReject, - _, receiver, - internalData -) { - var haveInternalData = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && - ((this._bitField & 2097152) !== 0)) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } - - var domain = getDomain(); - if (!((bitField & 50397184) === 0)) { - var handler, value, settler = target._settlePromiseCtx; - if (((bitField & 33554432) !== 0)) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if (((bitField & 16777216) !== 0)) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); - } - - return promise; -}; - -Promise.prototype._length = function () { - return this._bitField & 65535; -}; - -Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; -}; - -Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; -}; - -Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | - (len & 65535); -}; - -Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); -}; - -Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); -}; - -Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); -}; - -Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; -}; - -Promise.prototype._unsetCancelled = function() { - this._bitField = this._bitField & (~65536); -}; - -Promise.prototype._setCancelled = function() { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); -}; - -Promise.prototype._setWillBeCancelled = function() { - this._bitField = this._bitField | 8388608; -}; - -Promise.prototype._setAsyncGuaranteed = function() { - if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; -}; - -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[ - index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); - } - return ret; -}; - -Promise.prototype._promiseAt = function (index) { - return this[ - index * 4 - 4 + 2]; -}; - -Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[ - index * 4 - 4 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = function (index) { - return this[ - index * 4 - 4 + 1]; -}; - -Promise.prototype._boundValue = function() {}; - -Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._addCallbacks = function ( - fulfill, - reject, - promise, - receiver, - domain -) { - var index = this._length(); - - if (index >= 65535 - 4) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, reject); - } - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); -}; - -Promise.prototype._resolveCallback = function(value, shouldBind) { - if (((this._bitField & 117506048) !== 0)) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); - - if (shouldBind) this._propagateFrom(maybePromise, 2); - - var promise = maybePromise._target(); - - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } - - var bitField = promise._bitField; - if (((bitField & 50397184) === 0)) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(promise); - } else if (((bitField & 33554432) !== 0)) { - this._fulfill(promise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); - } -}; - -Promise.prototype._rejectCallback = -function(reason, synchronous, ignoreNonErrorWarnings) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); - } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); -}; - -Promise.prototype._resolveFromExecutor = function (executor) { - if (executor === INTERNAL) return; - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute(executor, function(value) { - promise._resolveCallback(value); - }, function (reason) { - promise._rejectCallback(reason, synchronous); - }); - synchronous = false; - this._popContext(); - - if (r !== undefined) { - promise._rejectCallback(r, true); - } -}; - -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - var bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError("cannot .spread() a non-array: " + - util.classString(value)); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } -}; - -Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; -}; - -Promise.prototype._followee = function() { - return this._rejectionHandler0; -}; - -Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; -}; - -Promise.prototype._settlePromise = function(promise, handler, receiver, value) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = ((bitField & 134217728) !== 0); - if (((bitField & 65536) !== 0)) { - if (isPromise) promise._invokeInternalOnCancel(); - - if (receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler()) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if (((bitField & 33554432) !== 0)) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if (((bitField & 33554432) !== 0)) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } -}; - -Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } -}; - -Promise.prototype._settlePromiseCtx = function(ctx) { - this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); -}; - -Promise.prototype._settlePromise0 = function(handler, value, bitField) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); -}; - -Promise.prototype._clearCallbackDataAtIndex = function(index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = undefined; -}; - -Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; - - if ((bitField & 65535) > 0) { - if (((bitField & 134217728) !== 0)) { - this._settlePromises(); - } else { - async.settlePromises(this); - } - } -}; - -Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; - - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } - - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } -}; - -Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } -}; - -Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = (bitField & 65535); - - if (len > 0) { - if (((bitField & 16842752) !== 0)) { - var reason = this._fulfillmentHandler0; - this._settlePromise0(this._rejectionHandler0, reason, bitField); - this._rejectPromises(len, reason); - } else { - var value = this._rejectionHandler0; - this._settlePromise0(this._fulfillmentHandler0, value, bitField); - this._fulfillPromises(len, value); - } - this._setLength(0); - } - this._clearCancellationData(); -}; - -Promise.prototype._settledValue = function() { - var bitField = this._bitField; - if (((bitField & 33554432) !== 0)) { - return this._rejectionHandler0; - } else if (((bitField & 16777216) !== 0)) { - return this._fulfillmentHandler0; - } -}; - -function deferResolve(v) {this.promise._resolveCallback(v);} -function deferReject(v) {this.promise._rejectCallback(v, false);} - -Promise.defer = Promise.pending = function() { - debug.deprecated("Promise.defer", "new Promise"); - var promise = new Promise(INTERNAL); - return { - promise: promise, - resolve: deferResolve, - reject: deferReject - }; -}; - -util.notEnumerableProp(Promise, - "_makeSelfResolutionError", - makeSelfResolutionError); - -require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, - debug); -require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); -require("./cancel")(Promise, PromiseArray, apiRejection, debug); -require("./direct_resolve")(Promise); -require("./synchronous_inspection")(Promise); -require("./join")( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); -Promise.Promise = Promise; -Promise.version = "3.5.1"; -require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -require('./call_get.js')(Promise); -require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -require('./timers.js')(Promise, INTERNAL, debug); -require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); -require('./nodeify.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, debug); -require('./settle.js')(Promise, PromiseArray, debug); -require('./some.js')(Promise, PromiseArray, apiRejection); -require('./filter.js')(Promise, INTERNAL); -require('./each.js')(Promise, INTERNAL); -require('./any.js')(Promise); - - util.toFastProperties(Promise); - util.toFastProperties(Promise.prototype); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return Promise; - -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/promise_array.js b/node_modules/mquery/node_modules/bluebird/js/release/promise_array.js deleted file mode 100644 index 0fb303eb0d3dc147baf11edc756616c955ed2a36..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/promise_array.js +++ /dev/null @@ -1,185 +0,0 @@ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = require("./util"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - case -6: return new Map(); - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -util.inherits(PromiseArray, Proxyable); - -PromiseArray.prototype.length = function () { - return this._length; -}; - -PromiseArray.prototype.promise = function () { - return this._promise; -}; - -PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - var values = tryConvertToPromise(this._values, this._promise); - if (values instanceof Promise) { - values = values._target(); - var bitField = values._bitField; - ; - this._values = values; - - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - this._iterate(values); -}; - -PromiseArray.prototype._iterate = function(values) { - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() ? new Array(len) : this._values; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); - - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } - - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); -}; - -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); -}; - -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; -}; - -PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; -}; - -PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } -}; - -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; - -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; - -return PromiseArray; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/promisify.js b/node_modules/mquery/node_modules/bluebird/js/release/promisify.js deleted file mode 100644 index aa98e5bde1ca973ff24ecfe6bc7ad305246d7415..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/promisify.js +++ /dev/null @@ -1,314 +0,0 @@ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = require("./util"); -var nodebackForPromise = require("./nodeback"); -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var TypeError = require("./errors").TypeError; -var defaultSuffix = "Async"; -var defaultPromisified = {__isPromisified__: true}; -var noCopyProps = [ - "arity", "length", - "name", - "arguments", - "caller", - "callee", - "prototype", - "__isPromisified__" -]; -var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); - -var defaultFilter = function(name) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - name !== "constructor"; -}; - -function propsFilter(key) { - return !noCopyPropsPattern.test(key); -} - -function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } -} - -function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; -} -function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" - .replace("%s", suffix)); - } - } - } - } -} - -function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - var passesDefaultFilter = filter === defaultFilter - ? true : defaultFilter(key, value, obj); - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj, passesDefaultFilter)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; -} - -var escapeIdentRegex = function(str) { - return str.replace(/([$])/, "\\$"); -}; - -var makeNodePromisifiedEval; -if (!false) { -var switchCaseArgumentOrder = function(likelyArgumentCount) { - var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 3); - for(var i = likelyArgumentCount - 1; i >= min; --i) { - ret.push(i); - } - for(var i = likelyArgumentCount + 1; i <= 3; ++i) { - ret.push(i); - } - return ret; -}; - -var argumentSequence = function(argumentCount) { - return util.filledRange(argumentCount, "_arg", ""); -}; - -var parameterDeclaration = function(parameterCount) { - return util.filledRange( - Math.max(parameterCount, 3), "_arg", ""); -}; - -var parameterCount = function(fn) { - if (typeof fn.length === "number") { - return Math.max(Math.min(fn.length, 1023 + 1), 0); - } - return 0; -}; - -makeNodePromisifiedEval = -function(callback, receiver, originalName, fn, _, multiArgs) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var shouldProxyThis = typeof callback === "string" || receiver === THIS; - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (shouldProxyThis) { - ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; - } else { - ret = receiver === undefined - ? "ret = callback({{args}}, nodeback); break;\n" - : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; - } - return ret.replace("{{args}}", args).replace(", ", comma); - } - - function generateArgumentSwitchCase() { - var ret = ""; - for (var i = 0; i < argumentOrder.length; ++i) { - ret += "case " + argumentOrder[i] +":" + - generateCallForArgumentCount(argumentOrder[i]); - } - - ret += " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = nodeback; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace("[CodeForCall]", (shouldProxyThis - ? "ret = callback.apply(this, args);\n" - : "ret = callback.apply(receiver, args);\n")); - return ret; - } - - var getFunctionCode = typeof callback === "string" - ? ("this != null ? this['"+callback+"'] : fn") - : "fn"; - var body = "'use strict'; \n\ - var ret = function (Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._captureStackTrace(); \n\ - var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ - var ret; \n\ - var callback = tryCatch([GetFunctionCode]); \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ - } \n\ - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ - return promise; \n\ - }; \n\ - notEnumerableProp(ret, '__isPromisified__', true); \n\ - return ret; \n\ - ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) - .replace("[GetFunctionCode]", getFunctionCode); - body = body.replace("Parameters", parameterDeclaration(newParameterCount)); - return new Function("Promise", - "fn", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "tryCatch", - "errorObj", - "notEnumerableProp", - "INTERNAL", - body)( - Promise, - fn, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - util.tryCatch, - util.errorObj, - util.notEnumerableProp, - INTERNAL); -}; -} - -function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { - var defaultThis = (function() {return this;})(); - var method = callback; - if (typeof method === "string") { - callback = fn; - } - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - var promise = new Promise(INTERNAL); - promise._captureStackTrace(); - var cb = typeof method === "string" && this !== defaultThis - ? this[method] : callback; - var fn = nodebackForPromise(promise, multiArgs); - try { - cb.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - promise._rejectCallback(maybeWrapAsError(e), true, true); - } - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); - return promise; - } - util.notEnumerableProp(promisified, "__isPromisified__", true); - return promisified; -} - -var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - -function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - if (promisifier === makeNodePromisified) { - obj[promisifiedKey] = - makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); - } else { - var promisified = promisifier(fn, function() { - return makeNodePromisified(key, THIS, key, - fn, suffix, multiArgs); - }); - util.notEnumerableProp(promisified, "__isPromisified__", true); - obj[promisifiedKey] = promisified; - } - } - util.toFastProperties(obj); - return obj; -} - -function promisify(callback, receiver, multiArgs) { - return makeNodePromisified(callback, receiver, undefined, - callback, null, multiArgs); -} - -Promise.promisify = function (fn, options) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - if (isPromisified(fn)) { - return fn; - } - options = Object(options); - var receiver = options.context === undefined ? THIS : options.context; - var multiArgs = !!options.multiArgs; - var ret = promisify(fn, receiver, multiArgs); - util.copyDescriptors(fn, ret, propsFilter); - return ret; -}; - -Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - options = Object(options); - var multiArgs = !!options.multiArgs; - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - - var keys = util.inheritedDataKeys(target); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier, - multiArgs); - promisifyAll(value, suffix, filter, promisifier, multiArgs); - } - } - - return promisifyAll(target, suffix, filter, promisifier, multiArgs); -}; -}; - diff --git a/node_modules/mquery/node_modules/bluebird/js/release/props.js b/node_modules/mquery/node_modules/bluebird/js/release/props.js deleted file mode 100644 index 6a34aaf55648b933bfc2fd9363814cc7f765998d..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/props.js +++ /dev/null @@ -1,118 +0,0 @@ -"use strict"; -module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = require("./util"); -var isObject = util.isObject; -var es5 = require("./es5"); -var Es6Map; -if (typeof Map === "function") Es6Map = Map; - -var mapToEntries = (function() { - var index = 0; - var size = 0; - - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; - } - - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; -})(); - -var entriesToMap = function(entries) { - var ret = new Es6Map(); - var length = entries.length / 2 | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); - } - return ret; -}; - -function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; - } - } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, isMap ? -6 : -3); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = function () {}; - -PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - } - this._resolve(val); - return true; - } - return false; -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; -}; - -function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; -} - -Promise.prototype.props = function () { - return props(this); -}; - -Promise.props = function (promises) { - return props(promises); -}; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/queue.js b/node_modules/mquery/node_modules/bluebird/js/release/queue.js deleted file mode 100644 index ffd36fda1fb51f855c24ae218b52dd430bef0380..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/queue.js +++ /dev/null @@ -1,73 +0,0 @@ -"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.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/mquery/node_modules/bluebird/js/release/race.js b/node_modules/mquery/node_modules/bluebird/js/release/race.js deleted file mode 100644 index b862f46d64ea047159d7df0370998dfc14b091d5..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/race.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; -module.exports = function( - Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = require("./util"); - -var raceLater = function (promise) { - return promise.then(function(array) { - return race(array, promise); - }); -}; - -function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else { - promises = util.asArray(promises); - if (promises === null) - return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); - } - - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 3); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === undefined && !(i in promises)) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; -} - -Promise.race = function (promises) { - return race(promises, undefined); -}; - -Promise.prototype.race = function () { - return race(this, undefined); -}; - -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/reduce.js b/node_modules/mquery/node_modules/bluebird/js/release/reduce.js deleted file mode 100644 index 26e2b1a970618468e9faedeb38cb543cc4e4db23..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/reduce.js +++ /dev/null @@ -1,172 +0,0 @@ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = require("./util"); -var tryCatch = util.tryCatch; - -function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, fn); - if (initialValue !== undefined) { - initialValue = Promise.resolve(initialValue); - initialValue._attachCancellationCallback(this); - } - this._initialValue = initialValue; - this._currentCancellable = null; - if(_each === INTERNAL) { - this._eachValues = Array(this._length); - } else if (_each === 0) { - this._eachValues = null; - } else { - this._eachValues = undefined; - } - this._promise._captureStackTrace(); - this._init$(undefined, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && - this._eachValues !== null && - accum !== INTERNAL) { - this._eachValues.push(accum); - } -}; - -ReductionPromiseArray.prototype._eachComplete = function(value) { - if (this._eachValues !== null) { - this._eachValues.push(value); - } - return this._eachValues; -}; - -ReductionPromiseArray.prototype._init = function() {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = function() { - this._resolve(this._eachValues !== undefined ? this._eachValues - : this._initialValue); -}; - -ReductionPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -ReductionPromiseArray.prototype._resolve = function(value) { - this._promise._resolveCallback(value); - this._values = null; -}; - -ReductionPromiseArray.prototype._resultCancelled = function(sender) { - if (sender === this._initialValue) return this._cancel(); - if (this._isResolved()) return; - this._resultCancelled$(); - if (this._currentCancellable instanceof Promise) { - this._currentCancellable.cancel(); - } - if (this._initialValue instanceof Promise) { - this._initialValue.cancel(); - } -}; - -ReductionPromiseArray.prototype._iterate = function (values) { - this._values = values; - var value; - var i; - var length = values.length; - if (this._initialValue !== undefined) { - value = this._initialValue; - i = 0; - } else { - value = Promise.resolve(values[0]); - i = 1; - } - - this._currentCancellable = value; - - if (!value.isRejected()) { - for (; i < length; ++i) { - var ctx = { - accum: null, - value: values[i], - index: i, - length: length, - array: this - }; - value = value._then(gotAccum, undefined, undefined, ctx, undefined); - } - } - - if (this._eachValues !== undefined) { - value = value - ._then(this._eachComplete, undefined, undefined, this, undefined); - } - value._then(completed, completed, undefined, value, this); -}; - -Promise.prototype.reduce = function (fn, initialValue) { - return reduce(this, fn, initialValue, null); -}; - -Promise.reduce = function (promises, fn, initialValue, _each) { - return reduce(promises, fn, initialValue, _each); -}; - -function completed(valueOrReason, array) { - if (this.isFulfilled()) { - array._resolve(valueOrReason); - } else { - array._reject(valueOrReason); - } -} - -function reduce(promises, fn, initialValue, _each) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var array = new ReductionPromiseArray(promises, fn, initialValue, _each); - return array.promise(); -} - -function gotAccum(accum) { - this.accum = accum; - this.array._gotAccum(accum); - var value = tryConvertToPromise(this.value, this.array._promise); - if (value instanceof Promise) { - this.array._currentCancellable = value; - return value._then(gotValue, undefined, undefined, this, undefined); - } else { - return gotValue.call(this, value); - } -} - -function gotValue(value) { - var array = this.array; - var promise = array._promise; - var fn = tryCatch(array._fn); - promise._pushContext(); - var ret; - if (array._eachValues !== undefined) { - ret = fn.call(promise._boundValue(), value, this.index, this.length); - } else { - ret = fn.call(promise._boundValue(), - this.accum, value, this.index, this.length); - } - if (ret instanceof Promise) { - array._currentCancellable = ret; - } - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", - promise - ); - return ret; -} -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/schedule.js b/node_modules/mquery/node_modules/bluebird/js/release/schedule.js deleted file mode 100644 index f70df9fc123b83c86cbb87ca37c3d091a5b3adb8..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/schedule.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -var util = require("./util"); -var schedule; -var noAsyncScheduler = function() { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var NativePromise = util.getNativePromise(); -if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function(fn) { GlobalSetImmediate.call(global, fn); } - : function(fn) { ProcessNextTick.call(process, fn); }; -} else if (typeof NativePromise === "function" && - typeof NativePromise.resolve === "function") { - var nativePromise = NativePromise.resolve(); - schedule = function(fn) { - nativePromise.then(fn); - }; -} else if ((typeof MutationObserver !== "undefined") && - !(typeof window !== "undefined" && - window.navigator && - (window.navigator.standalone || window.cordova))) { - schedule = (function() { - var div = document.createElement("div"); - var opts = {attributes: true}; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function() { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); - - var scheduleToggle = function() { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; - - return function schedule(fn) { - var o = new MutationObserver(function() { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); -} else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; -} else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; -} else { - schedule = noAsyncScheduler; -} -module.exports = schedule; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/settle.js b/node_modules/mquery/node_modules/bluebird/js/release/settle.js deleted file mode 100644 index fade3a174f2a4ac51e002412449d0c18a09418ea..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/settle.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -module.exports = - function(Promise, PromiseArray, debug) { -var PromiseInspection = Promise.PromiseInspection; -var util = require("./util"); - -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); - -SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { - var ret = new PromiseInspection(); - ret._bitField = 33554432; - ret._settledValueField = value; - return this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = function (reason, index) { - var ret = new PromiseInspection(); - ret._bitField = 16777216; - ret._settledValueField = reason; - return this._promiseResolved(index, ret); -}; - -Promise.settle = function (promises) { - debug.deprecated(".settle()", ".reflect()"); - return new SettledPromiseArray(promises).promise(); -}; - -Promise.prototype.settle = function () { - return Promise.settle(this); -}; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/some.js b/node_modules/mquery/node_modules/bluebird/js/release/some.js deleted file mode 100644 index 400d85207d6d7de2b996509bd567efe5cd893b0e..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/some.js +++ /dev/null @@ -1,148 +0,0 @@ -"use strict"; -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = require("./util"); -var RangeError = require("./errors").RangeError; -var AggregateError = require("./errors").AggregateError; -var isArray = util.isArray; -var CANCELLATION = {}; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; - -SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function () { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - return true; - } - return false; - -}; -SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._checkOutcome = function() { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; -}; - -SomePromiseArray.prototype._fulfilled = function () { - return this._totalResolved; -}; - -SomePromiseArray.prototype._rejected = function () { - return this._values.length - this.length(); -}; - -SomePromiseArray.prototype._addRejected = function (reason) { - this._values.push(reason); -}; - -SomePromiseArray.prototype._addFulfilled = function (value) { - this._values[this._totalResolved++] = value; -}; - -SomePromiseArray.prototype._canPossiblyFulfill = function () { - return this.length() - this._rejected(); -}; - -SomePromiseArray.prototype._getRangeError = function (count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; - -SomePromiseArray.prototype._resolveEmptyArray = function () { - this._reject(this._getRangeError(0)); -}; - -function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -Promise.some = function (promises, howMany) { - return some(promises, howMany); -}; - -Promise.prototype.some = function (howMany) { - return some(this, howMany); -}; - -Promise._SomePromiseArray = SomePromiseArray; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/synchronous_inspection.js b/node_modules/mquery/node_modules/bluebird/js/release/synchronous_inspection.js deleted file mode 100644 index 9c49d2e6003923d6093535246bc8ef64cae0422f..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/synchronous_inspection.js +++ /dev/null @@ -1,103 +0,0 @@ -"use strict"; -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() : undefined; - } - else { - this._bitField = 0; - this._settledValueField = undefined; - } -} - -PromiseInspection.prototype._settledValue = function() { - return this._settledValueField; -}; - -var value = PromiseInspection.prototype.value = function () { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var reason = PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { - return (this._bitField & 33554432) !== 0; -}; - -var isRejected = PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; -}; - -var isPending = PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; -}; - -var isResolved = PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; -}; - -PromiseInspection.prototype.isCancelled = function() { - return (this._bitField & 8454144) !== 0; -}; - -Promise.prototype.__isCancelled = function() { - return (this._bitField & 65536) === 65536; -}; - -Promise.prototype._isCancelled = function() { - return this._target().__isCancelled(); -}; - -Promise.prototype.isCancelled = function() { - return (this._target()._bitField & 8454144) !== 0; -}; - -Promise.prototype.isPending = function() { - return isPending.call(this._target()); -}; - -Promise.prototype.isRejected = function() { - return isRejected.call(this._target()); -}; - -Promise.prototype.isFulfilled = function() { - return isFulfilled.call(this._target()); -}; - -Promise.prototype.isResolved = function() { - return isResolved.call(this._target()); -}; - -Promise.prototype.value = function() { - return value.call(this._target()); -}; - -Promise.prototype.reason = function() { - var target = this._target(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); -}; - -Promise.prototype._value = function() { - return this._settledValue(); -}; - -Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); -}; - -Promise.PromiseInspection = PromiseInspection; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/thenables.js b/node_modules/mquery/node_modules/bluebird/js/release/thenables.js deleted file mode 100644 index d6ab9aa275d5b09dc39bc0978affe66333910dee..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/thenables.js +++ /dev/null @@ -1,86 +0,0 @@ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var util = require("./util"); -var errorObj = util.errorObj; -var isObject = util.isObject; - -function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; -} - -function doGetThen(obj) { - return obj.then; -} - -function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } -} - -function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; - - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } - - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } - - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; -} - -return tryConvertToPromise; -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/timers.js b/node_modules/mquery/node_modules/bluebird/js/release/timers.js deleted file mode 100644 index cb8f1f421a8cb44cf7457aa2d247a65e5ad2e7b2..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/timers.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; -module.exports = function(Promise, INTERNAL, debug) { -var util = require("./util"); -var TimeoutError = Promise.TimeoutError; - -function HandleWrapper(handle) { - this.handle = handle; -} - -HandleWrapper.prototype._resultCancelled = function() { - clearTimeout(this.handle); -}; - -var afterValue = function(value) { return delay(+this).thenReturn(value); }; -var delay = Promise.delay = function (ms, value) { - var ret; - var handle; - if (value !== undefined) { - ret = Promise.resolve(value) - ._then(afterValue, null, null, ms, undefined); - if (debug.cancellation() && value instanceof Promise) { - ret._setOnCancel(value); - } - } else { - ret = new Promise(INTERNAL); - handle = setTimeout(function() { ret._fulfill(); }, +ms); - if (debug.cancellation()) { - ret._setOnCancel(new HandleWrapper(handle)); - } - ret._captureStackTrace(); - } - ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.prototype.delay = function (ms) { - return delay(ms, this); -}; - -var afterTimeout = function (promise, message, parent) { - var err; - if (typeof message !== "string") { - if (message instanceof Error) { - err = message; - } else { - err = new TimeoutError("operation timed out"); - } - } else { - err = new TimeoutError(message); - } - util.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._reject(err); - - if (parent != null) { - parent.cancel(); - } -}; - -function successClear(value) { - clearTimeout(this.handle); - return value; -} - -function failureClear(reason) { - clearTimeout(this.handle); - throw reason; -} - -Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret, parent; - - var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { - if (ret.isPending()) { - afterTimeout(ret, message, parent); - } - }, ms)); - - if (debug.cancellation()) { - parent = this.then(); - ret = parent._then(successClear, failureClear, - undefined, handleWrapper, undefined); - ret._setOnCancel(handleWrapper); - } else { - ret = this._then(successClear, failureClear, - undefined, handleWrapper, undefined); - } - - return ret; -}; - -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/using.js b/node_modules/mquery/node_modules/bluebird/js/release/using.js deleted file mode 100644 index 65de531c11da24b485b59740807e6c3ea72e4a9e..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/using.js +++ /dev/null @@ -1,226 +0,0 @@ -"use strict"; -module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL, debug) { - var util = require("./util"); - var TypeError = require("./errors").TypeError; - var inherits = require("./util").inherits; - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var NULL = {}; - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = new Promise(INTERNAL); - function iterator() { - if (i >= len) return ret._fulfill(); - var maybePromise = castPreservingDisposable(resources[i++]); - if (maybePromise instanceof Promise && - maybePromise._isDisposable()) { - try { - maybePromise = tryConvertToPromise( - maybePromise._getDisposer().tryDispose(inspection), - resources.promise); - } catch (e) { - return thrower(e); - } - if (maybePromise instanceof Promise) { - return maybePromise._then(iterator, thrower, - null, null, null); - } - } - iterator(); - } - iterator(); - return ret; - } - - function Disposer(data, promise, context) { - this._data = data; - this._promise = promise; - this._context = context; - } - - Disposer.prototype.data = function () { - return this._data; - }; - - Disposer.prototype.promise = function () { - return this._promise; - }; - - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return NULL; - }; - - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var context = this._context; - if (context !== undefined) context._pushContext(); - var ret = resource !== NULL - ? this.doDispose(resource, inspection) : null; - if (context !== undefined) context._popContext(); - this._promise._unsetDisposable(); - this._data = null; - return ret; - }; - - Disposer.isDisposer = function (d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; - - function FunctionDisposer(fn, promise, context) { - this.constructor$(fn, promise, context); - } - inherits(FunctionDisposer, Disposer); - - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; - - function maybeUnwrapDisposer(value) { - if (Disposer.isDisposer(value)) { - this.resources[this.index]._setDisposable(value); - return value.promise(); - } - return value; - } - - function ResourceList(length) { - this.length = length; - this.promise = null; - this[length-1] = null; - } - - ResourceList.prototype._resultCancelled = function() { - var len = this.length; - for (var i = 0; i < len; ++i) { - var item = this[i]; - if (item instanceof Promise) { - item.cancel(); - } - } - }; - - Promise.using = function () { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var input; - var spreadArgs = true; - if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; - spreadArgs = false; - } else { - input = arguments; - len--; - } - var resources = new ResourceList(len); - for (var i = 0; i < len; ++i) { - var resource = input[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } else { - var maybePromise = tryConvertToPromise(resource); - if (maybePromise instanceof Promise) { - resource = - maybePromise._then(maybeUnwrapDisposer, null, null, { - resources: resources, - index: i - }, undefined); - } - } - resources[i] = resource; - } - - var reflectedResources = new Array(resources.length); - for (var i = 0; i < reflectedResources.length; ++i) { - reflectedResources[i] = Promise.resolve(resources[i]).reflect(); - } - - var resultPromise = Promise.all(reflectedResources) - .then(function(inspections) { - for (var i = 0; i < inspections.length; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - errorObj.e = inspection.error(); - return errorObj; - } else if (!inspection.isFulfilled()) { - resultPromise.cancel(); - return; - } - inspections[i] = inspection.value(); - } - promise._pushContext(); - - fn = tryCatch(fn); - var ret = spreadArgs - ? fn.apply(undefined, inspections) : fn(inspections); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, promiseCreated, "Promise.using", promise); - return ret; - }); - - var promise = resultPromise.lastly(function() { - var inspection = new Promise.PromiseInspection(resultPromise); - return dispose(resources, inspection); - }); - resources.promise = promise; - promise._setOnCancel(resources); - return promise; - }; - - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 131072; - this._disposer = disposer; - }; - - Promise.prototype._isDisposable = function () { - return (this._bitField & 131072) > 0; - }; - - Promise.prototype._getDisposer = function () { - return this._disposer; - }; - - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~131072); - this._disposer = undefined; - }; - - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this, createContext()); - } - throw new TypeError(); - }; - -}; diff --git a/node_modules/mquery/node_modules/bluebird/js/release/util.js b/node_modules/mquery/node_modules/bluebird/js/release/util.js deleted file mode 100644 index 7ac0e2fa1986c2d77345bb5785a630335e2f0653..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/js/release/util.js +++ /dev/null @@ -1,380 +0,0 @@ -"use strict"; -var es5 = require("./es5"); -var canEvaluate = typeof navigator == "undefined"; - -var errorObj = {e: {}}; -var tryCatchTarget; -var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; - -function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(safeToString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; - - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; - - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } - -})(); - -var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); - - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; - - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var l = 8; - while (l--) new FakeConstructor(); - return obj; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } -} - -function isError(obj) { - return obj instanceof Error || - (obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"); -} - -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 isError(obj) && es5.propertyIsWritable(obj, "stack"); -} - -var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } -})(); - -function classString(obj) { - return {}.toString.call(obj); -} - -function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } - } -} - -var asArray = function(v) { - if (es5.isArray(v)) { - return v; - } - return null; -}; - -if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; - - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; -} - -var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; - -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; - -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} - -function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -function domainBind(self, cb) { - return self.bind(cb); -} - -var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; diff --git a/node_modules/mquery/node_modules/bluebird/package.json b/node_modules/mquery/node_modules/bluebird/package.json deleted file mode 100644 index c228cbfc6d81a75d80e2c4e4a259486904370010..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/bluebird/package.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "_from": "bluebird@3.5.1", - "_id": "bluebird@3.5.1", - "_inBundle": false, - "_integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA==", - "_location": "/mquery/bluebird", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "bluebird@3.5.1", - "name": "bluebird", - "escapedName": "bluebird", - "rawSpec": "3.5.1", - "saveSpec": null, - "fetchSpec": "3.5.1" - }, - "_requiredBy": [ - "/mquery" - ], - "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", - "_shasum": "d9551f9de98f1fcda1e683d17ee91a0602ee2eb9", - "_spec": "bluebird@3.5.1", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mquery", - "author": { - "name": "Petka Antonov", - "email": "petka_antonov@hotmail.com", - "url": "http://github.com/petkaantonov/" - }, - "browser": "./js/browser/bluebird.js", - "bugs": { - "url": "http://github.com/petkaantonov/bluebird/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Full featured Promises/A+ implementation with exceptionally good performance", - "devDependencies": { - "acorn": "~0.6.0", - "baconjs": "^0.7.43", - "bluebird": "^2.9.2", - "body-parser": "^1.10.2", - "browserify": "^8.1.1", - "cli-table": "~0.3.1", - "co": "^4.2.0", - "cross-spawn": "^0.2.3", - "glob": "^4.3.2", - "grunt-saucelabs": "~8.4.1", - "highland": "^2.3.0", - "istanbul": "^0.3.5", - "jshint": "^2.6.0", - "jshint-stylish": "~0.2.0", - "kefir": "^2.4.1", - "mkdirp": "~0.5.0", - "mocha": "~2.1", - "open": "~0.0.5", - "optimist": "~0.6.1", - "rimraf": "~2.2.6", - "rx": "^2.3.25", - "serve-static": "^1.7.1", - "sinon": "~1.7.3", - "uglify-js": "~2.4.16" - }, - "files": [ - "js/browser", - "js/release", - "LICENSE" - ], - "homepage": "https://github.com/petkaantonov/bluebird", - "keywords": [ - "promise", - "performance", - "promises", - "promises-a", - "promises-aplus", - "async", - "await", - "deferred", - "deferreds", - "future", - "flow control", - "dsl", - "fluent interface" - ], - "license": "MIT", - "main": "./js/release/bluebird.js", - "name": "bluebird", - "repository": { - "type": "git", - "url": "git://github.com/petkaantonov/bluebird.git" - }, - "scripts": { - "generate-browser-core": "node tools/build.js --features=core --no-debug --release --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js", - "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify", - "istanbul": "istanbul", - "lint": "node scripts/jshint.js", - "prepublish": "npm run generate-browser-core && npm run generate-browser-full", - "test": "node tools/test.js" - }, - "version": "3.5.1", - "webpack": "./js/release/bluebird.js" -} diff --git a/node_modules/mquery/node_modules/debug/.coveralls.yml b/node_modules/mquery/node_modules/debug/.coveralls.yml deleted file mode 100644 index 20a7068581791335487166ddc5001a2ca3a3b060..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/.coveralls.yml +++ /dev/null @@ -1 +0,0 @@ -repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/mquery/node_modules/debug/.eslintrc b/node_modules/mquery/node_modules/debug/.eslintrc deleted file mode 100644 index 146371edbe325121c7666716c0fe238310b5e6ca..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/.eslintrc +++ /dev/null @@ -1,14 +0,0 @@ -{ - "env": { - "browser": true, - "node": true - }, - "globals": { - "chrome": true - }, - "rules": { - "no-console": 0, - "no-empty": [1, { "allowEmptyCatch": true }] - }, - "extends": "eslint:recommended" -} diff --git a/node_modules/mquery/node_modules/debug/.npmignore b/node_modules/mquery/node_modules/debug/.npmignore deleted file mode 100644 index 5f60eecc84e219e52554407ad38d04abd1cf2111..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -support -test -examples -example -*.sock -dist -yarn.lock -coverage -bower.json diff --git a/node_modules/mquery/node_modules/debug/.travis.yml b/node_modules/mquery/node_modules/debug/.travis.yml deleted file mode 100644 index a764300377fa424ed6b2651e72aaa3d68cd2075f..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -sudo: false - -language: node_js - -node_js: - - "4" - - "6" - - "8" - -install: - - make install - -script: - - make lint - - make test - -matrix: - include: - - node_js: '8' - env: BROWSER=1 diff --git a/node_modules/mquery/node_modules/debug/CHANGELOG.md b/node_modules/mquery/node_modules/debug/CHANGELOG.md deleted file mode 100644 index 820d21e3322b9d2778786ea743dd5e818991d595..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/CHANGELOG.md +++ /dev/null @@ -1,395 +0,0 @@ - -3.1.0 / 2017-09-26 -================== - - * Add `DEBUG_HIDE_DATE` env var (#486) - * Remove ReDoS regexp in %o formatter (#504) - * Remove "component" from package.json - * Remove `component.json` - * Ignore package-lock.json - * Examples: fix colors printout - * Fix: browser detection - * Fix: spelling mistake (#496, @EdwardBetts) - -3.0.1 / 2017-08-24 -================== - - * Fix: Disable colors in Edge and Internet Explorer (#489) - -3.0.0 / 2017-08-08 -================== - - * Breaking: Remove DEBUG_FD (#406) - * Breaking: Use `Date#toISOString()` instead to `Date#toUTCString()` when output is not a TTY (#418) - * Breaking: Make millisecond timer namespace specific and allow 'always enabled' output (#408) - * Addition: document `enabled` flag (#465) - * Addition: add 256 colors mode (#481) - * Addition: `enabled()` updates existing debug instances, add `destroy()` function (#440) - * Update: component: update "ms" to v2.0.0 - * Update: separate the Node and Browser tests in Travis-CI - * Update: refactor Readme, fixed documentation, added "Namespace Colors" section, redid screenshots - * Update: separate Node.js and web browser examples for organization - * Update: update "browserify" to v14.4.0 - * Fix: fix Readme typo (#473) - -2.6.9 / 2017-09-22 -================== - - * remove ReDoS regexp in %o formatter (#504) - -2.6.8 / 2017-05-18 -================== - - * Fix: Check for undefined on browser globals (#462, @marbemac) - -2.6.7 / 2017-05-16 -================== - - * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) - * Fix: Inline extend function in node implementation (#452, @dougwilson) - * Docs: Fix typo (#455, @msasad) - -2.6.5 / 2017-04-27 -================== - - * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) - * Misc: clean up browser reference checks (#447, @thebigredgeek) - * Misc: add npm-debug.log to .gitignore (@thebigredgeek) - - -2.6.4 / 2017-04-20 -================== - - * Fix: bug that would occur if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) - * Chore: ignore bower.json in npm installations. (#437, @joaovieira) - * Misc: update "ms" to v0.7.3 (@tootallnate) - -2.6.3 / 2017-03-13 -================== - - * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) - * Docs: Changelog fix (@thebigredgeek) - -2.6.2 / 2017-03-10 -================== - - * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) - * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) - * Docs: Add Slackin invite badge (@tootallnate) - -2.6.1 / 2017-02-10 -================== - - * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error - * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) - * Fix: IE8 "Expected identifier" error (#414, @vgoma) - * Fix: Namespaces would not disable once enabled (#409, @musikov) - -2.6.0 / 2016-12-28 -================== - - * Fix: added better null pointer checks for browser useColors (@thebigredgeek) - * Improvement: removed explicit `window.debug` export (#404, @tootallnate) - * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) - -2.5.2 / 2016-12-25 -================== - - * Fix: reference error on window within webworkers (#393, @KlausTrainer) - * Docs: fixed README typo (#391, @lurch) - * Docs: added notice about v3 api discussion (@thebigredgeek) - -2.5.1 / 2016-12-20 -================== - - * Fix: babel-core compatibility - -2.5.0 / 2016-12-20 -================== - - * Fix: wrong reference in bower file (@thebigredgeek) - * Fix: webworker compatibility (@thebigredgeek) - * Fix: output formatting issue (#388, @kribblo) - * Fix: babel-loader compatibility (#383, @escwald) - * Misc: removed built asset from repo and publications (@thebigredgeek) - * Misc: moved source files to /src (#378, @yamikuronue) - * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) - * Test: coveralls integration (#378, @yamikuronue) - * Docs: simplified language in the opening paragraph (#373, @yamikuronue) - -2.4.5 / 2016-12-17 -================== - - * Fix: `navigator` undefined in Rhino (#376, @jochenberger) - * Fix: custom log function (#379, @hsiliev) - * Improvement: bit of cleanup + linting fixes (@thebigredgeek) - * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) - * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) - -2.4.4 / 2016-12-14 -================== - - * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) - -2.4.3 / 2016-12-14 -================== - - * Fix: navigation.userAgent error for react native (#364, @escwald) - -2.4.2 / 2016-12-14 -================== - - * Fix: browser colors (#367, @tootallnate) - * Misc: travis ci integration (@thebigredgeek) - * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) - -2.4.1 / 2016-12-13 -================== - - * Fix: typo that broke the package (#356) - -2.4.0 / 2016-12-13 -================== - - * Fix: bower.json references unbuilt src entry point (#342, @justmatt) - * Fix: revert "handle regex special characters" (@tootallnate) - * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) - * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) - * Improvement: allow colors in workers (#335, @botverse) - * Improvement: use same color for same namespace. (#338, @lchenay) - -2.3.3 / 2016-11-09 -================== - - * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) - * Fix: Returning `localStorage` saved values (#331, Levi Thomason) - * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) - -2.3.2 / 2016-11-09 -================== - - * Fix: be super-safe in index.js as well (@TooTallNate) - * Fix: should check whether process exists (Tom Newby) - -2.3.1 / 2016-11-09 -================== - - * Fix: Added electron compatibility (#324, @paulcbetts) - * Improvement: Added performance optimizations (@tootallnate) - * Readme: Corrected PowerShell environment variable example (#252, @gimre) - * Misc: Removed yarn lock file from source control (#321, @fengmk2) - -2.3.0 / 2016-11-07 -================== - - * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) - * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) - * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) - * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) - * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) - * Package: Update "ms" to 0.7.2 (#315, @DevSide) - * Package: removed superfluous version property from bower.json (#207 @kkirsche) - * Readme: fix USE_COLORS to DEBUG_COLORS - * Readme: Doc fixes for format string sugar (#269, @mlucool) - * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) - * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) - * Readme: better docs for browser support (#224, @matthewmueller) - * Tooling: Added yarn integration for development (#317, @thebigredgeek) - * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) - * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) - * Misc: Updated contributors (@thebigredgeek) - -2.2.0 / 2015-05-09 -================== - - * package: update "ms" to v0.7.1 (#202, @dougwilson) - * README: add logging to file example (#193, @DanielOchoa) - * README: fixed a typo (#191, @amir-s) - * browser: expose `storage` (#190, @stephenmathieson) - * Makefile: add a `distclean` target (#189, @stephenmathieson) - -2.1.3 / 2015-03-13 -================== - - * Updated stdout/stderr example (#186) - * Updated example/stdout.js to match debug current behaviour - * Renamed example/stderr.js to stdout.js - * Update Readme.md (#184) - * replace high intensity foreground color for bold (#182, #183) - -2.1.2 / 2015-03-01 -================== - - * dist: recompile - * update "ms" to v0.7.0 - * package: update "browserify" to v9.0.3 - * component: fix "ms.js" repo location - * changed bower package name - * updated documentation about using debug in a browser - * fix: security error on safari (#167, #168, @yields) - -2.1.1 / 2014-12-29 -================== - - * browser: use `typeof` to check for `console` existence - * browser: check for `console.log` truthiness (fix IE 8/9) - * browser: add support for Chrome apps - * Readme: added Windows usage remarks - * Add `bower.json` to properly support bower install - -2.1.0 / 2014-10-15 -================== - - * node: implement `DEBUG_FD` env variable support - * package: update "browserify" to v6.1.0 - * package: add "license" field to package.json (#135, @panuhorsmalahti) - -2.0.0 / 2014-09-01 -================== - - * package: update "browserify" to v5.11.0 - * node: use stderr rather than stdout for logging (#29, @stephenmathieson) - -1.0.4 / 2014-07-15 -================== - - * dist: recompile - * example: remove `console.info()` log usage - * example: add "Content-Type" UTF-8 header to browser example - * browser: place %c marker after the space character - * browser: reset the "content" color via `color: inherit` - * browser: add colors support for Firefox >= v31 - * debug: prefer an instance `log()` function over the global one (#119) - * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) - -1.0.3 / 2014-07-09 -================== - - * Add support for multiple wildcards in namespaces (#122, @seegno) - * browser: fix lint - -1.0.2 / 2014-06-10 -================== - - * browser: update color palette (#113, @gscottolson) - * common: make console logging function configurable (#108, @timoxley) - * node: fix %o colors on old node <= 0.8.x - * Makefile: find node path using shell/which (#109, @timoxley) - -1.0.1 / 2014-06-06 -================== - - * browser: use `removeItem()` to clear localStorage - * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) - * package: add "contributors" section - * node: fix comment typo - * README: list authors - -1.0.0 / 2014-06-04 -================== - - * make ms diff be global, not be scope - * debug: ignore empty strings in enable() - * node: make DEBUG_COLORS able to disable coloring - * *: export the `colors` array - * npmignore: don't publish the `dist` dir - * Makefile: refactor to use browserify - * package: add "browserify" as a dev dependency - * Readme: add Web Inspector Colors section - * node: reset terminal color for the debug content - * node: map "%o" to `util.inspect()` - * browser: map "%j" to `JSON.stringify()` - * debug: add custom "formatters" - * debug: use "ms" module for humanizing the diff - * Readme: add "bash" syntax highlighting - * browser: add Firebug color support - * browser: add colors for WebKit browsers - * node: apply log to `console` - * rewrite: abstract common logic for Node & browsers - * add .jshintrc file - -0.8.1 / 2014-04-14 -================== - - * package: re-add the "component" section - -0.8.0 / 2014-03-30 -================== - - * add `enable()` method for nodejs. Closes #27 - * change from stderr to stdout - * remove unnecessary index.js file - -0.7.4 / 2013-11-13 -================== - - * remove "browserify" key from package.json (fixes something in browserify) - -0.7.3 / 2013-10-30 -================== - - * fix: catch localStorage security error when cookies are blocked (Chrome) - * add debug(err) support. Closes #46 - * add .browser prop to package.json. Closes #42 - -0.7.2 / 2013-02-06 -================== - - * fix package.json - * fix: Mobile Safari (private mode) is broken with debug - * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript - -0.7.1 / 2013-02-05 -================== - - * add repository URL to package.json - * add DEBUG_COLORED to force colored output - * add browserify support - * fix component. Closes #24 - -0.7.0 / 2012-05-04 -================== - - * Added .component to package.json - * Added debug.component.js build - -0.6.0 / 2012-03-16 -================== - - * Added support for "-" prefix in DEBUG [Vinay Pulim] - * Added `.enabled` flag to the node version [TooTallNate] - -0.5.0 / 2012-02-02 -================== - - * Added: humanize diffs. Closes #8 - * Added `debug.disable()` to the CS variant - * Removed padding. Closes #10 - * Fixed: persist client-side variant again. Closes #9 - -0.4.0 / 2012-02-01 -================== - - * Added browser variant support for older browsers [TooTallNate] - * Added `debug.enable('project:*')` to browser variant [TooTallNate] - * Added padding to diff (moved it to the right) - -0.3.0 / 2012-01-26 -================== - - * Added millisecond diff when isatty, otherwise UTC string - -0.2.0 / 2012-01-22 -================== - - * Added wildcard support - -0.1.0 / 2011-12-02 -================== - - * Added: remove colors unless stderr isatty [TooTallNate] - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/mquery/node_modules/debug/LICENSE b/node_modules/mquery/node_modules/debug/LICENSE deleted file mode 100644 index 658c933d28255e8c716899789e8c0f846e5dc125..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 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/mquery/node_modules/debug/Makefile b/node_modules/mquery/node_modules/debug/Makefile deleted file mode 100644 index 3ddd1360e6a95e6d7161f2d4d4f8cb9a0816f577..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/Makefile +++ /dev/null @@ -1,58 +0,0 @@ -# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 -THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) -THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) - -# BIN directory -BIN := $(THIS_DIR)/node_modules/.bin - -# Path -PATH := node_modules/.bin:$(PATH) -SHELL := /bin/bash - -# applications -NODE ?= $(shell which node) -YARN ?= $(shell which yarn) -PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) -BROWSERIFY ?= $(NODE) $(BIN)/browserify - -install: node_modules - -browser: dist/debug.js - -node_modules: package.json - @NODE_ENV= $(PKG) install - @touch node_modules - -dist/debug.js: src/*.js node_modules - @mkdir -p dist - @$(BROWSERIFY) \ - --standalone debug \ - . > dist/debug.js - -lint: - @eslint *.js src/*.js - -test-node: - @istanbul cover node_modules/mocha/bin/_mocha -- test/**.js - @cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js - -test-browser: - @$(MAKE) browser - @karma start --single-run - -test-all: - @concurrently \ - "make test-node" \ - "make test-browser" - -test: - @if [ "x$(BROWSER)" = "x" ]; then \ - $(MAKE) test-node; \ - else \ - $(MAKE) test-browser; \ - fi - -clean: - rimraf dist coverage - -.PHONY: browser install clean lint test test-all test-node test-browser diff --git a/node_modules/mquery/node_modules/debug/README.md b/node_modules/mquery/node_modules/debug/README.md deleted file mode 100644 index 8e754d17b164ad9c15b82e26426afa71298a34d1..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/README.md +++ /dev/null @@ -1,368 +0,0 @@ -# debug -[](https://travis-ci.org/visionmedia/debug) [](https://coveralls.io/github/visionmedia/debug?branch=master) [](https://visionmedia-community-slackin.now.sh/) [](#backers) -[](#sponsors) - -<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> - -A tiny JavaScript debugging utility modelled after Node.js core's debugging -technique. Works in Node.js and web browsers. - -## Installation - -```bash -$ npm install debug -``` - -## Usage - -`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. - -Example [_app.js_](./examples/node/app.js): - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %o', 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_](./examples/node/worker.js): - -```js -var a = require('debug')('worker:a') - , b = require('debug')('worker:b'); - -function work() { - a('doing lots of uninteresting work'); - setTimeout(work, Math.random() * 1000); -} - -work(); - -function workb() { - b('doing some work'); - setTimeout(workb, Math.random() * 2000); -} - -workb(); -``` - -The `DEBUG` environment variable is then used to enable these based on space or -comma-delimited names. - -Here are some examples: - -<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> -<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> -<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> - -#### Windows note - -On Windows the environment variable is set using the `set` command. - -```cmd -set DEBUG=*,-not_this -``` - -Note that PowerShell uses different syntax to set environment variables. - -```cmd -$env:DEBUG = "*,-not_this" -``` - -Then, run the program to be debugged as usual. - - -## Namespace Colors - -Every debug instance has a color generated for it based on its namespace name. -This helps when visually parsing the debug output to identify which debug instance -a debug line belongs to. - -#### Node.js - -In Node.js, colors are enabled when stderr is a TTY. You also _should_ install -the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, -otherwise debug will only use a small handful of basic colors. - -<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> - -#### Web Browser - -Colors are also enabled on "Web Inspectors" that understand the `%c` formatting -option. These are WebKit web inspectors, Firefox ([since version -31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) -and the Firebug plugin for Firefox (any version). - -<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.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. - -<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> - -When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: - -<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.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". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. - -## 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:". - -## Environment Variables - -When running through Node.js, you can set a few environment variables that will -change the behavior of the debug logging: - -| Name | Purpose | -|-----------|-------------------------------------------------| -| `DEBUG` | Enables/disables specific debugging namespaces. | -| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | -| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | -| `DEBUG_DEPTH` | Object inspection depth. | -| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | - - -__Note:__ The environment variables beginning with `DEBUG_` end up being -converted into an Options object that gets used with `%o`/`%O` formatters. -See the Node.js documentation for -[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) -for the complete list. - -## Formatters - -Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. -Below are the officially supported formatters: - -| Formatter | Representation | -|-----------|----------------| -| `%O` | Pretty-print an Object on multiple lines. | -| `%o` | Pretty-print an Object all on a single line. | -| `%s` | String. | -| `%d` | Number (both integer and float). | -| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | -| `%%` | Single percent sign ('%'). This does not consume an argument. | - - -### Custom formatters - -You can add custom formatters by extending the `debug.formatters` object. -For example, if you wanted to add support for rendering a Buffer as hex with -`%h`, you could do something like: - -```js -const createDebug = require('debug') -createDebug.formatters.h = (v) => { - return v.toString('hex') -} - -// …elsewhere -const debug = createDebug('foo') -debug('this is hex: %h', new Buffer('hello world')) -// foo this is hex: 68656c6c6f20776f726c6421 +0ms -``` - - -## Browser Support - -You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), -or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), -if you don't want to build it yourself. - -Debug's enable state is currently persisted by `localStorage`. -Consider the situation shown below where you have `worker:a` and `worker:b`, -and wish to debug both. You can enable this using `localStorage.debug`: - -```js -localStorage.debug = 'worker:*' -``` - -And then refresh the page. - -```js -a = debug('worker:a'); -b = debug('worker:b'); - -setInterval(function(){ - a('doing some work'); -}, 1000); - -setInterval(function(){ - b('doing some work'); -}, 1200); -``` - - -## Output streams - - By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: - -Example [_stdout.js_](./examples/node/stdout.js): - -```js -var debug = require('debug'); -var error = debug('app:error'); - -// by default stderr is used -error('goes to stderr!'); - -var log = debug('app:log'); -// set this namespace to log via console.log -log.log = console.log.bind(console); // don't forget to bind to console! -log('goes to stdout'); -error('still goes to stderr!'); - -// set all output to go via console.info -// overrides all per-namespace log settings -debug.log = console.info.bind(console); -error('now goes to stdout via console.info'); -log('still goes to stdout, but via console.info now'); -``` - -## Checking whether a debug target is enabled - -After you've created a debug instance, you can determine whether or not it is -enabled by checking the `enabled` property: - -```javascript -const debug = require('debug')('http'); - -if (debug.enabled) { - // do stuff... -} -``` - -You can also manually toggle this property to force the debug instance to be -enabled or disabled. - - -## Authors - - - TJ Holowaychuk - - Nathan Rajlich - - Andrew Rhyne - -## Backers - -Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] - -<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> -<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> - - -## Sponsors - -Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] - -<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> -<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> - -## License - -(The MIT License) - -Copyright (c) 2014-2017 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/mquery/node_modules/debug/karma.conf.js b/node_modules/mquery/node_modules/debug/karma.conf.js deleted file mode 100644 index 103a82d15bd72b3cdf9ba4108272985f7e0bfdb3..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/karma.conf.js +++ /dev/null @@ -1,70 +0,0 @@ -// Karma configuration -// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) - -module.exports = function(config) { - config.set({ - - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '', - - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['mocha', 'chai', 'sinon'], - - - // list of files / patterns to load in the browser - files: [ - 'dist/debug.js', - 'test/*spec.js' - ], - - - // list of files to exclude - exclude: [ - 'src/node.js' - ], - - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - }, - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['progress'], - - - // web server port - port: 9876, - - - // enable / disable colors in the output (reporters and logs) - colors: true, - - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: true, - - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: ['PhantomJS'], - - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: false, - - // Concurrency level - // how many browser should be started simultaneous - concurrency: Infinity - }) -} diff --git a/node_modules/mquery/node_modules/debug/node.js b/node_modules/mquery/node_modules/debug/node.js deleted file mode 100644 index 7fc36fe6dbecbfd41530c5a490cc738ec2968653..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/node.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./src/node'); diff --git a/node_modules/mquery/node_modules/debug/package.json b/node_modules/mquery/node_modules/debug/package.json deleted file mode 100644 index 65e45c4213b56895c7aaf12ad9c09f02c711fd2c..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/package.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "_from": "debug@3.1.0", - "_id": "debug@3.1.0", - "_inBundle": false, - "_integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "_location": "/mquery/debug", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "debug@3.1.0", - "name": "debug", - "escapedName": "debug", - "rawSpec": "3.1.0", - "saveSpec": null, - "fetchSpec": "3.1.0" - }, - "_requiredBy": [ - "/mquery" - ], - "_resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "_shasum": "5bb5a0672628b64149566ba16819e61518c67261", - "_spec": "debug@3.1.0", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mquery", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "browser": "./src/browser.js", - "bugs": { - "url": "https://github.com/visionmedia/debug/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "http://n8.io" - }, - { - "name": "Andrew Rhyne", - "email": "rhyneandrew@gmail.com" - } - ], - "dependencies": { - "ms": "2.0.0" - }, - "deprecated": false, - "description": "small debugging utility", - "devDependencies": { - "browserify": "14.4.0", - "chai": "^3.5.0", - "concurrently": "^3.1.0", - "coveralls": "^2.11.15", - "eslint": "^3.12.1", - "istanbul": "^0.4.5", - "karma": "^1.3.0", - "karma-chai": "^0.1.0", - "karma-mocha": "^1.3.0", - "karma-phantomjs-launcher": "^1.0.2", - "karma-sinon": "^1.0.5", - "mocha": "^3.2.0", - "mocha-lcov-reporter": "^1.2.0", - "rimraf": "^2.5.4", - "sinon": "^1.17.6", - "sinon-chai": "^2.8.0" - }, - "homepage": "https://github.com/visionmedia/debug#readme", - "keywords": [ - "debug", - "log", - "debugger" - ], - "license": "MIT", - "main": "./src/index.js", - "name": "debug", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/debug.git" - }, - "version": "3.1.0" -} diff --git a/node_modules/mquery/node_modules/debug/src/browser.js b/node_modules/mquery/node_modules/debug/src/browser.js deleted file mode 100644 index f5149ff5296aa11442834d29fdc8565bb159d0be..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/src/browser.js +++ /dev/null @@ -1,195 +0,0 @@ -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', - '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', - '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', - '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', - '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', - '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', - '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', - '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', - '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', - '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', - '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} diff --git a/node_modules/mquery/node_modules/debug/src/debug.js b/node_modules/mquery/node_modules/debug/src/debug.js deleted file mode 100644 index 77e6384a3397605624a1706eb864455f8e7f38ba..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/src/debug.js +++ /dev/null @@ -1,225 +0,0 @@ - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); - -/** - * Active `debug` instances. - */ -exports.instances = []; - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - -exports.formatters = {}; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; - - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return exports.colors[Math.abs(hash) % exports.colors.length]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - var prevTime; - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - exports.instances.push(debug); - - return debug; -} - -function destroy () { - var index = exports.instances.indexOf(this); - if (index !== -1) { - exports.instances.splice(index, 1); - return true; - } else { - return false; - } -} - -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var i; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } - - for (i = 0; i < exports.instances.length; i++) { - var instance = exports.instances[i]; - instance.enabled = exports.enabled(instance.namespace); - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} diff --git a/node_modules/mquery/node_modules/debug/src/index.js b/node_modules/mquery/node_modules/debug/src/index.js deleted file mode 100644 index cabcbcda135e862c4780a270a8df97784e65ebb3..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/src/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer') { - module.exports = require('./browser.js'); -} else { - module.exports = require('./node.js'); -} diff --git a/node_modules/mquery/node_modules/debug/src/node.js b/node_modules/mquery/node_modules/debug/src/node.js deleted file mode 100644 index d666fb9c00919bf71317101ebe1096df0e43b215..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/debug/src/node.js +++ /dev/null @@ -1,186 +0,0 @@ -/** - * Module dependencies. - */ - -var tty = require('tty'); -var util = require('util'); - -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. - */ - -exports.colors = [ 6, 2, 3, 4, 5, 1 ]; - -try { - var supportsColor = require('supports-color'); - if (supportsColor && supportsColor.level >= 2) { - exports.colors = [ - 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, - 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, - 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, - 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, - 205, 206, 207, 208, 209, 214, 215, 220, 221 - ]; - } -} catch (err) { - // swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(process.stderr.fd); -} - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; - -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ - -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; - - if (useColors) { - var c = this.color; - var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c); - var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m'; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } else { - return new Date().toISOString() + ' '; - } -} - -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ - -function log() { - return process.stderr.write(util.format.apply(util, arguments) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ - -exports.enable(load()); diff --git a/node_modules/mquery/node_modules/ms/index.js b/node_modules/mquery/node_modules/ms/index.js deleted file mode 100644 index 6a522b16b3a3bf5e93aa5b8bf485f866ff71c5c2..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/ms/index.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} diff --git a/node_modules/mquery/node_modules/ms/package.json b/node_modules/mquery/node_modules/ms/package.json deleted file mode 100644 index 5fd2d7c40fe7a547798bdb057ee933afa09406eb..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/ms/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "ms@2.0.0", - "_id": "ms@2.0.0", - "_inBundle": false, - "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "_location": "/mquery/ms", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "ms@2.0.0", - "name": "ms", - "escapedName": "ms", - "rawSpec": "2.0.0", - "saveSpec": null, - "fetchSpec": "2.0.0" - }, - "_requiredBy": [ - "/mquery/debug" - ], - "_resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "_shasum": "5608aeadfc00be6c2901df5f9861788de0d597c8", - "_spec": "ms@2.0.0", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mquery/node_modules/debug", - "bugs": { - "url": "https://github.com/zeit/ms/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Tiny milisecond conversion utility", - "devDependencies": { - "eslint": "3.19.0", - "expect.js": "0.3.1", - "husky": "0.13.3", - "lint-staged": "3.4.1", - "mocha": "3.4.1" - }, - "eslintConfig": { - "extends": "eslint:recommended", - "env": { - "node": true, - "es6": true - } - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/zeit/ms#readme", - "license": "MIT", - "lint-staged": { - "*.js": [ - "npm run lint", - "prettier --single-quote --write", - "git add" - ] - }, - "main": "./index", - "name": "ms", - "repository": { - "type": "git", - "url": "git+https://github.com/zeit/ms.git" - }, - "scripts": { - "lint": "eslint lib/* bin/*", - "precommit": "lint-staged", - "test": "mocha tests.js" - }, - "version": "2.0.0" -} diff --git a/node_modules/mquery/node_modules/ms/readme.md b/node_modules/mquery/node_modules/ms/readme.md deleted file mode 100644 index 84a9974cccd81f9296b7d3c77f2b0d2765dfe181..0000000000000000000000000000000000000000 --- a/node_modules/mquery/node_modules/ms/readme.md +++ /dev/null @@ -1,51 +0,0 @@ -# ms - -[](https://travis-ci.org/zeit/ms) -[](https://zeit.chat/) - -Use this package to easily convert various time formats to milliseconds. - -## Examples - -```js -ms('2 days') // 172800000 -ms('1d') // 86400000 -ms('10h') // 36000000 -ms('2.5 hrs') // 9000000 -ms('2h') // 7200000 -ms('1m') // 60000 -ms('5s') // 5000 -ms('1y') // 31557600000 -ms('100') // 100 -``` - -### Convert from milliseconds - -```js -ms(60000) // "1m" -ms(2 * 60000) // "2m" -ms(ms('10 hours')) // "10h" -``` - -### Time format written-out - -```js -ms(60000, { long: true }) // "1 minute" -ms(2 * 60000, { long: true }) // "2 minutes" -ms(ms('10 hours'), { long: true }) // "10 hours" -``` - -## Features - -- Works both in [node](https://nodejs.org) and in the browser. -- If a number is supplied to `ms`, a string with a unit is returned. -- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). -- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. - -## Caught a bug? - -1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device -2. Link the package to the global module directory: `npm link` -3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! - -As always, you can run the tests using: `npm test` diff --git a/node_modules/mquery/package.json b/node_modules/mquery/package.json deleted file mode 100644 index 1f9068e898993933db330722c3baeae7f98bc798..0000000000000000000000000000000000000000 --- a/node_modules/mquery/package.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "_from": "mquery@3.2.0", - "_id": "mquery@3.2.0", - "_inBundle": false, - "_integrity": "sha512-qPJcdK/yqcbQiKoemAt62Y0BAc0fTEKo1IThodBD+O5meQRJT/2HSe5QpBNwaa4CjskoGrYWsEyjkqgiE0qjhg==", - "_location": "/mquery", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mquery@3.2.0", - "name": "mquery", - "escapedName": "mquery", - "rawSpec": "3.2.0", - "saveSpec": null, - "fetchSpec": "3.2.0" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/mquery/-/mquery-3.2.0.tgz", - "_shasum": "e276472abd5109686a15eb2a8e0761db813c81cc", - "_spec": "mquery@3.2.0", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongoose", - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "bugs": { - "url": "https://github.com/aheckmann/mquery/issues/new" - }, - "bundleDependencies": false, - "dependencies": { - "bluebird": "3.5.1", - "debug": "3.1.0", - "regexp-clone": "0.0.1", - "safe-buffer": "5.1.2", - "sliced": "1.0.1" - }, - "deprecated": false, - "description": "Expressive query building for MongoDB", - "devDependencies": { - "eslint": "^4.14.0", - "istanbul": "^0.4.5", - "mocha": "4.1.0", - "mongodb": "3.1.1" - }, - "engines": { - "node": ">=4.0.0" - }, - "eslintConfig": { - "env": { - "node": true, - "mocha": true, - "es6": false - }, - "extends": "eslint:recommended", - "parserOptions": { - "ecmaVersion": 5 - }, - "rules": { - "comma-style": "error", - "consistent-this": [ - "error", - "_this" - ], - "indent": [ - "error", - 2, - { - "SwitchCase": 1, - "VariableDeclarator": 2 - } - ], - "keyword-spacing": "error", - "no-console": "off", - "no-multi-spaces": "error", - "func-call-spacing": "error", - "no-trailing-spaces": "error", - "quotes": [ - "error", - "single" - ], - "semi": "error", - "space-before-blocks": "error", - "space-before-function-paren": [ - "error", - "never" - ], - "space-infix-ops": "error", - "space-unary-ops": "error" - } - }, - "homepage": "https://github.com/aheckmann/mquery/", - "keywords": [ - "mongodb", - "query", - "builder" - ], - "license": "MIT", - "main": "lib/mquery.js", - "name": "mquery", - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mquery.git" - }, - "scripts": { - "fix-lint": "eslint . --fix", - "lint": "eslint .", - "test": "mocha test/index.js test/*.test.js" - }, - "version": "3.2.0" -} diff --git a/node_modules/mquery/test/collection/browser.js b/node_modules/mquery/test/collection/browser.js deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/node_modules/mquery/test/collection/mongo.js b/node_modules/mquery/test/collection/mongo.js deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/node_modules/mquery/test/collection/node.js b/node_modules/mquery/test/collection/node.js deleted file mode 100644 index 8ac380b4fc80bbf226d1371118b96ce0e6286b0e..0000000000000000000000000000000000000000 --- a/node_modules/mquery/test/collection/node.js +++ /dev/null @@ -1,28 +0,0 @@ - -var assert = require('assert'); -var mongo = require('mongodb'); - -var uri = process.env.MQUERY_URI || 'mongodb://localhost/mquery'; -var client; -var db; - -exports.getCollection = function(cb) { - mongo.MongoClient.connect(uri, function(err, _client) { - assert.ifError(err); - client = _client; - db = client.db(); - - var collection = db.collection('stuff'); - - // clean test db before starting - db.dropDatabase(function() { - cb(null, collection); - }); - }); -}; - -exports.dropCollection = function(cb) { - db.dropDatabase(function() { - client.close(cb); - }); -}; diff --git a/node_modules/mquery/test/env.js b/node_modules/mquery/test/env.js deleted file mode 100644 index 38385b074f3f6bf82186cc53f86d1b10e763acea..0000000000000000000000000000000000000000 --- a/node_modules/mquery/test/env.js +++ /dev/null @@ -1,21 +0,0 @@ - -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'); - break; - case 'browser': - col = require('./collection/browser'); - break; - default: - throw new Error('missing collection implementation for environment: ' + env.type); -} - -module.exports = exports = col; diff --git a/node_modules/mquery/test/index.js b/node_modules/mquery/test/index.js deleted file mode 100644 index 44adb178582fe0c8be4e2e551ba00194b91b4057..0000000000000000000000000000000000000000 --- a/node_modules/mquery/test/index.js +++ /dev/null @@ -1,3076 +0,0 @@ -var mquery = require('../'); -var assert = require('assert'); - -/* global Map */ - -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; - m = mquery(col, { safe: true }); - assert.deepEqual({ safe: true }, m.options); - 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(), - n; - - n = m.setOptions(); - assert.equal(m, n); - 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(), - n; - - n = m.where('x', 'y'); - assert.equal(m, n); - 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('eq', function() { - it('is alias of equals', function() { - var m = mquery(); - m.where('age').eq(1000); - assert.deepEqual({ age: 1000 }, m._conditions); - }); - }); - 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 minDistance'.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('supports minDistance', function() { - var m = mquery().where('loc').near({ center: [1,2], minDistance:4 }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2], $minDistance: 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 accept an array', function() { - var o = ['x', '-y']; - var m = mquery().select(o); - assert.deepEqual(m._fields, { x: 1, y: 0 }); - }); - - 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 arguments objects', function() { - var m = mquery(); - function t() { - m.select(arguments); - assert.deepEqual(m._fields, { x: 1, y: 0 }); - } - t('x', '-y'); - }); - - noDistinct('select'); - }); - - describe('selected', function() { - it('returns true when fields have been selected', function(done) { - var m; - - m = mquery().select({ name: 1 }); - assert.ok(m.selected()); - - 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(); - }); - it('when using $meta', function(done) { - assert.strictEqual(false, mquery().select({ name: { $meta: 'textScore' } }).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(); - query.sort([['a', -1], ['c', 1], ['b', 'desc'], ['e', 'ascending'], ['f', 'descending']]); - 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], { 'b': 5 }]); - } catch (err) { - e = err; - } - assert.ok(e, 'uh oh. no error was thrown'); - assert.equal(e.message, 'Invalid sort() argument, must be array of arrays'); - - query = mquery(); - 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, object, or array.'); - }); - - it('handles $meta sort options', function() { - var query = mquery(); - query.sort({ score: { $meta : 'textScore' } }); - assert.deepEqual(query.options.sort, { score : { $meta : 'textScore' } }); - }); - - it('array syntax', function() { - var query = mquery(); - query.sort([['field', 1], ['test', -1]]); - assert.deepEqual(query.options.sort, [['field', 1], ['test', -1]]); - }); - - it('throws with mixed array/object syntax', function() { - var query = mquery(); - assert.throws(function() { - query.sort({ field: 1 }).sort([['test', -1]]); - }, /Can't mix sort syntaxes/); - assert.throws(function() { - query.sort([['field', 1]]).sort({ test: 1 }); - }, /Can't mix sort syntaxes/); - }); - - it('works with maps', function() { - if (typeof Map === 'undefined') { - return this.skip(); - } - var query = mquery(); - query.sort(new Map().set('field', 1).set('test', -1)); - assert.deepEqual(query.options.sort, new Map().set('field', 1).set('test', -1)); - }); - }); - - 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; - - query = mquery(); - query.snapshot(); - assert.equal(true, query.options.snapshot); - - query = mquery(); - query.snapshot(true); - assert.equal(true, query.options.snapshot); - - 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('accepts a string', function() { - var query2 = mquery(); - query2.hint('a'); - assert.deepEqual(query2.options.hint, 'a'); - }); - - it('rejects everything else', function() { - 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('j', function() { - it('works', function() { - var m = mquery().j(true); - assert.equal(true, m.options.j); - }); - }); - - describe('slaveOk', function() { - it('works', function() { - var query; - - query = mquery(); - query.slaveOk(); - assert.equal(true, query.options.slaveOk); - - query = mquery(); - query.slaveOk(true); - assert.equal(true, query.options.slaveOk); - - 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('readConcern', function() { - it('sets associated readConcern option', function() { - var m; - - m = mquery(); - m.readConcern('s'); - assert.deepEqual({ level: 'snapshot' }, m.options.readConcern); - - m = mquery(); - m.r('local'); - assert.deepEqual({ level: 'local' }, m.options.readConcern); - }); - it('is chainable', function() { - var m = mquery(); - assert.equal(m, m.readConcern('lz')); - }); - }); - - describe('tailable', function() { - it('works', function() { - var query; - - query = mquery(); - query.tailable(); - assert.equal(true, query.options.tailable); - - query = mquery(); - query.tailable(true); - assert.equal(true, query.options.tailable); - - 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'); - }); - - describe('writeConcern', function() { - it('sets associated writeConcern option', function() { - var m; - m = mquery(); - m.writeConcern('majority'); - assert.equal('majority', m.options.w); - - m = mquery(); - m.writeConcern('m'); // m is alias of majority - assert.equal('majority', m.options.w); - - m = mquery(); - m.writeConcern(1); - assert.equal(1, m.options.w); - }); - it('accepts object', function() { - var m; - - m = mquery().writeConcern({ w: 'm', j: true, wtimeout: 1000 }); - assert.equal('m', m.options.w); // check it does not convert m to majority - assert.equal(true, m.options.j); - assert.equal(1000, m.options.wtimeout); - - m = mquery().w('m').w({j: false, wtimeout: 0 }); - assert.equal('majority', m.options.w); - assert.strictEqual(false, m.options.j); - assert.strictEqual(0, m.options.wtimeout); - }); - it('is chainable', function() { - var m = mquery(); - assert.equal(m, m.writeConcern('majority')); - }); - }); - - // 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.doesNotThrow(function() { - mquery().sort('x').count(); - }); - done(); - }); - - it('select', function(done) { - assert.throws(function() { - mquery().select('x').count(); - }, /field selection and slice cannot be used with count/); - done(); - }); - - it('slice', function(done) { - assert.throws(function() { - mquery().where('x').slice(-3).count(); - }, /field selection and slice cannot be used with count/); - done(); - }); - - it('limit', function(done) { - assert.doesNotThrow(function() { - mquery().limit(3).count(); - }); - done(); - }); - - it('skip', function(done) { - assert.doesNotThrow(function() { - mquery().skip(3).count(); - }); - done(); - }); - - it('batchSize', function(done) { - assert.throws(function() { - mquery({}, { batchSize: 3 }).count(); - }, /batchSize cannot be used with count/); - done(); - }); - - it('comment', function(done) { - assert.throws(function() { - mquery().comment('mquery').count(); - }, /comment cannot be used with count/); - done(); - }); - - it('maxScan', function(done) { - assert.throws(function() { - mquery().maxScan(300).count(); - }, /maxScan cannot be used with count/); - done(); - }); - - it('snapshot', function(done) { - assert.throws(function() { - mquery().snapshot().count(); - }, /snapshot cannot be used with count/); - done(); - }); - - it('tailable', function(done) { - assert.throws(function() { - 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() { - 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() { - mquery().sort('x').distinct(); - }, /sort cannot be used with distinct/); - done(); - }); - - it('select', function(done) { - assert.throws(function() { - mquery().select('x').distinct(); - }, /field selection and slice cannot be used with distinct/); - done(); - }); - - it('slice', function(done) { - assert.throws(function() { - mquery().where('x').slice(-3).distinct(); - }, /field selection and slice cannot be used with distinct/); - done(); - }); - - it('limit', function(done) { - assert.throws(function() { - mquery().limit(3).distinct(); - }, /limit cannot be used with distinct/); - done(); - }); - - it('skip', function(done) { - assert.throws(function() { - mquery().skip(3).distinct(); - }, /skip cannot be used with distinct/); - done(); - }); - - it('batchSize', function(done) { - assert.throws(function() { - mquery({}, { batchSize: 3 }).distinct(); - }, /batchSize cannot be used with distinct/); - done(); - }); - - it('comment', function(done) { - assert.throws(function() { - mquery().comment('mquery').distinct(); - }, /comment cannot be used with distinct/); - done(); - }); - - it('maxScan', function(done) { - assert.throws(function() { - mquery().maxScan(300).distinct(); - }, /maxScan cannot be used with distinct/); - done(); - }); - - it('snapshot', function(done) { - assert.throws(function() { - mquery().snapshot().distinct(); - }, /snapshot cannot be used with distinct/); - done(); - }); - - it('hint', function(done) { - assert.throws(function() { - mquery().hint({ x: 1 }).distinct(); - }, /hint cannot be used with distinct/); - done(); - }); - - it('tailable', function(done) { - assert.throws(function() { - 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, res) { - id = res.insertedIds[0]; - 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, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - 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) { - 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) { - 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, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - 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) { - 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, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - 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, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - 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!')); - }; - - 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() { - mquery().sort('x')[method](); - }); - done(); - }); - - it('select', function(done) { - assert.doesNotThrow(function() { - mquery().select('x')[method](); - }); - done(); - }); - - it('limit', function(done) { - assert.throws(function() { - mquery().limit(3)[method](); - }, new RegExp('limit cannot be used with ' + method)); - done(); - }); - - it('skip', function(done) { - assert.throws(function() { - mquery().skip(3)[method](); - }, new RegExp('skip cannot be used with ' + method)); - done(); - }); - - it('batchSize', function(done) { - assert.throws(function() { - mquery({}, { batchSize: 3 })[method](); - }, new RegExp('batchSize cannot be used with ' + method)); - done(); - }); - - it('maxScan', function(done) { - assert.throws(function() { - mquery().maxScan(300)[method](); - }, new RegExp('maxScan cannot be used with ' + method)); - done(); - }); - - it('snapshot', function(done) { - assert.throws(function() { - mquery().snapshot()[method](); - }, new RegExp('snapshot cannot be used with ' + method)); - done(); - }); - - it('hint', function(done) { - assert.throws(function() { - mquery().hint({ x: 1 })[method](); - }, new RegExp('hint cannot be used with ' + method)); - done(); - }); - - it('tailable', function(done) { - assert.throws(function() { - mquery().tailable()[method](); - }, new RegExp('tailable cannot be used with ' + method)); - done(); - }); - - it('comment', function(done) { - assert.throws(function() { - 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, res) { - assert.ifError(err); - assert.ok(res.value); - assert.equal(name, res.value.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 }}, { new: true }, function(err, res) { - assert.ifError(err); - assert.equal(10, res.value.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 }, { new: true }, function(err, res) { - assert.ifError(err); - assert.ok(res.value); - assert.equal(name, res.value.name); - assert.ok(true === res.value.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, res) { - assert.ifError(err); - assert.ok(res.value); - assert.equal(name, res.value.name); - assert.ok(true === res.value.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, res) { - assert.ifError(err); - assert.ok(res.value); - assert.equal(name, res.value.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, res) { - assert.ifError(err); - assert.equal(name, res.value.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, res) { - assert.ifError(err); - assert.equal(name, res.value.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, res) { - assert.ifError(err); - assert.ok(res.value); - assert.equal(name, res.value.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) { - done(e.code === 'MODULE_NOT_FOUND' ? null : e); - return; - } - m.exec(function(err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }); - }); - - it('works with hint', function(done) { - mquery(col).hint({ _id: 1 }).find({ name: 'exec' }).exec(function(err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - - mquery(col).hint('_id_').find({ age: 1 }).exec(function(err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }); - }); - }); - - it('works with readConcern', function(done) { - var m = mquery(col).find({ name: 'exec' }); - m.readConcern('l'); - m.exec(function(err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }); - }); - - it('works with collation', function(done) { - var m = mquery(col).find({ name: 'EXEC' }); - m.collation({ locale: 'en_US', strength: 1 }); - 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.result.n); - mquery(col).find({ name: 'exec + update' }, function(err, docs) { - assert.ifError(err); - assert.equal(num, docs.length); - done(); - }); - }); - }); - }); - - describe('updateMany', function() { - it('works', function(done) { - mquery(col).updateMany({ name: 'exec' }, { name: 'test' }). - exec(function(error) { - assert.ifError(error); - mquery(col).count({ name: 'test' }).exec(function(error, res) { - assert.ifError(error); - assert.equal(res, 2); - done(); - }); - }); - }); - it('works with write concern', function(done) { - mquery(col).updateMany({ name: 'exec' }, { name: 'test' }) - .w(1).j(true).wtimeout(1000) - .exec(function(error) { - assert.ifError(error); - mquery(col).count({ name: 'test' }).exec(function(error, res) { - assert.ifError(error); - assert.equal(res, 2); - done(); - }); - }); - }); - }); - - describe('updateOne', function() { - it('works', function(done) { - mquery(col).updateOne({ name: 'exec' }, { name: 'test' }). - exec(function(error) { - assert.ifError(error); - mquery(col).count({ name: 'test' }).exec(function(error, res) { - assert.ifError(error); - assert.equal(res, 1); - done(); - }); - }); - }); - }); - - describe('replaceOne', function() { - it('works', function(done) { - mquery(col).replaceOne({ name: 'exec' }, { name: 'test' }). - exec(function(error) { - assert.ifError(error); - mquery(col).findOne({ name: 'test' }).exec(function(error, res) { - assert.ifError(error); - assert.equal(res.name, 'test'); - assert.ok(res.age == null); - 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, res) { - assert.ifError(err); - assert.equal(1, res.result.n); - 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('deleteOne', function() { - it('with a callback', function(done) { - var m = mquery(col).where({ age: { $gte: 0 } }).deleteOne(); - m.exec(function(err, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - done(); - }); - }); - - it('with justOne set', function(done) { - var m = mquery(col).where({ age: { $gte: 0 } }). - // Should ignore `justOne` - setOptions({ justOne: false }). - deleteOne(); - m.exec(function(err, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - done(); - }); - }); - }); - - describe('deleteMany', function() { - it('with a callback', function(done) { - var m = mquery(col).where({ age: { $gte: 0 } }).deleteMany(); - m.exec(function(err, res) { - assert.ifError(err); - assert.equal(res.result.n, 2); - done(); - }); - }); - }); - - 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, res) { - assert.ifError(err); - assert.equal('findOneAndUpdate', res.value.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, res) { - assert.ifError(err); - assert.equal('exec', res.value.name); - assert.equal(2, res.value.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); - assert.ok(typeof millis === 'number'); - } 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 exec() cb being called synchronously #66', function(done) { - var query = mquery(col).count({ name: 'then' }); - query.exec = function(cb) { - cb(null, 66); - }; - - query.then(success, done); - function success(count) { - assert.equal(66, count); - 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('end', function() { - if (err) return done(err); - assert.equal(2, 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 = []; - var key; - for (key in q._update.$push.n) { - order.push(key); - } - - // compare output - var doc = q._updateForExec(); - var i = 0; - for (key in doc.$push.n) { - assert.equal(key, order[i]); - i++; - } - - done(); - }); - }); -}); diff --git a/node_modules/mquery/test/utils.test.js b/node_modules/mquery/test/utils.test.js deleted file mode 100644 index ff95f3322fceadd0cc43ad31df2047716eff4bba..0000000000000000000000000000000000000000 --- a/node_modules/mquery/test/utils.test.js +++ /dev/null @@ -1,144 +0,0 @@ -'use strict'; - -var Buffer = require('safe-buffer').Buffer; -var utils = require('../lib/utils'); -var assert = require('assert'); -var debug = require('debug'); - -var mongo; -try { - mongo = new require('mongodb'); -} catch (e) { - debug('mongo', 'cannot construct mongodb instance'); -} - -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('secondary', tags) - ]; - - var prefsCloned = utils.clone(prefs); - - for (var i = 0; i < prefsCloned.length; i++) { - assert.notEqual(prefs[i], prefsCloned[i]); - 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 = Buffer.from('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 = Buffer.alloc(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/mysql/Changes.md b/node_modules/mysql/Changes.md new file mode 100644 index 0000000000000000000000000000000000000000..ba51bb7fed797ef819511627c547e02b51ef62b8 --- /dev/null +++ b/node_modules/mysql/Changes.md @@ -0,0 +1,536 @@ +# Changes + +This file is a manually maintained list of changes for each release. Feel free +to add your changes here when sending pull requests. Also send corrections if +you spot any mistakes. + +## v2.16.0 (2018-07-17) + +* Add Amazon RDS GovCloud SSL certificates #1876 +* Add new error codes up to MySQL 5.7.21 +* Include connection ID in debug output +* Support Node.js 9.x +* Support Node.js 10.x #2003 #2024 #2026 #2034 +* Update Amazon RDS SSL certificates +* Update `bignumber.js` to 4.1.0 +* Update `readable-stream` to 2.3.6 +* Update `sqlstring` to 2.3.1 + - Fix incorrectly replacing non-placeholders in SQL + +## v2.15.0 (2017-10-05) + +* Add new Amazon RDS ca-central-1 certificate CA to Amazon RDS SSL profile #1809 +* Add new error codes up to MySQL 5.7.19 +* Add `mysql.raw()` to generate pre-escaped values #877 #1821 +* Fix "changedRows" to work on non-English servers #1819 +* Fix error when server sends RST on `QUIT` #1811 +* Fix typo in insecure auth error message +* Support `mysql_native_password` auth switch request for Azure #1396 #1729 #1730 +* Update `sqlstring` to 2.3.0 + - Add `.toSqlString()` escape overriding + - Small performance improvement on `escapeId` +* Update `bignumber.js` to 4.0.4 + +## v2.14.1 (2017-08-01) + +* Fix holding first closure for lifetime of connection #1785 + +## v2.14.0 (2017-07-25) + +* Add new Amazon RDS ap-south-1 certificate CA to Amazon RDS SSL profile #1780 +* Add new Amazon RDS eu-west-2 certificate CA to Amazon RDS SSL profile #1770 +* Add `sql` property to query `Error` objects #1462 #1628 #1629 +* Add `sqlMessage` property to `Error` objects #1714 +* Fix the MySQL 5.7.17 error codes +* Support Node.js 8.x +* Update `bignumber.js` to 4.0.2 +* Update `readable-stream` to 2.3.3 +* Use `safe-buffer` for improved Buffer API + +## v2.13.0 (2017-01-24) + +* Accept regular expression as pool cluster pattern #1572 +* Accept wildcard anywhere in pool cluster pattern #1570 +* Add `acquire` and `release` events to `Pool` for tracking #1366 #1449 #1528 #1625 +* Add new error codes up to MySQL 5.7.17 +* Fix edge cases when determing Query result packets #1547 +* Fix memory leak when using long-running domains #1619 #1620 +* Remove unnecessary buffer copies when receiving large packets +* Update `bignumber.js` to 3.1.2 +* Use a simple buffer list to improve performance #566 #1590 + +## v2.12.0 (2016-11-02) + +* Accept array of type names to `dateStrings` option #605 #1481 +* Add `query` method to `PoolNamespace` #1256 #1505 #1506 + - Used as `cluster.of(...).query(...)` +* Add new error codes up to MySQL 5.7.16 +* Fix edge cases writing certain length coded values +* Fix typo in `HANDSHAKE_NO_SSL_SUPPORT` error message #1534 +* Support Node.js 7.x +* Update `bignumber.js` to 2.4.0 +* Update `sqlstring` to 2.2.0 + - Accept numbers and other value types in `escapeId` + - Escape invalid `Date` objects as `NULL` + - Run `buffer.toString()` through escaping + +## v2.11.1 (2016-06-07) + +* Fix writing truncated packets starting with large string/buffer #1438 + +## v2.11.0 (2016-06-06) + +* Add `POOL_CLOSED` code to "Pool is closed." error +* Add `POOL_CONNLIMIT` code to "No connections available." error #1332 +* Bind underlying connections in pool to same domain as pool #1242 +* Bind underlying socket to same domain as connection #1243 +* Fix allocation errors receiving many result rows #918 #1265 #1324 #1415 +* Fix edge cases constructing long stack traces #1387 +* Fix handshake inactivity timeout on Node.js v4.2.0 #1223 #1236 #1239 #1240 #1241 #1252 +* Fix Query stream to emit close after ending #1349 #1350 +* Fix type cast for BIGINT columns when number is negative #1376 +* Performance improvements for array/object escaping in SqlString #1331 +* Performance improvements for formatting in SqlString #1431 +* Performance improvements for string escaping in SqlString #1390 +* Performance improvements for writing packets to network +* Support Node.js 6.x +* Update `bignumber.js` to 2.3.0 +* Update `readable-stream` to 1.1.14 +* Use the `sqlstring` module for SQL escaping and formatting + +## v2.10.2 (2016-01-12) + +* Fix exception/hang from certain SSL connection errors #1153 +* Update `bignumber.js` to 2.1.4 + +## v2.10.1 (2016-01-11) + +* Add new Amazon RDS ap-northeast-2 certificate CA to Amazon RDS SSL profile #1329 + +## v2.10.0 (2015-12-15) + +* Add new error codes up to MySQL 5.7.9 #1294 +* Add new JSON type constant #1295 +* Add types for fractional seconds support +* Fix `connection.destroy()` on pool connection creating sequences #1291 +* Fix error code 139 `HA_ERR_TO_BIG_ROW` to be `HA_ERR_TOO_BIG_ROW` +* Fix error when call site error is missing stack #1179 +* Fix reading password from MySQL URL that has bare colon #1278 +* Handle MySQL servers not closing TCP connection after QUIT -> OK exchange #1277 +* Minor SqlString Date to string performance improvement #1233 +* Support Node.js 4.x +* Support Node.js 5.x +* Update `bignumber.js` to 2.1.2 + +## v2.9.0 (2015-08-19) + +* Accept the `ciphers` property in connection `ssl` option #1185 +* Fix bad timezone conversion from `Date` to string for certain times #1045 #1155 + +## v2.8.0 (2015-07-13) + +* Add `connect` event to `Connection` #1129 +* Default `timeout` for `connection.end` to 30 seconds #1057 +* Fix a sync callback when sequence enqueue fails #1147 +* Provide static require analysis +* Re-use connection from pool after `conn.changeUser` is used #837 #1088 + +## v2.7.0 (2015-05-27) + +* Destroy/end connections removed from the pool on error +* Delay implied connect until after `.query` argument validation +* Do not remove connections with non-fatal errors from the pool +* Error early if `callback` argument to `.query` is not a function #1060 +* Lazy-load modules from many entry point; reduced memory use + +## v2.6.2 (2015-04-14) + +* Fix `Connection.createQuery` for no SQL #1058 +* Update `bignumber.js` to 2.0.7 + +## v2.6.1 (2015-03-26) + +* Update `bignumber.js` to 2.0.5 #1037 #1038 + +## v2.6.0 (2015-03-24) + +* Add `poolCluster.remove` to remove pools from the cluster #1006 #1007 +* Add optional callback to `poolCluster.end` +* Add `restoreNodeTimeout` option to `PoolCluster` #880 #906 +* Fix LOAD DATA INFILE handling in multiple statements #1036 +* Fix `poolCluster.add` to throw if `PoolCluster` has been closed +* Fix `poolCluster.add` to throw if `id` already defined +* Fix un-catchable error from `PoolCluster` when MySQL server offline #1033 +* Improve speed formatting SQL #1019 +* Support io.js + +## v2.5.5 (2015-02-23) + +* Store SSL presets in JS instead of JSON #959 +* Support Node.js 0.12 +* Update Amazon RDS SSL certificates #1001 + +## v2.5.4 (2014-12-16) + +* Fix error if falsy error thrown in callback handler #960 +* Fix various error code strings #954 + +## v2.5.3 (2014-11-06) + +* Fix `pool.query` streaming interface not emitting connection errors #941 + +## v2.5.2 (2014-10-10) + +* Fix receiving large text fields #922 + +## v2.5.1 (2014-09-22) + +* Fix `pool.end` race conditions #915 +* Fix `pool.getConnection` race conditions + +## v2.5.0 (2014-09-07) + +* Add code `POOL_ENQUEUELIMIT` to error reaching `queueLimit` +* Add `enqueue` event to pool #716 +* Add `enqueue` event to protocol and connection #381 +* Blacklist unsupported connection flags #881 +* Make only column names enumerable in `RowDataPacket` #549 #895 +* Support Node.js 0.6 #718 + +## v2.4.3 (2014-08-25) + +* Fix `pool.query` to use `typeCast` configuration + +## v2.4.2 (2014-08-03) + +* Fix incorrect sequence packet errors to be catchable #867 +* Fix stray protocol packet errors to be catchable #867 +* Fix timing of fatal protocol errors bubbling to user #879 + +## v2.4.1 (2014-07-17) + +* Fix `pool.query` not invoking callback on connection error #872 + +## v2.4.0 (2014-07-13) + +* Add code `POOL_NOEXIST` in PoolCluster error #846 +* Add `acquireTimeout` pool option to specify a timeout for acquiring a connection #821 #854 +* Add `connection.escapeId` +* Add `pool.escapeId` +* Add `timeout` option to all sequences #855 #863 +* Default `connectTimeout` to 10 seconds +* Fix domain binding with `conn.connect` +* Fix `packet.default` to actually be a string +* Fix `PARSER_*` errors to be catchable +* Fix `PROTOCOL_PACKETS_OUT_OF_ORDER` error to be catchable #844 +* Include packets that failed parsing under `debug` +* Return `Query` object from `pool.query` like `conn.query` #830 +* Use `EventEmitter.listenerCount` when possible for faster counting + +## v2.3.2 (2014-05-29) + +* Fix pool leaking connections after `conn.changeUser` #833 + +## v2.3.1 (2014-05-26) + +* Add database errors to error constants +* Add global errors to error constants +* Throw when calling `conn.release` multiple times #824 #827 +* Update known error codes + +## v2.3.0 (2014-05-16) + +* Accept MySQL charset (like `UTF8` or `UTF8MB4`) in `charset` option #808 +* Accept pool options in connection string to `mysql.createPool` #811 +* Clone connection config for new pool connections +* Default `connectTimeout` to 2 minutes +* Reject unauthorized SSL connections (use `ssl.rejectUnauthorized` to override) #816 +* Return last error when PoolCluster exhausts connection retries #818 +* Remove connection from pool after `conn.changeUser` is released #806 +* Throw on unknown SSL profile name #817 +* User newer TLS functions when available #809 + +## v2.2.0 (2014-04-27) + +* Use indexOf instead of for loops removing conn from pool #611 +* Make callback to `pool.query` optional like `conn.query` #585 +* Prevent enqueuing sequences after fatal error #400 +* Fix geometry parser for empty fields #742 +* Accept lower-case charset option +* Throw on unknown charset option #789 +* Update known charsets +* Remove console.warn from PoolCluster #744 +* Fix `pool.end` to handle queued connections #797 +* Fix `pool.releaseConnection` to keep connection queue flowing #797 +* Fix SSL handshake error to be catchable #800 +* Add `connection.threadId` to get MySQL connection ID #602 +* Ensure `pool.getConnection` retrieves good connections #434 #557 #778 +* Fix pool cluster wildcard matching #627 +* Pass query values through to `SqlString.format` #590 + +## v2.1.1 (2014-03-13) + +* fix authentication w/password failure for node.js 0.10.5 #746 #752 +* fix authentication w/password TypeError exception for node.js 0.10.0-0.10.4 #747 +* fix specifying `values` in `conn.query({...}).on(...)` pattern #755 +* fix long stack trace to include the `pool.query(...)` call #715 + +## v2.1.0 (2014-02-20) + +* crypto.createHash fix for node.js < 11 #735 +* Add `connectTimeout` option to specify a timeout for establishing a connection #726 +* SSL support #481 + +## v2.0.1 + +* internal parser speed improvement #702 +* domains support +* 'trace' connection option to control if long stack traces are generated #713 #710 #439 + +## v2.0.0 (2014-01-09) + +* stream improvements: + - node 0.8 support #692 + - Emit 'close' events from query streams #688 +* encoding fix in streaming LOAD DATA LOCAL INFILE #670 +* Doc improvements + +## v2.0.0-rc2 (2013-12-07) + +* Streaming LOAD DATA LOCAL INFILE #668 +* Doc improvements + +## v2.0.0-rc1 (2013-11-30) + +* Transaction support +* Expose SqlString.format as mysql.format() +* Many bug fixes +* Better support for dates in local time zone +* Doc improvements + +## v2.0.0-alpha9 (2013-08-27) + +* Add query to pool to execute queries directly using the pool +* Add `sqlState` property to `Error` objects #556 +* Pool option to set queue limit +* Pool sends 'connection' event when it opens a new connection +* Added stringifyObjects option to treat input as strings rather than objects (#501) +* Support for poolClusters +* Datetime improvements +* Bug fixes + +## v2.0.0-alpha8 (2013-04-30) + +* Switch to old mode for Streams 2 (Node.js v 0.10.x) +* Add stream method to Query Wraps events from the query object into a node v0.10.x Readable stream +* DECIMAL should also be treated as big number +* Removed slow unnecessary stack access +* Added charsets +* Added bigNumberStrings option for forcing BIGINT columns as strings +* Changes date parsing to return String if not a valid JS Date +* Adds support for ?? escape sequence to escape identifiers +* Changes Auth.token() to force password to be in binary, not utf8 (#378) +* Restrict debugging by packet types +* Add 'multipleStatements' option tracking to ConnectionConfig. Fixes GH-408 +* Changes Pool to handle 'error' events and dispose connection +* Allows db.query({ sql: "..." }, [ val1, ... ], cb); (#390) +* Improved documentation +* Bug fixes + +## v2.0.0-alpha7 (2013-02-03) + +* Add connection pooling (#351) + +## v2.0.0-alpha6 (2013-01-31) + +* Add supportBigNumbers option (#381, #382) +* Accept prebuilt Query object in connection.query +* Bug fixes + +## v2.0.0-alpha5 (2012-12-03) + +* Add mysql.escapeId to escape identifiers (closes #342) +* Allow custom escaping mode (config.queryFormat) +* Convert DATE columns to configured timezone instead of UTC (#332) +* Convert LONGLONG and NEWDECIMAL to numbers (#333) +* Fix Connection.escape() (fixes #330) +* Changed Readme ambiguity about custom type cast fallback +* Change typeCast to receive Connection instead of Connection.config.timezone +* Fix drain event having useless err parameter +* Add Connection.statistics() back from v0.9 +* Add Connection.ping() back from v0.9 + +## v2.0.0-alpha4 (2012-10-03) + +* Fix some OOB errors on resume() +* Fix quick pause() / resume() usage +* Properly parse host denied / similar errors +* Add Connection.ChangeUser functionality +* Make sure changeUser errors are fatal +* Enable formatting nested arrays for bulk inserts +* Add Connection.escape functionality +* Renamed 'close' to 'end' event +* Return parsed object instead of Buffer for GEOMETRY types +* Allow nestTables inline (using a string instead of a boolean) +* Check for ZEROFILL_FLAG and format number accordingly +* Add timezone support (default: local) +* Add custom typeCast functionality +* Export mysql column types +* Add connection flags functionality (#237) +* Exports drain event when queue finishes processing (#272, #271, #306) + +## v2.0.0-alpha3 (2012-06-12) + +* Implement support for `LOAD DATA LOCAL INFILE` queries (#182). +* Support OLD\_PASSWORD() accounts like 0.9.x did. You should still upgrade any + user accounts in your your MySQL user table that has short (16 byte) Password + values. Connecting to those accounts is not secure. (#204) +* Ignore function values when escaping objects, allows to use RowDataPacket + objects as query arguments. (Alex Gorbatchev, #213) +* Handle initial error packets from server such as `ER_HOST_NOT_PRIVILEGED`. +* Treat `utf8\_bin` as a String, not Buffer. (#214) +* Handle empty strings in first row column value. (#222) +* Honor Connection#nestTables setting for queries. (#221) +* Remove `CLIENT_INTERACTIVE` flag from config. Improves #225. +* Improve docs for connections settings. +* Implement url string support for Connection configs. + +## v2.0.0-alpha2 (2012-05-31) + +* Specify escaping before for NaN / Infinity (they are as unquoted constants). +* Support for unix domain socket connections (use: {socketPath: '...'}). +* Fix type casting for NULL values for Date/Number fields +* Add `fields` argument to `query()` as well as `'fields'` event. This is + similar to what was available in 0.9.x. +* Support connecting to the sphinx searchd daemon as well as MariaDB (#199). +* Implement long stack trace support, will be removed / disabled if the node + core ever supports it natively. +* Implement `nestTables` option for queries, allows fetching JOIN result sets + with overlapping column names. +* Fix ? placeholder mechanism for values containing '?' characters (#205). +* Detect when `connect()` is called more than once on a connection and provide + the user with a good error message for it (#204). +* Switch to `UTF8_GENERAL_CI` (previously `UTF8_UNICODE_CI`) as the default + charset for all connections to avoid strange MySQL performance issues (#200), + and also make the charset user configurable. +* Fix BLOB type casting for `TINY_BLOB`, `MEDIUM_BLOB` and `LONG_BLOB`. +* Add support for sending and receiving large (> 16 MB) packets. + +## v2.0.0-alpha (2012-05-15) + +This release is a rewrite. You should carefully test your application after +upgrading to avoid problems. This release features many improvements, most +importantly: + +* ~5x faster than v0.9.x for parsing query results +* Support for pause() / resume() (for streaming rows) +* Support for multiple statement queries +* Support for stored procedures +* Support for transactions +* Support for binary columns (as blobs) +* Consistent & well documented error handling +* A new Connection class that has well defined semantics (unlike the old Client class). +* Convenient escaping of objects / arrays that allows for simpler query construction +* A significantly simpler code base +* Many bug fixes & other small improvements (Closed 62 out of 66 GitHub issues) + +Below are a few notes on the upgrade process itself: + +The first thing you will run into is that the old `Client` class is gone and +has been replaced with a less ambitious `Connection` class. So instead of +`mysql.createClient()`, you now have to: + +```js +var mysql = require('mysql'); +var connection = mysql.createConnection({ + host : 'localhost', + user : 'me', + password : 'secret', +}); + +connection.query('SELECT 1', function(err, rows) { + if (err) throw err; + + console.log('Query result: ', rows); +}); + +connection.end(); +``` + +The new `Connection` class does not try to handle re-connects, please study the +`Server disconnects` section in the new Readme. + +Other than that, the interface has stayed very similar. Here are a few things +to check out so: + +* BIGINT's are now cast into strings +* Binary data is now cast to buffers +* The `'row'` event on the `Query` object is now called `'result'` and will + also be emitted for queries that produce an OK/Error response. +* Error handling is consistently defined now, check the Readme +* Escaping has become more powerful which may break your code if you are + currently using objects to fill query placeholders. +* Connections can now be established explicitly again, so you may wish to do so + if you want to handle connection errors specifically. + +That should be most of it, if you run into anything else, please send a patch +or open an issue to improve this document. + +## v0.9.6 (2012-03-12) + +* Escape array values so they produce sql arrays (Roger Castells, Colin Smith) +* docs: mention mysql transaction stop gap solution (Blake Miner) +* docs: Mention affectedRows in FAQ (Michael Baldwin) + +## v0.9.5 (2011-11-26) + +* Fix #142 Driver stalls upon reconnect attempt that's immediately closed +* Add travis build +* Switch to urun as a test runner +* Switch to utest for unit tests +* Remove fast-or-slow dependency for tests +* Split integration tests into individual files again + +## v0.9.4 (2011-08-31) + +* Expose package.json as `mysql.PACKAGE` (#104) + +## v0.9.3 (2011-08-22) + +* Set default `client.user` to root +* Fix #91: Client#format should not mutate params array +* Fix #94: TypeError in client.js +* Parse decimals as string (vadimg) + +## v0.9.2 (2011-08-07) + +* The underlaying socket connection is now managed implicitly rather than explicitly. +* Check the [upgrading guide][] for a full list of changes. + +## v0.9.1 (2011-02-20) + +* Fix issue #49 / `client.escape()` throwing exceptions on objects. (Nick Payne) +* Drop < v0.4.x compatibility. From now on you need node v0.4.x to use this module. + +## Older releases + +These releases were done before maintaining this file: + +* [v0.9.0](https://github.com/mysqljs/mysql/compare/v0.8.0...v0.9.0) + (2011-01-04) +* [v0.8.0](https://github.com/mysqljs/mysql/compare/v0.7.0...v0.8.0) + (2010-10-30) +* [v0.7.0](https://github.com/mysqljs/mysql/compare/v0.6.0...v0.7.0) + (2010-10-14) +* [v0.6.0](https://github.com/mysqljs/mysql/compare/v0.5.0...v0.6.0) + (2010-09-28) +* [v0.5.0](https://github.com/mysqljs/mysql/compare/v0.4.0...v0.5.0) + (2010-09-17) +* [v0.4.0](https://github.com/mysqljs/mysql/compare/v0.3.0...v0.4.0) + (2010-09-02) +* [v0.3.0](https://github.com/mysqljs/mysql/compare/v0.2.0...v0.3.0) + (2010-08-25) +* [v0.2.0](https://github.com/mysqljs/mysql/compare/v0.1.0...v0.2.0) + (2010-08-22) +* [v0.1.0](https://github.com/mysqljs/mysql/commits/v0.1.0) + (2010-08-22) diff --git a/node_modules/mysql/License b/node_modules/mysql/License new file mode 100644 index 0000000000000000000000000000000000000000..c7ff12a2f8af2e2c57f39da1754409c25b35f46a --- /dev/null +++ b/node_modules/mysql/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/mysql/Readme.md b/node_modules/mysql/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..5af3ed261293f6e97b3281042a2f50c49014709c --- /dev/null +++ b/node_modules/mysql/Readme.md @@ -0,0 +1,1504 @@ +# mysql + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +## Table of Contents + +- [Install](#install) +- [Introduction](#introduction) +- [Contributors](#contributors) +- [Sponsors](#sponsors) +- [Community](#community) +- [Establishing connections](#establishing-connections) +- [Connection options](#connection-options) +- [SSL options](#ssl-options) +- [Terminating connections](#terminating-connections) +- [Pooling connections](#pooling-connections) +- [Pool options](#pool-options) +- [Pool events](#pool-events) +- [Closing all the connections in a pool](#closing-all-the-connections-in-a-pool) +- [PoolCluster](#poolcluster) +- [PoolCluster options](#poolcluster-options) +- [Switching users and altering connection state](#switching-users-and-altering-connection-state) +- [Server disconnects](#server-disconnects) +- [Performing queries](#performing-queries) +- [Escaping query values](#escaping-query-values) +- [Escaping query identifiers](#escaping-query-identifiers) +- [Preparing Queries](#preparing-queries) +- [Custom format](#custom-format) +- [Getting the id of an inserted row](#getting-the-id-of-an-inserted-row) +- [Getting the number of affected rows](#getting-the-number-of-affected-rows) +- [Getting the number of changed rows](#getting-the-number-of-changed-rows) +- [Getting the connection ID](#getting-the-connection-id) +- [Executing queries in parallel](#executing-queries-in-parallel) +- [Streaming query rows](#streaming-query-rows) +- [Piping results with Streams](#piping-results-with-streams) +- [Multiple statement queries](#multiple-statement-queries) +- [Stored procedures](#stored-procedures) +- [Joins with overlapping column names](#joins-with-overlapping-column-names) +- [Transactions](#transactions) +- [Ping](#ping) +- [Timeouts](#timeouts) +- [Error handling](#error-handling) +- [Exception Safety](#exception-safety) +- [Type casting](#type-casting) +- [Connection Flags](#connection-flags) +- [Debugging and reporting problems](#debugging-and-reporting-problems) +- [Security issues](#security-issues) +- [Contributing](#contributing) +- [Running tests](#running-tests) +- [Todo](#todo) + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). + +Before installing, [download and install Node.js](https://nodejs.org/en/download/). +Node.js 0.6 or higher is required. + +Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mysql +``` + +For information about the previous 0.9.x releases, visit the [v0.9 branch][]. + +Sometimes I may also ask you to install the latest version from Github to check +if a bugfix is working. In this case, please do: + +```sh +$ npm install mysqljs/mysql +``` + +[v0.9 branch]: https://github.com/mysqljs/mysql/tree/v0.9 + +## Introduction + +This is a node.js driver for mysql. It is written in JavaScript, does not +require compiling, and is 100% MIT licensed. + +Here is an example on how to use it: + +```js +var mysql = require('mysql'); +var connection = mysql.createConnection({ + host : 'localhost', + user : 'me', + password : 'secret', + database : 'my_db' +}); + +connection.connect(); + +connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { + if (error) throw error; + console.log('The solution is: ', results[0].solution); +}); + +connection.end(); +``` + +From this example, you can learn the following: + +* Every method you invoke on a connection is queued and executed in sequence. +* Closing the connection is done using `end()` which makes sure all remaining + queries are executed before sending a quit packet to the mysql server. + +## Contributors + +Thanks goes to the people who have contributed code to this module, see the +[GitHub Contributors page][]. + +[GitHub Contributors page]: https://github.com/mysqljs/mysql/graphs/contributors + +Additionally I'd like to thank the following people: + +* [Andrey Hristov][] (Oracle) - for helping me with protocol questions. +* [Ulf Wendel][] (Oracle) - for helping me with protocol questions. + +[Ulf Wendel]: http://blog.ulf-wendel.de/ +[Andrey Hristov]: http://andrey.hristov.com/ + +## Sponsors + +The following companies have supported this project financially, allowing me to +spend more time on it (ordered by time of contribution): + +* [Transloadit](http://transloadit.com) (my startup, we do file uploading & + video encoding as a service, check it out) +* [Joyent](http://www.joyent.com/) +* [pinkbike.com](http://pinkbike.com/) +* [Holiday Extras](http://www.holidayextras.co.uk/) (they are [hiring](http://join.holidayextras.co.uk/)) +* [Newscope](http://newscope.com/) (they are [hiring](https://newscope.com/unternehmen/jobs/)) + +## Community + +If you'd like to discuss this module, or ask questions about it, please use one +of the following: + +* **Mailing list**: https://groups.google.com/forum/#!forum/node-mysql +* **IRC Channel**: #node.js (on freenode.net, I pay attention to any message + including the term `mysql`) + +## Establishing connections + +The recommended way to establish a connection is this: + +```js +var mysql = require('mysql'); +var connection = mysql.createConnection({ + host : 'example.org', + user : 'bob', + password : 'secret' +}); + +connection.connect(function(err) { + if (err) { + console.error('error connecting: ' + err.stack); + return; + } + + console.log('connected as id ' + connection.threadId); +}); +``` + +However, a connection can also be implicitly established by invoking a query: + +```js +var mysql = require('mysql'); +var connection = mysql.createConnection(...); + +connection.query('SELECT 1', function (error, results, fields) { + if (error) throw error; + // connected! +}); +``` + +Depending on how you like to handle your errors, either method may be +appropriate. Any type of connection error (handshake or network) is considered +a fatal error, see the [Error Handling](#error-handling) section for more +information. + +## Connection options + +When establishing a connection, you can set the following options: + +* `host`: The hostname of the database you are connecting to. (Default: + `localhost`) +* `port`: The port number to connect to. (Default: `3306`) +* `localAddress`: The source IP address to use for TCP connection. (Optional) +* `socketPath`: The path to a unix domain socket to connect to. When used `host` + and `port` are ignored. +* `user`: The MySQL user to authenticate as. +* `password`: The password of that MySQL user. +* `database`: Name of the database to use for this connection (Optional). +* `charset`: The charset for the connection. This is called "collation" in the SQL-level + of MySQL (like `utf8_general_ci`). If a SQL-level charset is specified (like `utf8mb4`) + then the default collation for that charset is used. (Default: `'UTF8_GENERAL_CI'`) +* `timezone`: The timezone configured on the MySQL server. This is used to type cast server date/time values to JavaScript `Date` object and vice versa. This can be `'local'`, `'Z'`, or an offset in the form `+HH:MM` or `-HH:MM`. (Default: `'local'`) +* `connectTimeout`: The milliseconds before a timeout occurs during the initial connection + to the MySQL server. (Default: `10000`) +* `stringifyObjects`: Stringify objects instead of converting to values. See +issue [#501](https://github.com/mysqljs/mysql/issues/501). (Default: `false`) +* `insecureAuth`: Allow connecting to MySQL instances that ask for the old + (insecure) authentication method. (Default: `false`) +* `typeCast`: Determines if column values should be converted to native + JavaScript types. (Default: `true`) +* `queryFormat`: A custom query format function. See [Custom format](#custom-format). +* `supportBigNumbers`: When dealing with big numbers (BIGINT and DECIMAL columns) in the database, + you should enable this option (Default: `false`). +* `bigNumberStrings`: Enabling both `supportBigNumbers` and `bigNumberStrings` forces big numbers + (BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default: `false`). + Enabling `supportBigNumbers` but leaving `bigNumberStrings` disabled will return big numbers as String + objects only when they cannot be accurately represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5) + (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as + Number objects. This option is ignored if `supportBigNumbers` is disabled. +* `dateStrings`: Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then + inflated into JavaScript Date objects. Can be `true`/`false` or an array of type names to keep as + strings. (Default: `false`) +* `debug`: Prints protocol details to stdout. Can be `true`/`false` or an array of packet type names + that should be printed. (Default: `false`) +* `trace`: Generates stack traces on `Error` to include call site of library + entrance ("long stack traces"). Slight performance penalty for most calls. + (Default: `true`) +* `multipleStatements`: Allow multiple mysql statements per query. Be careful + with this, it could increase the scope of SQL injection attacks. (Default: `false`) +* `flags`: List of connection flags to use other than the default ones. It is + also possible to blacklist default ones. For more information, check + [Connection Flags](#connection-flags). +* `ssl`: object with ssl parameters or a string containing name of ssl profile. See [SSL options](#ssl-options). + + +In addition to passing these options as an object, you can also use a url +string. For example: + +```js +var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700'); +``` + +Note: The query values are first attempted to be parsed as JSON, and if that +fails assumed to be plaintext strings. + +### SSL options + +The `ssl` option in the connection options takes a string or an object. When given a string, +it uses one of the predefined SSL profiles included. The following profiles are included: + +* `"Amazon RDS"`: this profile is for connecting to an Amazon RDS server and contains the + certificates from https://rds.amazonaws.com/doc/rds-ssl-ca-cert.pem and + https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem + +When connecting to other servers, you will need to provide an object of options, in the +same format as [tls.createSecureContext](https://nodejs.org/api/tls.html#tls_tls_createsecurecontext_options). +Please note the arguments expect a string of the certificate, not a file name to the +certificate. Here is a simple example: + +```js +var connection = mysql.createConnection({ + host : 'localhost', + ssl : { + ca : fs.readFileSync(__dirname + '/mysql-ca.crt') + } +}); +``` + +You can also connect to a MySQL server without properly providing the appropriate +CA to trust. _You should not do this_. + +```js +var connection = mysql.createConnection({ + host : 'localhost', + ssl : { + // DO NOT DO THIS + // set up your ca correctly to trust the connection + rejectUnauthorized: false + } +}); +``` + +## Terminating connections + +There are two ways to end a connection. Terminating a connection gracefully is +done by calling the `end()` method: + +```js +connection.end(function(err) { + // The connection is terminated now +}); +``` + +This will make sure all previously enqueued queries are still before sending a +`COM_QUIT` packet to the MySQL server. If a fatal error occurs before the +`COM_QUIT` packet can be sent, an `err` argument will be provided to the +callback, but the connection will be terminated regardless of that. + +An alternative way to end the connection is to call the `destroy()` method. +This will cause an immediate termination of the underlying socket. +Additionally `destroy()` guarantees that no more events or callbacks will be +triggered for the connection. + +```js +connection.destroy(); +``` + +Unlike `end()` the `destroy()` method does not take a callback argument. + +## Pooling connections + +Rather than creating and managing connections one-by-one, this module also +provides built-in connection pooling using `mysql.createPool(config)`. +[Read more about connection pooling](https://en.wikipedia.org/wiki/Connection_pool). + +Create a pool and use it directly: + +```js +var mysql = require('mysql'); +var pool = mysql.createPool({ + connectionLimit : 10, + host : 'example.org', + user : 'bob', + password : 'secret', + database : 'my_db' +}); + +pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) { + if (error) throw error; + console.log('The solution is: ', results[0].solution); +}); +``` + +This is a shortcut for the `pool.getConnection()` -> `connection.query()` -> +`connection.release()` code flow. Using `pool.getConnection()` is useful to +share connection state for subsequent queries. This is because two calls to +`pool.query()` may use two different connections and run in parallel. This is +the basic structure: + +```js +var mysql = require('mysql'); +var pool = mysql.createPool(...); + +pool.getConnection(function(err, connection) { + if (err) throw err; // not connected! + + // Use the connection + connection.query('SELECT something FROM sometable', function (error, results, fields) { + // When done with the connection, release it. + connection.release(); + + // Handle error after the release. + if (error) throw error; + + // Don't use the connection here, it has been returned to the pool. + }); +}); +``` + +If you would like to close the connection and remove it from the pool, use +`connection.destroy()` instead. The pool will create a new connection the next +time one is needed. + +Connections are lazily created by the pool. If you configure the pool to allow +up to 100 connections, but only ever use 5 simultaneously, only 5 connections +will be made. Connections are also cycled round-robin style, with connections +being taken from the top of the pool and returning to the bottom. + +When a previous connection is retrieved from the pool, a ping packet is sent +to the server to check if the connection is still good. + +## Pool options + +Pools accept all the same [options as a connection](#connection-options). +When creating a new connection, the options are simply passed to the connection +constructor. In addition to those options pools accept a few extras: + +* `acquireTimeout`: The milliseconds before a timeout occurs during the connection + acquisition. This is slightly different from `connectTimeout`, because acquiring + a pool connection does not always involve making a connection. (Default: `10000`) +* `waitForConnections`: Determines the pool's action when no connections are + available and the limit has been reached. If `true`, the pool will queue the + connection request and call it when one becomes available. If `false`, the + pool will immediately call back with an error. (Default: `true`) +* `connectionLimit`: The maximum number of connections to create at once. + (Default: `10`) +* `queueLimit`: The maximum number of connection requests the pool will queue + before returning an error from `getConnection`. If set to `0`, there is no + limit to the number of queued connection requests. (Default: `0`) + +## Pool events + +### acquire + +The pool will emit an `acquire` event when a connection is acquired from the pool. +This is called after all acquiring activity has been performed on the connection, +right before the connection is handed to the callback of the acquiring code. + +```js +pool.on('acquire', function (connection) { + console.log('Connection %d acquired', connection.threadId); +}); +``` + +### connection + +The pool will emit a `connection` event when a new connection is made within the pool. +If you need to set session variables on the connection before it gets used, you can +listen to the `connection` event. + +```js +pool.on('connection', function (connection) { + connection.query('SET SESSION auto_increment_increment=1') +}); +``` + +### enqueue + +The pool will emit an `enqueue` event when a callback has been queued to wait for +an available connection. + +```js +pool.on('enqueue', function () { + console.log('Waiting for available connection slot'); +}); +``` + +### release + +The pool will emit a `release` event when a connection is released back to the +pool. This is called after all release activity has been performed on the connection, +so the connection will be listed as free at the time of the event. + +```js +pool.on('release', function (connection) { + console.log('Connection %d released', connection.threadId); +}); +``` + +## Closing all the connections in a pool + +When you are done using the pool, you have to end all the connections or the +Node.js event loop will stay active until the connections are closed by the +MySQL server. This is typically done if the pool is used in a script or when +trying to gracefully shutdown a server. To end all the connections in the +pool, use the `end` method on the pool: + +```js +pool.end(function (err) { + // all connections in the pool have ended +}); +``` + +The `end` method takes an _optional_ callback that you can use to know when +all the connections are ended. + +**Once `pool.end` is called, `pool.getConnection` and other operations +can no longer be performed.** Wait until all connections in the pool are +released before calling `pool.end`. If you use the shortcut method +`pool.query`, in place of `pool.getConnection` → `connection.query` → +`connection.release`, wait until it completes. + +`pool.end` calls `connection.end` on every active connection in the pool. +This queues a `QUIT` packet on the connection and sets a flag to prevent +`pool.getConnection` from creating new connections. All commands / queries +already in progress will complete, but new commands won't execute. + +## PoolCluster + +PoolCluster provides multiple hosts connection. (group & retry & selector) + +```js +// create +var poolCluster = mysql.createPoolCluster(); + +// add configurations (the config is a pool config object) +poolCluster.add(config); // add configuration with automatic name +poolCluster.add('MASTER', masterConfig); // add a named configuration +poolCluster.add('SLAVE1', slave1Config); +poolCluster.add('SLAVE2', slave2Config); + +// remove configurations +poolCluster.remove('SLAVE2'); // By nodeId +poolCluster.remove('SLAVE*'); // By target group : SLAVE1-2 + +// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default) +poolCluster.getConnection(function (err, connection) {}); + +// Target Group : MASTER, Selector : round-robin +poolCluster.getConnection('MASTER', function (err, connection) {}); + +// Target Group : SLAVE1-2, Selector : order +// If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster) +poolCluster.on('remove', function (nodeId) { + console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1 +}); + +// A pattern can be passed with * as wildcard +poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) {}); + +// The pattern can also be a regular expression +poolCluster.getConnection(/^SLAVE[12]$/, function (err, connection) {}); + +// of namespace : of(pattern, selector) +poolCluster.of('*').getConnection(function (err, connection) {}); + +var pool = poolCluster.of('SLAVE*', 'RANDOM'); +pool.getConnection(function (err, connection) {}); +pool.getConnection(function (err, connection) {}); +pool.query(function (error, results, fields) {}); + +// close all connections +poolCluster.end(function (err) { + // all connections in the pool cluster have ended +}); +``` + +### PoolCluster options + +* `canRetry`: If `true`, `PoolCluster` will attempt to reconnect when connection fails. (Default: `true`) +* `removeNodeErrorCount`: If connection fails, node's `errorCount` increases. + When `errorCount` is greater than `removeNodeErrorCount`, remove a node in the `PoolCluster`. (Default: `5`) +* `restoreNodeTimeout`: If connection fails, specifies the number of milliseconds + before another connection attempt will be made. If set to `0`, then node will be + removed instead and never re-used. (Default: `0`) +* `defaultSelector`: The default selector. (Default: `RR`) + * `RR`: Select one alternately. (Round-Robin) + * `RANDOM`: Select the node by random function. + * `ORDER`: Select the first node available unconditionally. + +```js +var clusterConfig = { + removeNodeErrorCount: 1, // Remove the node immediately when connection fails. + defaultSelector: 'ORDER' +}; + +var poolCluster = mysql.createPoolCluster(clusterConfig); +``` + +## Switching users and altering connection state + +MySQL offers a changeUser command that allows you to alter the current user and +other aspects of the connection without shutting down the underlying socket: + +```js +connection.changeUser({user : 'john'}, function(err) { + if (err) throw err; +}); +``` + +The available options for this feature are: + +* `user`: The name of the new user (defaults to the previous one). +* `password`: The password of the new user (defaults to the previous one). +* `charset`: The new charset (defaults to the previous one). +* `database`: The new database (defaults to the previous one). + +A sometimes useful side effect of this functionality is that this function also +resets any connection state (variables, transactions, etc.). + +Errors encountered during this operation are treated as fatal connection errors +by this module. + +## Server disconnects + +You may lose the connection to a MySQL server due to network problems, the +server timing you out, the server being restarted, or crashing. All of these +events are considered fatal errors, and will have the `err.code = +'PROTOCOL_CONNECTION_LOST'`. See the [Error Handling](#error-handling) section +for more information. + +Re-connecting a connection is done by establishing a new connection. Once +terminated, an existing connection object cannot be re-connected by design. + +With Pool, disconnected connections will be removed from the pool freeing up +space for a new connection to be created on the next getConnection call. + +## Performing queries + +The most basic way to perform a query is to call the `.query()` method on an object +(like a `Connection`, `Pool`, or `PoolNamespace` instance). + +The simplest form of .`query()` is `.query(sqlString, callback)`, where a SQL string +is the first argument and the second is a callback: + +```js +connection.query('SELECT * FROM `books` WHERE `author` = "David"', function (error, results, fields) { + // error will be an Error if one occurred during the query + // results will contain the results of the query + // fields will contain information about the returned results fields (if any) +}); +``` + +The second form `.query(sqlString, values, callback)` comes when using +placeholder values (see [escaping query values](#escaping-query-values)): + +```js +connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) { + // error will be an Error if one occurred during the query + // results will contain the results of the query + // fields will contain information about the returned results fields (if any) +}); +``` + +The third form `.query(options, callback)` comes when using various advanced +options on the query, like [escaping query values](#escaping-query-values), +[joins with overlapping column names](#joins-with-overlapping-column-names), +[timeouts](#timeout), and [type casting](#type-casting). + +```js +connection.query({ + sql: 'SELECT * FROM `books` WHERE `author` = ?', + timeout: 40000, // 40s + values: ['David'] +}, function (error, results, fields) { + // error will be an Error if one occurred during the query + // results will contain the results of the query + // fields will contain information about the returned results fields (if any) +}); +``` + +Note that a combination of the second and third forms can be used where the +placeholder values are passed as an argument and not in the options object. +The `values` argument will override the `values` in the option object. + +```js +connection.query({ + sql: 'SELECT * FROM `books` WHERE `author` = ?', + timeout: 40000, // 40s + }, + ['David'], + function (error, results, fields) { + // error will be an Error if one occurred during the query + // results will contain the results of the query + // fields will contain information about the returned results fields (if any) + } +); +``` + +If the query only has a single replacement character (`?`), and the value is +not `null`, `undefined`, or an array, it can be passed directly as the second +argument to `.query`: + +```js +connection.query( + 'SELECT * FROM `books` WHERE `author` = ?', + 'David', + function (error, results, fields) { + // error will be an Error if one occurred during the query + // results will contain the results of the query + // fields will contain information about the returned results fields (if any) + } +); +``` + +## Escaping query values + +**Caution** These methods of escaping values only works when the +[NO_BACKSLASH_ESCAPES](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_backslash_escapes) +SQL mode is disabled (which is the default state for MySQL servers). + +In order to avoid SQL Injection attacks, you should always escape any user +provided data before using it inside a SQL query. You can do so using the +`mysql.escape()`, `connection.escape()` or `pool.escape()` methods: + +```js +var userId = 'some user provided value'; +var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId); +connection.query(sql, function (error, results, fields) { + if (error) throw error; + // ... +}); +``` + +Alternatively, you can use `?` characters as placeholders for values you would +like to have escaped like this: + +```js +connection.query('SELECT * FROM users WHERE id = ?', [userId], function (error, results, fields) { + if (error) throw error; + // ... +}); +``` + +Multiple placeholders are mapped to values in the same order as passed. For example, +in the following query `foo` equals `a`, `bar` equals `b`, `baz` equals `c`, and +`id` will be `userId`: + +```js +connection.query('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', ['a', 'b', 'c', userId], function (error, results, fields) { + if (error) throw error; + // ... +}); +``` + +This looks similar to prepared statements in MySQL, however it really just uses +the same `connection.escape()` method internally. + +**Caution** This also differs from prepared statements in that all `?` are +replaced, even those contained in comments and strings. + +Different value types are escaped differently, here is how: + +* Numbers are left untouched +* Booleans are converted to `true` / `false` +* Date objects are converted to `'YYYY-mm-dd HH:ii:ss'` strings +* Buffers are converted to hex strings, e.g. `X'0fa5'` +* Strings are safely escaped +* Arrays are turned into list, e.g. `['a', 'b']` turns into `'a', 'b'` +* Nested arrays are turned into grouped lists (for bulk inserts), e.g. `[['a', + 'b'], ['c', 'd']]` turns into `('a', 'b'), ('c', 'd')` +* Objects that have a `toSqlString` method will have `.toSqlString()` called + and the returned value is used as the raw SQL. +* Objects are turned into `key = 'val'` pairs for each enumerable property on + the object. If the property's value is a function, it is skipped; if the + property's value is an object, toString() is called on it and the returned + value is used. +* `undefined` / `null` are converted to `NULL` +* `NaN` / `Infinity` are left as-is. MySQL does not support these, and trying + to insert them as values will trigger MySQL errors until they implement + support. + +This escaping allows you to do neat things like this: + +```js +var post = {id: 1, title: 'Hello MySQL'}; +var query = connection.query('INSERT INTO posts SET ?', post, function (error, results, fields) { + if (error) throw error; + // Neat! +}); +console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL' +``` + +And the `toSqlString` method allows you to form complex queries with functions: + +```js +var CURRENT_TIMESTAMP = { toSqlString: function() { return 'CURRENT_TIMESTAMP()'; } }; +var sql = mysql.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 +``` + +To generate objects with a `toSqlString` method, the `mysql.raw()` method can +be used. This creates an object that will be left un-touched when using in a `?` +placeholder, useful for using functions as dynamic values: + +**Caution** The string provided to `mysql.raw()` will skip all escaping +functions when used, so be careful when passing in unvalidated input. + +```js +var CURRENT_TIMESTAMP = mysql.raw('CURRENT_TIMESTAMP()'); +var sql = mysql.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 +``` + +If you feel the need to escape queries by yourself, you can also use the escaping +function directly: + +```js +var query = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL"); + +console.log(query); // SELECT * FROM posts WHERE title='Hello MySQL' +``` + +## Escaping query identifiers + +If you can't trust an SQL identifier (database / table / column name) because it is +provided by a user, you should escape it with `mysql.escapeId(identifier)`, +`connection.escapeId(identifier)` or `pool.escapeId(identifier)` like this: + +```js +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter); +connection.query(sql, function (error, results, fields) { + if (error) throw error; + // ... +}); +``` + +It also supports adding qualified identifiers. It will escape both parts. + +```js +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId('posts.' + sorter); +// -> SELECT * FROM posts ORDER BY `posts`.`date` +``` + +If you do not want to treat `.` as qualified identifiers, you can set the second +argument to `true` in order to keep the string as a literal identifier: + +```js +var sorter = 'date.2'; +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter, true); +// -> SELECT * FROM posts ORDER BY `date.2` +``` + +Alternatively, you can use `??` characters as placeholders for identifiers you would +like to have escaped like this: + +```js +var userId = 1; +var columns = ['username', 'email']; +var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId], function (error, results, fields) { + if (error) throw error; + // ... +}); + +console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1 +``` +**Please note that this last character sequence is experimental and syntax might change** + +When you pass an Object to `.escape()` or `.query()`, `.escapeId()` is used to avoid SQL injection in object keys. + +### Preparing Queries + +You can use mysql.format to prepare a query with multiple insertion points, utilizing the proper escaping for ids and values. A simple example of this follows: + +```js +var sql = "SELECT * FROM ?? WHERE ?? = ?"; +var inserts = ['users', 'id', userId]; +sql = mysql.format(sql, inserts); +``` + +Following this you then have a valid, escaped query that you can then send to the database safely. This is useful if you are looking to prepare the query before actually sending it to the database. As mysql.format is exposed from SqlString.format you also have the option (but are not required) to pass in stringifyObject and timezone, allowing you provide a custom means of turning objects into strings, as well as a location-specific/timezone-aware Date. + +### Custom format + +If you prefer to have another type of query escape format, there's a connection configuration option you can use to define a custom format function. You can access the connection object if you want to use the built-in `.escape()` or any other connection function. + +Here's an example of how to implement another format: + +```js +connection.config.queryFormat = function (query, values) { + if (!values) return query; + return query.replace(/\:(\w+)/g, function (txt, key) { + if (values.hasOwnProperty(key)) { + return this.escape(values[key]); + } + return txt; + }.bind(this)); +}; + +connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" }); +``` + +## Getting the id of an inserted row + +If you are inserting a row into a table with an auto increment primary key, you +can retrieve the insert id like this: + +```js +connection.query('INSERT INTO posts SET ?', {title: 'test'}, function (error, results, fields) { + if (error) throw error; + console.log(results.insertId); +}); +``` + +When dealing with big numbers (above JavaScript Number precision limit), you should +consider enabling `supportBigNumbers` option to be able to read the insert id as a +string, otherwise it will throw an error. + +This option is also required when fetching big numbers from the database, otherwise +you will get values rounded to hundreds or thousands due to the precision limit. + +## Getting the number of affected rows + +You can get the number of affected rows from an insert, update or delete statement. + +```js +connection.query('DELETE FROM posts WHERE title = "wrong"', function (error, results, fields) { + if (error) throw error; + console.log('deleted ' + results.affectedRows + ' rows'); +}) +``` + +## Getting the number of changed rows + +You can get the number of changed rows from an update statement. + +"changedRows" differs from "affectedRows" in that it does not count updated rows +whose values were not changed. + +```js +connection.query('UPDATE posts SET ...', function (error, results, fields) { + if (error) throw error; + console.log('changed ' + results.changedRows + ' rows'); +}) +``` + +## Getting the connection ID + +You can get the MySQL connection ID ("thread ID") of a given connection using the `threadId` +property. + +```js +connection.connect(function(err) { + if (err) throw err; + console.log('connected as id ' + connection.threadId); +}); +``` + +## Executing queries in parallel + +The MySQL protocol is sequential, this means that you need multiple connections +to execute queries in parallel. You can use a Pool to manage connections, one +simple approach is to create one connection per incoming http request. + +## Streaming query rows + +Sometimes you may want to select large quantities of rows and process each of +them as they are received. This can be done like this: + +```js +var query = connection.query('SELECT * FROM posts'); +query + .on('error', function(err) { + // Handle error, an 'end' event will be emitted after this as well + }) + .on('fields', function(fields) { + // the field packets for the rows to follow + }) + .on('result', function(row) { + // Pausing the connnection is useful if your processing involves I/O + connection.pause(); + + processRow(row, function() { + connection.resume(); + }); + }) + .on('end', function() { + // all rows have been received + }); +``` + +Please note a few things about the example above: + +* Usually you will want to receive a certain amount of rows before starting to + throttle the connection using `pause()`. This number will depend on the + amount and size of your rows. +* `pause()` / `resume()` operate on the underlying socket and parser. You are + guaranteed that no more `'result'` events will fire after calling `pause()`. +* You MUST NOT provide a callback to the `query()` method when streaming rows. +* The `'result'` event will fire for both rows as well as OK packets + confirming the success of a INSERT/UPDATE query. +* It is very important not to leave the result paused too long, or you may + encounter `Error: Connection lost: The server closed the connection.` + The time limit for this is determined by the + [net_write_timeout setting](https://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_net_write_timeout) + on your MySQL server. + +Additionally you may be interested to know that it is currently not possible to +stream individual row columns, they will always be buffered up entirely. If you +have a good use case for streaming large fields to and from MySQL, I'd love to +get your thoughts and contributions on this. + +### Piping results with Streams + +The query object provides a convenience method `.stream([options])` that wraps +query events into a [Readable Stream](http://nodejs.org/api/stream.html#stream_class_stream_readable) +object. This stream can easily be piped downstream and provides automatic +pause/resume, based on downstream congestion and the optional `highWaterMark`. +The `objectMode` parameter of the stream is set to `true` and cannot be changed +(if you need a byte stream, you will need to use a transform stream, like +[objstream](https://www.npmjs.com/package/objstream) for example). + +For example, piping query results into another stream (with a max buffer of 5 +objects) is simply: + +```js +connection.query('SELECT * FROM posts') + .stream({highWaterMark: 5}) + .pipe(...); +``` + +## Multiple statement queries + +Support for multiple statements is disabled for security reasons (it allows for +SQL injection attacks if values are not properly escaped). To use this feature +you have to enable it for your connection: + +```js +var connection = mysql.createConnection({multipleStatements: true}); +``` + +Once enabled, you can execute multiple statement queries like any other query: + +```js +connection.query('SELECT 1; SELECT 2', function (error, results, fields) { + if (error) throw error; + // `results` is an array with one element for every statement in the query: + console.log(results[0]); // [{1: 1}] + console.log(results[1]); // [{2: 2}] +}); +``` + +Additionally you can also stream the results of multiple statement queries: + +```js +var query = connection.query('SELECT 1; SELECT 2'); + +query + .on('fields', function(fields, index) { + // the fields for the result rows that follow + }) + .on('result', function(row, index) { + // index refers to the statement this result belongs to (starts at 0) + }); +``` + +If one of the statements in your query causes an error, the resulting Error +object contains a `err.index` property which tells you which statement caused +it. MySQL will also stop executing any remaining statements when an error +occurs. + +Please note that the interface for streaming multiple statement queries is +experimental and I am looking forward to feedback on it. + +## Stored procedures + +You can call stored procedures from your queries as with any other mysql driver. +If the stored procedure produces several result sets, they are exposed to you +the same way as the results for multiple statement queries. + +## Joins with overlapping column names + +When executing joins, you are likely to get result sets with overlapping column +names. + +By default, node-mysql will overwrite colliding column names in the +order the columns are received from MySQL, causing some of the received values +to be unavailable. + +However, you can also specify that you want your columns to be nested below +the table name like this: + +```js +var options = {sql: '...', nestTables: true}; +connection.query(options, function (error, results, fields) { + if (error) throw error; + /* results will be an array like this now: + [{ + table1: { + fieldA: '...', + fieldB: '...', + }, + table2: { + fieldA: '...', + fieldB: '...', + }, + }, ...] + */ +}); +``` + +Or use a string separator to have your results merged. + +```js +var options = {sql: '...', nestTables: '_'}; +connection.query(options, function (error, results, fields) { + if (error) throw error; + /* results will be an array like this now: + [{ + table1_fieldA: '...', + table1_fieldB: '...', + table2_fieldA: '...', + table2_fieldB: '...', + }, ...] + */ +}); +``` + +## Transactions + +Simple transaction support is available at the connection level: + +```js +connection.beginTransaction(function(err) { + if (err) { throw err; } + connection.query('INSERT INTO posts SET title=?', title, function (error, results, fields) { + if (error) { + return connection.rollback(function() { + throw error; + }); + } + + var log = 'Post ' + results.insertId + ' added'; + + connection.query('INSERT INTO log SET data=?', log, function (error, results, fields) { + if (error) { + return connection.rollback(function() { + throw error; + }); + } + connection.commit(function(err) { + if (err) { + return connection.rollback(function() { + throw err; + }); + } + console.log('success!'); + }); + }); + }); +}); +``` +Please note that beginTransaction(), commit() and rollback() are simply convenience +functions that execute the START TRANSACTION, COMMIT, and ROLLBACK commands respectively. +It is important to understand that many commands in MySQL can cause an implicit commit, +as described [in the MySQL documentation](http://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html) + +## Ping + +A ping packet can be sent over a connection using the `connection.ping` method. This +method will send a ping packet to the server and when the server responds, the callback +will fire. If an error occurred, the callback will fire with an error argument. + +```js +connection.ping(function (err) { + if (err) throw err; + console.log('Server responded to ping'); +}) +``` + +## Timeouts + +Every operation takes an optional inactivity timeout option. This allows you to +specify appropriate timeouts for operations. It is important to note that these +timeouts are not part of the MySQL protocol, and rather timeout operations through +the client. This means that when a timeout is reached, the connection it occurred +on will be destroyed and no further operations can be performed. + +```js +// Kill query after 60s +connection.query({sql: 'SELECT COUNT(*) AS count FROM big_table', timeout: 60000}, function (error, results, fields) { + if (error && error.code === 'PROTOCOL_SEQUENCE_TIMEOUT') { + throw new Error('too long to count table rows!'); + } + + if (error) { + throw error; + } + + console.log(results[0].count + ' rows'); +}); +``` + +## Error handling + +This module comes with a consistent approach to error handling that you should +review carefully in order to write solid applications. + +Most errors created by this module are instances of the JavaScript [Error][] +object. Additionally they typically come with two extra properties: + +* `err.code`: Either a [MySQL server error][] (e.g. + `'ER_ACCESS_DENIED_ERROR'`), a Node.js error (e.g. `'ECONNREFUSED'`) or an + internal error (e.g. `'PROTOCOL_CONNECTION_LOST'`). +* `err.fatal`: Boolean, indicating if this error is terminal to the connection + object. If the error is not from a MySQL protocol operation, this properly + will not be defined. +* `err.sql`: String, contains the full SQL of the failed query. This can be + useful when using a higher level interface like an ORM that is generating + the queries. +* `err.sqlState`: String, contains the five-character SQLSTATE value. Only populated from [MySQL server error][]. +* `err.sqlMessage`: String, contains the message string that provides a + textual description of the error. Only populated from [MySQL server error][]. + +[Error]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error +[MySQL server error]: http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html + +Fatal errors are propagated to *all* pending callbacks. In the example below, a +fatal error is triggered by trying to connect to an invalid port. Therefore the +error object is propagated to both pending callbacks: + +```js +var connection = require('mysql').createConnection({ + port: 84943, // WRONG PORT +}); + +connection.connect(function(err) { + console.log(err.code); // 'ECONNREFUSED' + console.log(err.fatal); // true +}); + +connection.query('SELECT 1', function (error, results, fields) { + console.log(error.code); // 'ECONNREFUSED' + console.log(error.fatal); // true +}); +``` + +Normal errors however are only delegated to the callback they belong to. So in +the example below, only the first callback receives an error, the second query +works as expected: + +```js +connection.query('USE name_of_db_that_does_not_exist', function (error, results, fields) { + console.log(error.code); // 'ER_BAD_DB_ERROR' +}); + +connection.query('SELECT 1', function (error, results, fields) { + console.log(error); // null + console.log(results.length); // 1 +}); +``` + +Last but not least: If a fatal errors occurs and there are no pending +callbacks, or a normal error occurs which has no callback belonging to it, the +error is emitted as an `'error'` event on the connection object. This is +demonstrated in the example below: + +```js +connection.on('error', function(err) { + console.log(err.code); // 'ER_BAD_DB_ERROR' +}); + +connection.query('USE name_of_db_that_does_not_exist'); +``` + +Note: `'error'` events are special in node. If they occur without an attached +listener, a stack trace is printed and your process is killed. + +**tl;dr:** This module does not want you to deal with silent failures. You +should always provide callbacks to your method calls. If you want to ignore +this advice and suppress unhandled errors, you can do this: + +```js +// I am Chuck Norris: +connection.on('error', function() {}); +``` + +## Exception Safety + +This module is exception safe. That means you can continue to use it, even if +one of your callback functions throws an error which you're catching using +'uncaughtException' or a domain. + +## Type casting + +For your convenience, this driver will cast mysql types into native JavaScript +types by default. The following mappings exist: + +### Number + +* TINYINT +* SMALLINT +* INT +* MEDIUMINT +* YEAR +* FLOAT +* DOUBLE + +### Date + +* TIMESTAMP +* DATE +* DATETIME + +### Buffer + +* TINYBLOB +* MEDIUMBLOB +* LONGBLOB +* BLOB +* BINARY +* VARBINARY +* BIT (last byte will be filled with 0 bits as necessary) + +### String + +**Note** text in the binary character set is returned as `Buffer`, rather +than a string. + +* CHAR +* VARCHAR +* TINYTEXT +* MEDIUMTEXT +* LONGTEXT +* TEXT +* ENUM +* SET +* DECIMAL (may exceed float precision) +* BIGINT (may exceed float precision) +* TIME (could be mapped to Date, but what date would be set?) +* GEOMETRY (never used those, get in touch if you do) + +It is not recommended (and may go away / change in the future) to disable type +casting, but you can currently do so on either the connection: + +```js +var connection = require('mysql').createConnection({typeCast: false}); +``` + +Or on the query level: + +```js +var options = {sql: '...', typeCast: false}; +var query = connection.query(options, function (error, results, fields) { + if (error) throw error; + // ... +}); +``` + +You can also pass a function and handle type casting yourself. You're given some +column information like database, table and name and also type and length. If you +just want to apply a custom type casting to a specific type you can do it and then +fallback to the default. Here's an example of converting `TINYINT(1)` to boolean: + +```js +connection.query({ + sql: '...', + typeCast: function (field, next) { + if (field.type == 'TINY' && field.length == 1) { + return (field.string() == '1'); // 1 = true, 0 = false + } + return next(); + } +}); +``` +__WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once. (see [#539](https://github.com/mysqljs/mysql/issues/539) for discussion)__ + +``` +field.string() +field.buffer() +field.geometry() +``` +are aliases for +``` +parser.parseLengthCodedString() +parser.parseLengthCodedBuffer() +parser.parseGeometryValue() +``` +__You can find which field function you need to use by looking at: [RowDataPacket.prototype._typeCast](https://github.com/mysqljs/mysql/blob/master/lib/protocol/packets/RowDataPacket.js#L41)__ + + +## Connection Flags + +If, for any reason, you would like to change the default connection flags, you +can use the connection option `flags`. Pass a string with a comma separated list +of items to add to the default flags. If you don't want a default flag to be used +prepend the flag with a minus sign. To add a flag that is not in the default list, +just write the flag name, or prefix it with a plus (case insensitive). + +**Please note that some available flags that are not supported (e.g.: Compression), +are still not allowed to be specified.** + +### Example + +The next example blacklists FOUND_ROWS flag from default connection flags. + +```js +var connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS"); +``` + +### Default Flags + +The following flags are sent by default on a new connection: + +- `CONNECT_WITH_DB` - Ability to specify the database on connection. +- `FOUND_ROWS` - Send the found rows instead of the affected rows as `affectedRows`. +- `IGNORE_SIGPIPE` - Old; no effect. +- `IGNORE_SPACE` - Let the parser ignore spaces before the `(` in queries. +- `LOCAL_FILES` - Can use `LOAD DATA LOCAL`. +- `LONG_FLAG` +- `LONG_PASSWORD` - Use the improved version of Old Password Authentication. +- `MULTI_RESULTS` - Can handle multiple resultsets for COM_QUERY. +- `ODBC` Old; no effect. +- `PROTOCOL_41` - Uses the 4.1 protocol. +- `PS_MULTI_RESULTS` - Can handle multiple resultsets for COM_STMT_EXECUTE. +- `RESERVED` - Old flag for the 4.1 protocol. +- `SECURE_CONNECTION` - Support native 4.1 authentication. +- `TRANSACTIONS` - Asks for the transaction status flags. + +In addition, the following flag will be sent if the option `multipleStatements` +is set to `true`: + +- `MULTI_STATEMENTS` - The client may send multiple statement per query or + statement prepare. + +### Other Available Flags + +There are other flags available. They may or may not function, but are still +available to specify. + +- `COMPRESS` +- `INTERACTIVE` +- `NO_SCHEMA` +- `PLUGIN_AUTH` +- `REMEMBER_OPTIONS` +- `SSL` +- `SSL_VERIFY_SERVER_CERT` + +## Debugging and reporting problems + +If you are running into problems, one thing that may help is enabling the +`debug` mode for the connection: + +```js +var connection = mysql.createConnection({debug: true}); +``` + +This will print all incoming and outgoing packets on stdout. You can also restrict debugging to +packet types by passing an array of types to debug: + +```js +var connection = mysql.createConnection({debug: ['ComQueryPacket', 'RowDataPacket']}); +``` + +to restrict debugging to the query and data packets. + +If that does not help, feel free to open a GitHub issue. A good GitHub issue +will have: + +* The minimal amount of code required to reproduce the problem (if possible) +* As much debugging output and information about your environment (mysql + version, node version, os, etc.) as you can gather. + +## Security issues + +Security issues should not be first reported through GitHub or another public +forum, but kept private in order for the collaborators to assess the report +and either (a) devise a fix and plan a release date or (b) assert that it is +not a security issue (in which case it can be posted in a public forum, like +a GitHub issue). + +The primary private forum is email, either by emailing the module's author or +opening a GitHub issue simply asking to whom a security issues should be +addressed to without disclosing the issue or type of issue. + +An ideal report would include a clear indication of what the security issue is +and how it would be exploited, ideally with an accompaning proof of concept +("PoC") for collaborators to work again and validate potentional fixes against. + +## Contributing + +This project welcomes contributions from the community. Contributions are +accepted using GitHub pull requests. If you're not familiar with making +GitHub pull requests, please refer to the +[GitHub documentation "Creating a pull request"](https://help.github.com/articles/creating-a-pull-request/). + +For a good pull request, we ask you provide the following: + +1. Try to include a clear description of your pull request in the description. + It should include the basic "what" and "why"s for the request. +2. The tests should pass as best as you can. See the [Running tests](#running-tests) + section on how to run the different tests. GitHub will automatically run + the tests as well, to act as a safety net. +3. The pull request should include tests for the change. A new feature should + have tests for the new feature and bug fixes should include a test that fails + without the corresponding code change and passes after they are applied. + The command `npm run test-cov` will generate a `coverage/` folder that + contains HTML pages of the code coverage, to better understand if everything + you're adding is being tested. +4. If the pull request is a new feature, please be sure to include all + appropriate documentation additions in the `Readme.md` file as well. +5. To help ensure that your code is similar in style to the existing code, + run the command `npm run lint` and fix any displayed issues. + +## Running tests + +The test suite is split into two parts: unit tests and integration tests. +The unit tests run on any machine while the integration tests require a +MySQL server instance to be setup. + +### Running unit tests + +```sh +$ FILTER=unit npm test +``` + +### Running integration tests + +Set the environment variables `MYSQL_DATABASE`, `MYSQL_HOST`, `MYSQL_PORT`, +`MYSQL_USER` and `MYSQL_PASSWORD`. `MYSQL_SOCKET` can also be used in place +of `MYSQL_HOST` and `MYSQL_PORT` to connect over a UNIX socket. Then run +`npm test`. + +For example, if you have an installation of mysql running on localhost:3306 +and no password set for the `root` user, run: + +```sh +$ mysql -u root -e "CREATE DATABASE IF NOT EXISTS node_mysql_test" +$ MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_DATABASE=node_mysql_test MYSQL_USER=root MYSQL_PASSWORD= FILTER=integration npm test +``` + +## Todo + +* Prepared statements +* Support for encodings other than UTF-8 / ASCII + +[npm-image]: https://img.shields.io/npm/v/mysql.svg +[npm-url]: https://npmjs.org/package/mysql +[node-version-image]: https://img.shields.io/node/v/mysql.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/mysqljs/mysql/master.svg?label=linux +[travis-url]: https://travis-ci.org/mysqljs/mysql +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/node-mysql/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/node-mysql +[coveralls-image]: https://img.shields.io/coveralls/mysqljs/mysql/master.svg +[coveralls-url]: https://coveralls.io/r/mysqljs/mysql?branch=master +[downloads-image]: https://img.shields.io/npm/dm/mysql.svg +[downloads-url]: https://npmjs.org/package/mysql diff --git a/node_modules/mysql/index.js b/node_modules/mysql/index.js new file mode 100644 index 0000000000000000000000000000000000000000..72624076b92c4f181287e668be9e19d9c4c3192b --- /dev/null +++ b/node_modules/mysql/index.js @@ -0,0 +1,161 @@ +var Classes = Object.create(null); + +/** + * Create a new Connection instance. + * @param {object|string} config Configuration or connection string for new MySQL connection + * @return {Connection} A new MySQL connection + * @public + */ +exports.createConnection = function createConnection(config) { + var Connection = loadClass('Connection'); + var ConnectionConfig = loadClass('ConnectionConfig'); + + return new Connection({config: new ConnectionConfig(config)}); +}; + +/** + * Create a new Pool instance. + * @param {object|string} config Configuration or connection string for new MySQL connections + * @return {Pool} A new MySQL pool + * @public + */ +exports.createPool = function createPool(config) { + var Pool = loadClass('Pool'); + var PoolConfig = loadClass('PoolConfig'); + + return new Pool({config: new PoolConfig(config)}); +}; + +/** + * Create a new PoolCluster instance. + * @param {object} [config] Configuration for pool cluster + * @return {PoolCluster} New MySQL pool cluster + * @public + */ +exports.createPoolCluster = function createPoolCluster(config) { + var PoolCluster = loadClass('PoolCluster'); + + return new PoolCluster(config); +}; + +/** + * Create a new Query instance. + * @param {string} sql The SQL for the query + * @param {array} [values] Any values to insert into placeholders in sql + * @param {function} [callback] The callback to use when query is complete + * @return {Query} New query object + * @public + */ +exports.createQuery = function createQuery(sql, values, callback) { + var Connection = loadClass('Connection'); + + return Connection.createQuery(sql, values, callback); +}; + +/** + * Escape a value for SQL. + * @param {*} value The value to escape + * @param {boolean} [stringifyObjects=false] Setting if objects should be stringified + * @param {string} [timeZone=local] Setting for time zone to use for Date conversion + * @return {string} Escaped string value + * @public + */ +exports.escape = function escape(value, stringifyObjects, timeZone) { + var SqlString = loadClass('SqlString'); + + return SqlString.escape(value, stringifyObjects, timeZone); +}; + +/** + * Escape an identifier for SQL. + * @param {*} value The value to escape + * @param {boolean} [forbidQualified=false] Setting to treat '.' as part of identifier + * @return {string} Escaped string value + * @public + */ +exports.escapeId = function escapeId(value, forbidQualified) { + var SqlString = loadClass('SqlString'); + + return SqlString.escapeId(value, forbidQualified); +}; + +/** + * Format SQL and replacement values into a SQL string. + * @param {string} sql The SQL for the query + * @param {array} [values] Any values to insert into placeholders in sql + * @param {boolean} [stringifyObjects=false] Setting if objects should be stringified + * @param {string} [timeZone=local] Setting for time zone to use for Date conversion + * @return {string} Formatted SQL string + * @public + */ +exports.format = function format(sql, values, stringifyObjects, timeZone) { + var SqlString = loadClass('SqlString'); + + return SqlString.format(sql, values, stringifyObjects, timeZone); +}; + +/** + * Wrap raw SQL strings from escape overriding. + * @param {string} sql The raw SQL + * @return {object} Wrapped object + * @public + */ +exports.raw = function raw(sql) { + var SqlString = loadClass('SqlString'); + + return SqlString.raw(sql); +}; + +/** + * The type constants. + * @public + */ +Object.defineProperty(exports, 'Types', { + get: loadClass.bind(null, 'Types') +}); + +/** + * Load the given class. + * @param {string} className Name of class to default + * @return {function|object} Class constructor or exports + * @private + */ +function loadClass(className) { + var Class = Classes[className]; + + if (Class !== undefined) { + return Class; + } + + // This uses a switch for static require analysis + switch (className) { + case 'Connection': + Class = require('./lib/Connection'); + break; + case 'ConnectionConfig': + Class = require('./lib/ConnectionConfig'); + break; + case 'Pool': + Class = require('./lib/Pool'); + break; + case 'PoolCluster': + Class = require('./lib/PoolCluster'); + break; + case 'PoolConfig': + Class = require('./lib/PoolConfig'); + break; + case 'SqlString': + Class = require('./lib/protocol/SqlString'); + break; + case 'Types': + Class = require('./lib/protocol/constants/types'); + break; + default: + throw new Error('Cannot find class \'' + className + '\''); + } + + // Store to prevent invoking require() + Classes[className] = Class; + + return Class; +} diff --git a/node_modules/mysql/lib/Connection.js b/node_modules/mysql/lib/Connection.js new file mode 100644 index 0000000000000000000000000000000000000000..2a37798e643e44b226863045ba206daa51934715 --- /dev/null +++ b/node_modules/mysql/lib/Connection.js @@ -0,0 +1,505 @@ +var Crypto = require('crypto'); +var Events = require('events'); +var Net = require('net'); +var tls = require('tls'); +var ConnectionConfig = require('./ConnectionConfig'); +var Protocol = require('./protocol/Protocol'); +var SqlString = require('./protocol/SqlString'); +var Query = require('./protocol/sequences/Query'); +var Util = require('util'); + +module.exports = Connection; +Util.inherits(Connection, Events.EventEmitter); +function Connection(options) { + Events.EventEmitter.call(this); + + this.config = options.config; + + this._socket = options.socket; + this._protocol = new Protocol({config: this.config, connection: this}); + this._connectCalled = false; + this.state = 'disconnected'; + this.threadId = null; +} + +Connection.createQuery = function createQuery(sql, values, callback) { + if (sql instanceof Query) { + return sql; + } + + var cb = wrapCallbackInDomain(null, callback); + var options = {}; + + if (typeof sql === 'function') { + cb = wrapCallbackInDomain(null, sql); + return new Query(options, cb); + } + + if (typeof sql === 'object') { + for (var prop in sql) { + options[prop] = sql[prop]; + } + + if (typeof values === 'function') { + cb = wrapCallbackInDomain(null, values); + } else if (values !== undefined) { + options.values = values; + } + + return new Query(options, cb); + } + + options.sql = sql; + options.values = values; + + if (typeof values === 'function') { + cb = wrapCallbackInDomain(null, values); + options.values = undefined; + } + + if (cb === undefined && callback !== undefined) { + throw new TypeError('argument callback must be a function when provided'); + } + + return new Query(options, cb); +}; + +Connection.prototype.connect = function connect(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + if (!this._connectCalled) { + this._connectCalled = true; + + // Connect either via a UNIX domain socket or a TCP socket. + this._socket = (this.config.socketPath) + ? Net.createConnection(this.config.socketPath) + : Net.createConnection(this.config.port, this.config.host); + + // Connect socket to connection domain + if (Events.usingDomains) { + this._socket.domain = this.domain; + } + + var connection = this; + this._protocol.on('data', function(data) { + connection._socket.write(data); + }); + this._socket.on('data', wrapToDomain(connection, function (data) { + connection._protocol.write(data); + })); + this._protocol.on('end', function() { + connection._socket.end(); + }); + this._socket.on('end', wrapToDomain(connection, function () { + connection._protocol.end(); + })); + + this._socket.on('error', this._handleNetworkError.bind(this)); + this._socket.on('connect', this._handleProtocolConnect.bind(this)); + this._protocol.on('handshake', this._handleProtocolHandshake.bind(this)); + this._protocol.on('unhandledError', this._handleProtocolError.bind(this)); + this._protocol.on('drain', this._handleProtocolDrain.bind(this)); + this._protocol.on('end', this._handleProtocolEnd.bind(this)); + this._protocol.on('enqueue', this._handleProtocolEnqueue.bind(this)); + + if (this.config.connectTimeout) { + var handleConnectTimeout = this._handleConnectTimeout.bind(this); + + this._socket.setTimeout(this.config.connectTimeout, handleConnectTimeout); + this._socket.once('connect', function() { + this.setTimeout(0, handleConnectTimeout); + }); + } + } + + this._protocol.handshake(options, wrapCallbackInDomain(this, callback)); +}; + +Connection.prototype.changeUser = function changeUser(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + this._implyConnect(); + + var charsetNumber = (options.charset) + ? ConnectionConfig.getCharsetNumber(options.charset) + : this.config.charsetNumber; + + return this._protocol.changeUser({ + user : options.user || this.config.user, + password : options.password || this.config.password, + database : options.database || this.config.database, + timeout : options.timeout, + charsetNumber : charsetNumber, + currentConfig : this.config + }, wrapCallbackInDomain(this, callback)); +}; + +Connection.prototype.beginTransaction = function beginTransaction(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + options.sql = 'START TRANSACTION'; + options.values = null; + + return this.query(options, callback); +}; + +Connection.prototype.commit = function commit(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + options.sql = 'COMMIT'; + options.values = null; + + return this.query(options, callback); +}; + +Connection.prototype.rollback = function rollback(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + options.sql = 'ROLLBACK'; + options.values = null; + + return this.query(options, callback); +}; + +Connection.prototype.query = function query(sql, values, cb) { + var query = Connection.createQuery(sql, values, cb); + query._connection = this; + + if (!(typeof sql === 'object' && 'typeCast' in sql)) { + query.typeCast = this.config.typeCast; + } + + if (query.sql) { + query.sql = this.format(query.sql, query.values); + } + + if (query._callback) { + query._callback = wrapCallbackInDomain(this, query._callback); + } + + this._implyConnect(); + + return this._protocol._enqueue(query); +}; + +Connection.prototype.ping = function ping(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + this._implyConnect(); + this._protocol.ping(options, wrapCallbackInDomain(this, callback)); +}; + +Connection.prototype.statistics = function statistics(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + this._implyConnect(); + this._protocol.stats(options, wrapCallbackInDomain(this, callback)); +}; + +Connection.prototype.end = function end(options, callback) { + var cb = callback; + var opts = options; + + if (!callback && typeof options === 'function') { + cb = options; + opts = null; + } + + // create custom options reference + opts = Object.create(opts || null); + + if (opts.timeout === undefined) { + // default timeout of 30 seconds + opts.timeout = 30000; + } + + this._implyConnect(); + this._protocol.quit(opts, wrapCallbackInDomain(this, cb)); +}; + +Connection.prototype.destroy = function() { + this.state = 'disconnected'; + this._implyConnect(); + this._socket.destroy(); + this._protocol.destroy(); +}; + +Connection.prototype.pause = function() { + this._socket.pause(); + this._protocol.pause(); +}; + +Connection.prototype.resume = function() { + this._socket.resume(); + this._protocol.resume(); +}; + +Connection.prototype.escape = function(value) { + return SqlString.escape(value, false, this.config.timezone); +}; + +Connection.prototype.escapeId = function escapeId(value) { + return SqlString.escapeId(value, false); +}; + +Connection.prototype.format = function(sql, values) { + if (typeof this.config.queryFormat === 'function') { + return this.config.queryFormat.call(this, sql, values, this.config.timezone); + } + return SqlString.format(sql, values, this.config.stringifyObjects, this.config.timezone); +}; + +if (tls.TLSSocket) { + // 0.11+ environment + Connection.prototype._startTLS = function _startTLS(onSecure) { + var connection = this; + var secureContext = tls.createSecureContext({ + ca : this.config.ssl.ca, + cert : this.config.ssl.cert, + ciphers : this.config.ssl.ciphers, + key : this.config.ssl.key, + passphrase : this.config.ssl.passphrase + }); + + // "unpipe" + this._socket.removeAllListeners('data'); + this._protocol.removeAllListeners('data'); + + // socket <-> encrypted + var rejectUnauthorized = this.config.ssl.rejectUnauthorized; + var secureEstablished = false; + var secureSocket = new tls.TLSSocket(this._socket, { + rejectUnauthorized : rejectUnauthorized, + requestCert : true, + secureContext : secureContext, + isServer : false + }); + + // error handler for secure socket + secureSocket.on('_tlsError', function(err) { + if (secureEstablished) { + connection._handleNetworkError(err); + } else { + onSecure(err); + } + }); + + // cleartext <-> protocol + secureSocket.pipe(this._protocol); + this._protocol.on('data', function(data) { + secureSocket.write(data); + }); + + secureSocket.on('secure', function() { + secureEstablished = true; + + onSecure(rejectUnauthorized ? this.ssl.verifyError() : null); + }); + + // start TLS communications + secureSocket._start(); + }; +} else { + // pre-0.11 environment + Connection.prototype._startTLS = function _startTLS(onSecure) { + // before TLS: + // _socket <-> _protocol + // after: + // _socket <-> securePair.encrypted <-> securePair.cleartext <-> _protocol + + var connection = this; + var credentials = Crypto.createCredentials({ + ca : this.config.ssl.ca, + cert : this.config.ssl.cert, + ciphers : this.config.ssl.ciphers, + key : this.config.ssl.key, + passphrase : this.config.ssl.passphrase + }); + + var rejectUnauthorized = this.config.ssl.rejectUnauthorized; + var secureEstablished = false; + var securePair = tls.createSecurePair(credentials, false, true, rejectUnauthorized); + + // error handler for secure pair + securePair.on('error', function(err) { + if (secureEstablished) { + connection._handleNetworkError(err); + } else { + onSecure(err); + } + }); + + // "unpipe" + this._socket.removeAllListeners('data'); + this._protocol.removeAllListeners('data'); + + // socket <-> encrypted + securePair.encrypted.pipe(this._socket); + this._socket.on('data', function(data) { + securePair.encrypted.write(data); + }); + + // cleartext <-> protocol + securePair.cleartext.pipe(this._protocol); + this._protocol.on('data', function(data) { + securePair.cleartext.write(data); + }); + + // secure established + securePair.on('secure', function() { + secureEstablished = true; + + if (!rejectUnauthorized) { + onSecure(); + return; + } + + var verifyError = this.ssl.verifyError(); + var err = verifyError; + + // node.js 0.6 support + if (typeof err === 'string') { + err = new Error(verifyError); + err.code = verifyError; + } + + onSecure(err); + }); + + // node.js 0.8 bug + securePair._cycle = securePair.cycle; + securePair.cycle = function cycle() { + if (this.ssl && this.ssl.error) { + this.error(); + } + + return this._cycle.apply(this, arguments); + }; + }; +} + +Connection.prototype._handleConnectTimeout = function() { + if (this._socket) { + this._socket.setTimeout(0); + this._socket.destroy(); + } + + var err = new Error('connect ETIMEDOUT'); + err.errorno = 'ETIMEDOUT'; + err.code = 'ETIMEDOUT'; + err.syscall = 'connect'; + + this._handleNetworkError(err); +}; + +Connection.prototype._handleNetworkError = function(err) { + this._protocol.handleNetworkError(err); +}; + +Connection.prototype._handleProtocolError = function(err) { + this.state = 'protocol_error'; + this.emit('error', err); +}; + +Connection.prototype._handleProtocolDrain = function() { + this.emit('drain'); +}; + +Connection.prototype._handleProtocolConnect = function() { + this.state = 'connected'; + this.emit('connect'); +}; + +Connection.prototype._handleProtocolHandshake = function _handleProtocolHandshake(packet) { + this.state = 'authenticated'; + this.threadId = packet.threadId; +}; + +Connection.prototype._handleProtocolEnd = function(err) { + this.state = 'disconnected'; + this.emit('end', err); +}; + +Connection.prototype._handleProtocolEnqueue = function _handleProtocolEnqueue(sequence) { + this.emit('enqueue', sequence); +}; + +Connection.prototype._implyConnect = function() { + if (!this._connectCalled) { + this.connect(); + } +}; + +function unwrapFromDomain(fn) { + return function () { + var domains = []; + var ret; + + while (process.domain) { + domains.shift(process.domain); + process.domain.exit(); + } + + try { + ret = fn.apply(this, arguments); + } finally { + for (var i = 0; i < domains.length; i++) { + domains[i].enter(); + } + } + + return ret; + }; +} + +function wrapCallbackInDomain(ee, fn) { + if (typeof fn !== 'function' || fn.domain) { + return fn; + } + + var domain = process.domain; + + if (domain) { + return domain.bind(fn); + } else if (ee) { + return unwrapFromDomain(wrapToDomain(ee, fn)); + } else { + return fn; + } +} + +function wrapToDomain(ee, fn) { + return function () { + if (Events.usingDomains && ee.domain) { + ee.domain.enter(); + fn.apply(this, arguments); + ee.domain.exit(); + } else { + fn.apply(this, arguments); + } + }; +} diff --git a/node_modules/mysql/lib/ConnectionConfig.js b/node_modules/mysql/lib/ConnectionConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..147aa0abbdc7ba1ca90ea7eaada05e3140ec30e3 --- /dev/null +++ b/node_modules/mysql/lib/ConnectionConfig.js @@ -0,0 +1,201 @@ +var urlParse = require('url').parse; +var ClientConstants = require('./protocol/constants/client'); +var Charsets = require('./protocol/constants/charsets'); +var SSLProfiles = null; + +module.exports = ConnectionConfig; +function ConnectionConfig(options) { + if (typeof options === 'string') { + options = ConnectionConfig.parseUrl(options); + } + + this.host = options.host || 'localhost'; + this.port = options.port || 3306; + this.localAddress = options.localAddress; + this.socketPath = options.socketPath; + this.user = options.user || undefined; + this.password = options.password || undefined; + this.database = options.database; + this.connectTimeout = (options.connectTimeout === undefined) + ? (10 * 1000) + : options.connectTimeout; + this.insecureAuth = options.insecureAuth || false; + this.supportBigNumbers = options.supportBigNumbers || false; + this.bigNumberStrings = options.bigNumberStrings || false; + this.dateStrings = options.dateStrings || false; + this.debug = options.debug; + this.trace = options.trace !== false; + this.stringifyObjects = options.stringifyObjects || false; + this.timezone = options.timezone || 'local'; + this.flags = options.flags || ''; + this.queryFormat = options.queryFormat; + this.pool = options.pool || undefined; + this.ssl = (typeof options.ssl === 'string') + ? ConnectionConfig.getSSLProfile(options.ssl) + : (options.ssl || false); + this.multipleStatements = options.multipleStatements || false; + this.typeCast = (options.typeCast === undefined) + ? true + : options.typeCast; + + if (this.timezone[0] === ' ') { + // "+" is a url encoded char for space so it + // gets translated to space when giving a + // connection string.. + this.timezone = '+' + this.timezone.substr(1); + } + + if (this.ssl) { + // Default rejectUnauthorized to true + this.ssl.rejectUnauthorized = this.ssl.rejectUnauthorized !== false; + } + + this.maxPacketSize = 0; + this.charsetNumber = (options.charset) + ? ConnectionConfig.getCharsetNumber(options.charset) + : options.charsetNumber || Charsets.UTF8_GENERAL_CI; + + // Set the client flags + var defaultFlags = ConnectionConfig.getDefaultFlags(options); + this.clientFlags = ConnectionConfig.mergeFlags(defaultFlags, options.flags); +} + +ConnectionConfig.mergeFlags = function mergeFlags(defaultFlags, userFlags) { + var allFlags = ConnectionConfig.parseFlagList(defaultFlags); + var newFlags = ConnectionConfig.parseFlagList(userFlags); + + // Merge the new flags + for (var flag in newFlags) { + if (allFlags[flag] !== false) { + allFlags[flag] = newFlags[flag]; + } + } + + // Build flags + var flags = 0x0; + for (var flag in allFlags) { + if (allFlags[flag]) { + // TODO: Throw here on some future release + flags |= ClientConstants['CLIENT_' + flag] || 0x0; + } + } + + return flags; +}; + +ConnectionConfig.getCharsetNumber = function getCharsetNumber(charset) { + var num = Charsets[charset.toUpperCase()]; + + if (num === undefined) { + throw new TypeError('Unknown charset \'' + charset + '\''); + } + + return num; +}; + +ConnectionConfig.getDefaultFlags = function getDefaultFlags(options) { + var defaultFlags = [ + '-COMPRESS', // Compression protocol *NOT* supported + '-CONNECT_ATTRS', // Does *NOT* send connection attributes in Protocol::HandshakeResponse41 + '+CONNECT_WITH_DB', // One can specify db on connect in Handshake Response Packet + '+FOUND_ROWS', // Send found rows instead of affected rows + '+IGNORE_SIGPIPE', // Don't issue SIGPIPE if network failures + '+IGNORE_SPACE', // Let the parser ignore spaces before '(' + '+LOCAL_FILES', // Can use LOAD DATA LOCAL + '+LONG_FLAG', // Longer flags in Protocol::ColumnDefinition320 + '+LONG_PASSWORD', // Use the improved version of Old Password Authentication + '+MULTI_RESULTS', // Can handle multiple resultsets for COM_QUERY + '+ODBC', // Special handling of ODBC behaviour + '-PLUGIN_AUTH', // Does *NOT* support auth plugins + '+PROTOCOL_41', // Uses the 4.1 protocol + '+PS_MULTI_RESULTS', // Can handle multiple resultsets for COM_STMT_EXECUTE + '+RESERVED', // Unused + '+SECURE_CONNECTION', // Supports Authentication::Native41 + '+TRANSACTIONS' // Expects status flags + ]; + + if (options && options.multipleStatements) { + // May send multiple statements per COM_QUERY and COM_STMT_PREPARE + defaultFlags.push('+MULTI_STATEMENTS'); + } + + return defaultFlags; +}; + +ConnectionConfig.getSSLProfile = function getSSLProfile(name) { + if (!SSLProfiles) { + SSLProfiles = require('./protocol/constants/ssl_profiles'); + } + + var ssl = SSLProfiles[name]; + + if (ssl === undefined) { + throw new TypeError('Unknown SSL profile \'' + name + '\''); + } + + return ssl; +}; + +ConnectionConfig.parseFlagList = function parseFlagList(flagList) { + var allFlags = Object.create(null); + + if (!flagList) { + return allFlags; + } + + var flags = !Array.isArray(flagList) + ? String(flagList || '').toUpperCase().split(/\s*,+\s*/) + : flagList; + + for (var i = 0; i < flags.length; i++) { + var flag = flags[i]; + var offset = 1; + var state = flag[0]; + + if (state === undefined) { + // TODO: throw here on some future release + continue; + } + + if (state !== '-' && state !== '+') { + offset = 0; + state = '+'; + } + + allFlags[flag.substr(offset)] = state === '+'; + } + + return allFlags; +}; + +ConnectionConfig.parseUrl = function(url) { + url = urlParse(url, true); + + var options = { + host : url.hostname, + port : url.port, + database : url.pathname.substr(1) + }; + + if (url.auth) { + var auth = url.auth.split(':'); + options.user = auth.shift(); + options.password = auth.join(':'); + } + + if (url.query) { + for (var key in url.query) { + var value = url.query[key]; + + try { + // Try to parse this as a JSON expression first + options[key] = JSON.parse(value); + } catch (err) { + // Otherwise assume it is a plain string + options[key] = value; + } + } + } + + return options; +}; diff --git a/node_modules/mysql/lib/Pool.js b/node_modules/mysql/lib/Pool.js new file mode 100644 index 0000000000000000000000000000000000000000..87a40114ac02977dd27be46206e7016af308d8e2 --- /dev/null +++ b/node_modules/mysql/lib/Pool.js @@ -0,0 +1,294 @@ +var mysql = require('../'); +var Connection = require('./Connection'); +var EventEmitter = require('events').EventEmitter; +var Util = require('util'); +var PoolConnection = require('./PoolConnection'); + +module.exports = Pool; + +Util.inherits(Pool, EventEmitter); +function Pool(options) { + EventEmitter.call(this); + this.config = options.config; + this.config.connectionConfig.pool = this; + + this._acquiringConnections = []; + this._allConnections = []; + this._freeConnections = []; + this._connectionQueue = []; + this._closed = false; +} + +Pool.prototype.getConnection = function (cb) { + + if (this._closed) { + var err = new Error('Pool is closed.'); + err.code = 'POOL_CLOSED'; + process.nextTick(function () { + cb(err); + }); + return; + } + + var connection; + var pool = this; + + if (this._freeConnections.length > 0) { + connection = this._freeConnections.shift(); + this.acquireConnection(connection, cb); + return; + } + + if (this.config.connectionLimit === 0 || this._allConnections.length < this.config.connectionLimit) { + connection = new PoolConnection(this, { config: this.config.newConnectionConfig() }); + + this._acquiringConnections.push(connection); + this._allConnections.push(connection); + + connection.connect({timeout: this.config.acquireTimeout}, function onConnect(err) { + spliceConnection(pool._acquiringConnections, connection); + + if (pool._closed) { + err = new Error('Pool is closed.'); + err.code = 'POOL_CLOSED'; + } + + if (err) { + pool._purgeConnection(connection); + cb(err); + return; + } + + pool.emit('connection', connection); + pool.emit('acquire', connection); + cb(null, connection); + }); + return; + } + + if (!this.config.waitForConnections) { + process.nextTick(function(){ + var err = new Error('No connections available.'); + err.code = 'POOL_CONNLIMIT'; + cb(err); + }); + return; + } + + this._enqueueCallback(cb); +}; + +Pool.prototype.acquireConnection = function acquireConnection(connection, cb) { + if (connection._pool !== this) { + throw new Error('Connection acquired from wrong pool.'); + } + + var changeUser = this._needsChangeUser(connection); + var pool = this; + + this._acquiringConnections.push(connection); + + function onOperationComplete(err) { + spliceConnection(pool._acquiringConnections, connection); + + if (pool._closed) { + err = new Error('Pool is closed.'); + err.code = 'POOL_CLOSED'; + } + + if (err) { + pool._connectionQueue.unshift(cb); + pool._purgeConnection(connection); + return; + } + + if (changeUser) { + pool.emit('connection', connection); + } + + pool.emit('acquire', connection); + cb(null, connection); + } + + if (changeUser) { + // restore user back to pool configuration + connection.config = this.config.newConnectionConfig(); + connection.changeUser({timeout: this.config.acquireTimeout}, onOperationComplete); + } else { + // ping connection + connection.ping({timeout: this.config.acquireTimeout}, onOperationComplete); + } +}; + +Pool.prototype.releaseConnection = function releaseConnection(connection) { + + if (this._acquiringConnections.indexOf(connection) !== -1) { + // connection is being acquired + return; + } + + if (connection._pool) { + if (connection._pool !== this) { + throw new Error('Connection released to wrong pool'); + } + + if (this._freeConnections.indexOf(connection) !== -1) { + // connection already in free connection pool + // this won't catch all double-release cases + throw new Error('Connection already released'); + } else { + // add connection to end of free queue + this._freeConnections.push(connection); + this.emit('release', connection); + } + } + + if (this._closed) { + // empty the connection queue + this._connectionQueue.splice(0).forEach(function (cb) { + var err = new Error('Pool is closed.'); + err.code = 'POOL_CLOSED'; + process.nextTick(function () { + cb(err); + }); + }); + } else if (this._connectionQueue.length) { + // get connection with next waiting callback + this.getConnection(this._connectionQueue.shift()); + } +}; + +Pool.prototype.end = function (cb) { + this._closed = true; + + if (typeof cb !== 'function') { + cb = function (err) { + if (err) throw err; + }; + } + + var calledBack = false; + var waitingClose = 0; + + function onEnd(err) { + if (!calledBack && (err || --waitingClose <= 0)) { + calledBack = true; + cb(err); + } + } + + while (this._allConnections.length !== 0) { + waitingClose++; + this._purgeConnection(this._allConnections[0], onEnd); + } + + if (waitingClose === 0) { + process.nextTick(onEnd); + } +}; + +Pool.prototype.query = function (sql, values, cb) { + var query = Connection.createQuery(sql, values, cb); + + if (!(typeof sql === 'object' && 'typeCast' in sql)) { + query.typeCast = this.config.connectionConfig.typeCast; + } + + if (this.config.connectionConfig.trace) { + // Long stack trace support + query._callSite = new Error(); + } + + this.getConnection(function (err, conn) { + if (err) { + query.on('error', function () {}); + query.end(err); + return; + } + + // Release connection based off event + query.once('end', function() { + conn.release(); + }); + + conn.query(query); + }); + + return query; +}; + +Pool.prototype._enqueueCallback = function _enqueueCallback(callback) { + + if (this.config.queueLimit && this._connectionQueue.length >= this.config.queueLimit) { + process.nextTick(function () { + var err = new Error('Queue limit reached.'); + err.code = 'POOL_ENQUEUELIMIT'; + callback(err); + }); + return; + } + + // Bind to domain, as dequeue will likely occur in a different domain + var cb = process.domain + ? process.domain.bind(callback) + : callback; + + this._connectionQueue.push(cb); + this.emit('enqueue'); +}; + +Pool.prototype._needsChangeUser = function _needsChangeUser(connection) { + var connConfig = connection.config; + var poolConfig = this.config.connectionConfig; + + // check if changeUser values are different + return connConfig.user !== poolConfig.user + || connConfig.database !== poolConfig.database + || connConfig.password !== poolConfig.password + || connConfig.charsetNumber !== poolConfig.charsetNumber; +}; + +Pool.prototype._purgeConnection = function _purgeConnection(connection, callback) { + var cb = callback || function () {}; + + if (connection.state === 'disconnected') { + connection.destroy(); + } + + this._removeConnection(connection); + + if (connection.state !== 'disconnected' && !connection._protocol._quitSequence) { + connection._realEnd(cb); + return; + } + + process.nextTick(cb); +}; + +Pool.prototype._removeConnection = function(connection) { + connection._pool = null; + + // Remove connection from all connections + spliceConnection(this._allConnections, connection); + + // Remove connection from free connections + spliceConnection(this._freeConnections, connection); + + this.releaseConnection(connection); +}; + +Pool.prototype.escape = function(value) { + return mysql.escape(value, this.config.connectionConfig.stringifyObjects, this.config.connectionConfig.timezone); +}; + +Pool.prototype.escapeId = function escapeId(value) { + return mysql.escapeId(value, false); +}; + +function spliceConnection(array, connection) { + var index; + if ((index = array.indexOf(connection)) !== -1) { + // Remove connection from all connections + array.splice(index, 1); + } +} diff --git a/node_modules/mysql/lib/PoolCluster.js b/node_modules/mysql/lib/PoolCluster.js new file mode 100644 index 0000000000000000000000000000000000000000..d0aed2c75d3da46ff72423bb5e470dee0242d6bb --- /dev/null +++ b/node_modules/mysql/lib/PoolCluster.js @@ -0,0 +1,288 @@ +var Pool = require('./Pool'); +var PoolConfig = require('./PoolConfig'); +var PoolNamespace = require('./PoolNamespace'); +var PoolSelector = require('./PoolSelector'); +var Util = require('util'); +var EventEmitter = require('events').EventEmitter; + +module.exports = PoolCluster; + +/** + * PoolCluster + * @constructor + * @param {object} [config] The pool cluster configuration + * @public + */ +function PoolCluster(config) { + EventEmitter.call(this); + + config = config || {}; + this._canRetry = typeof config.canRetry === 'undefined' ? true : config.canRetry; + this._defaultSelector = config.defaultSelector || 'RR'; + this._removeNodeErrorCount = config.removeNodeErrorCount || 5; + this._restoreNodeTimeout = config.restoreNodeTimeout || 0; + + this._closed = false; + this._findCaches = Object.create(null); + this._lastId = 0; + this._namespaces = Object.create(null); + this._nodes = Object.create(null); +} + +Util.inherits(PoolCluster, EventEmitter); + +PoolCluster.prototype.add = function add(id, config) { + if (this._closed) { + throw new Error('PoolCluster is closed.'); + } + + var nodeId = typeof id === 'object' + ? 'CLUSTER::' + (++this._lastId) + : String(id); + + if (this._nodes[nodeId] !== undefined) { + throw new Error('Node ID "' + nodeId + '" is already defined in PoolCluster.'); + } + + var poolConfig = typeof id !== 'object' + ? new PoolConfig(config) + : new PoolConfig(id); + + this._nodes[nodeId] = { + id : nodeId, + errorCount : 0, + pool : new Pool({config: poolConfig}), + _offlineUntil : 0 + }; + + this._clearFindCaches(); +}; + +PoolCluster.prototype.end = function end(callback) { + var cb = callback !== undefined + ? callback + : _cb; + + if (typeof cb !== 'function') { + throw TypeError('callback argument must be a function'); + } + + if (this._closed) { + process.nextTick(cb); + return; + } + + this._closed = true; + + var calledBack = false; + var nodeIds = Object.keys(this._nodes); + var waitingClose = 0; + + function onEnd(err) { + if (!calledBack && (err || --waitingClose <= 0)) { + calledBack = true; + cb(err); + } + } + + for (var i = 0; i < nodeIds.length; i++) { + var nodeId = nodeIds[i]; + var node = this._nodes[nodeId]; + + waitingClose++; + node.pool.end(onEnd); + } + + if (waitingClose === 0) { + process.nextTick(onEnd); + } +}; + +PoolCluster.prototype.of = function(pattern, selector) { + pattern = pattern || '*'; + + selector = selector || this._defaultSelector; + selector = selector.toUpperCase(); + if (typeof PoolSelector[selector] === 'undefined') { + selector = this._defaultSelector; + } + + var key = pattern + selector; + + if (typeof this._namespaces[key] === 'undefined') { + this._namespaces[key] = new PoolNamespace(this, pattern, selector); + } + + return this._namespaces[key]; +}; + +PoolCluster.prototype.remove = function remove(pattern) { + var foundNodeIds = this._findNodeIds(pattern, true); + + for (var i = 0; i < foundNodeIds.length; i++) { + var node = this._getNode(foundNodeIds[i]); + + if (node) { + this._removeNode(node); + } + } +}; + +PoolCluster.prototype.getConnection = function(pattern, selector, cb) { + var namespace; + if (typeof pattern === 'function') { + cb = pattern; + namespace = this.of(); + } else { + if (typeof selector === 'function') { + cb = selector; + selector = this._defaultSelector; + } + + namespace = this.of(pattern, selector); + } + + namespace.getConnection(cb); +}; + +PoolCluster.prototype._clearFindCaches = function _clearFindCaches() { + this._findCaches = Object.create(null); +}; + +PoolCluster.prototype._decreaseErrorCount = function _decreaseErrorCount(node) { + var errorCount = node.errorCount; + + if (errorCount > this._removeNodeErrorCount) { + errorCount = this._removeNodeErrorCount; + } + + if (errorCount < 1) { + errorCount = 1; + } + + node.errorCount = errorCount - 1; + + if (node._offlineUntil) { + node._offlineUntil = 0; + this.emit('online', node.id); + } +}; + +PoolCluster.prototype._findNodeIds = function _findNodeIds(pattern, includeOffline) { + var currentTime = 0; + var foundNodeIds = this._findCaches[pattern]; + + if (foundNodeIds === undefined) { + var expression = patternRegExp(pattern); + var nodeIds = Object.keys(this._nodes); + + foundNodeIds = nodeIds.filter(function (id) { + return id.match(expression); + }); + + this._findCaches[pattern] = foundNodeIds; + } + + if (includeOffline) { + return foundNodeIds; + } + + return foundNodeIds.filter(function (nodeId) { + var node = this._getNode(nodeId); + + if (!node._offlineUntil) { + return true; + } + + if (!currentTime) { + currentTime = getMonotonicMilliseconds(); + } + + return node._offlineUntil <= currentTime; + }, this); +}; + +PoolCluster.prototype._getNode = function _getNode(id) { + return this._nodes[id] || null; +}; + +PoolCluster.prototype._increaseErrorCount = function _increaseErrorCount(node) { + var errorCount = ++node.errorCount; + + if (this._removeNodeErrorCount > errorCount) { + return; + } + + if (this._restoreNodeTimeout > 0) { + node._offlineUntil = getMonotonicMilliseconds() + this._restoreNodeTimeout; + this.emit('offline', node.id); + return; + } + + this._removeNode(node); + this.emit('remove', node.id); +}; + +PoolCluster.prototype._getConnection = function(node, cb) { + var self = this; + + node.pool.getConnection(function (err, connection) { + if (err) { + self._increaseErrorCount(node); + cb(err); + return; + } else { + self._decreaseErrorCount(node); + } + + connection._clusterId = node.id; + + cb(null, connection); + }); +}; + +PoolCluster.prototype._removeNode = function _removeNode(node) { + delete this._nodes[node.id]; + + this._clearFindCaches(); + + node.pool.end(_noop); +}; + +function getMonotonicMilliseconds() { + var ms; + + if (typeof process.hrtime === 'function') { + ms = process.hrtime(); + ms = ms[0] * 1e3 + ms[1] * 1e-6; + } else { + ms = process.uptime() * 1000; + } + + return Math.floor(ms); +} + +function isRegExp(val) { + return typeof val === 'object' + && Object.prototype.toString.call(val) === '[object RegExp]'; +} + +function patternRegExp(pattern) { + if (isRegExp(pattern)) { + return pattern; + } + + var source = pattern + .replace(/([.+?^=!:${}()|\[\]\/\\])/g, '\\$1') + .replace(/\*/g, '.*'); + + return new RegExp('^' + source + '$'); +} + +function _cb(err) { + if (err) { + throw err; + } +} + +function _noop() {} diff --git a/node_modules/mysql/lib/PoolConfig.js b/node_modules/mysql/lib/PoolConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..8c5017a27e66c55643e400d9eca5089b0be10f84 --- /dev/null +++ b/node_modules/mysql/lib/PoolConfig.js @@ -0,0 +1,32 @@ + +var ConnectionConfig = require('./ConnectionConfig'); + +module.exports = PoolConfig; +function PoolConfig(options) { + if (typeof options === 'string') { + options = ConnectionConfig.parseUrl(options); + } + + this.acquireTimeout = (options.acquireTimeout === undefined) + ? 10 * 1000 + : Number(options.acquireTimeout); + this.connectionConfig = new ConnectionConfig(options); + this.waitForConnections = (options.waitForConnections === undefined) + ? true + : Boolean(options.waitForConnections); + this.connectionLimit = (options.connectionLimit === undefined) + ? 10 + : Number(options.connectionLimit); + this.queueLimit = (options.queueLimit === undefined) + ? 0 + : Number(options.queueLimit); +} + +PoolConfig.prototype.newConnectionConfig = function newConnectionConfig() { + var connectionConfig = new ConnectionConfig(this.connectionConfig); + + connectionConfig.clientFlags = this.connectionConfig.clientFlags; + connectionConfig.maxPacketSize = this.connectionConfig.maxPacketSize; + + return connectionConfig; +}; diff --git a/node_modules/mysql/lib/PoolConnection.js b/node_modules/mysql/lib/PoolConnection.js new file mode 100644 index 0000000000000000000000000000000000000000..064c99d32a72014cef8fb4ebc6abdefdae4b372e --- /dev/null +++ b/node_modules/mysql/lib/PoolConnection.js @@ -0,0 +1,65 @@ +var inherits = require('util').inherits; +var Connection = require('./Connection'); +var Events = require('events'); + +module.exports = PoolConnection; +inherits(PoolConnection, Connection); + +function PoolConnection(pool, options) { + Connection.call(this, options); + this._pool = pool; + + // Bind connection to pool domain + if (Events.usingDomains) { + this.domain = pool.domain; + } + + // When a fatal error occurs the connection's protocol ends, which will cause + // the connection to end as well, thus we only need to watch for the end event + // and we will be notified of disconnects. + this.on('end', this._removeFromPool); + this.on('error', function (err) { + if (err.fatal) { + this._removeFromPool(); + } + }); +} + +PoolConnection.prototype.release = function release() { + var pool = this._pool; + + if (!pool || pool._closed) { + return undefined; + } + + return pool.releaseConnection(this); +}; + +// TODO: Remove this when we are removing PoolConnection#end +PoolConnection.prototype._realEnd = Connection.prototype.end; + +PoolConnection.prototype.end = function () { + console.warn( + 'Calling conn.end() to release a pooled connection is ' + + 'deprecated. In next version calling conn.end() will be ' + + 'restored to default conn.end() behavior. Use ' + + 'conn.release() instead.' + ); + this.release(); +}; + +PoolConnection.prototype.destroy = function () { + Connection.prototype.destroy.apply(this, arguments); + this._removeFromPool(this); +}; + +PoolConnection.prototype._removeFromPool = function _removeFromPool() { + if (!this._pool || this._pool._closed) { + return; + } + + var pool = this._pool; + this._pool = null; + + pool._purgeConnection(this); +}; diff --git a/node_modules/mysql/lib/PoolNamespace.js b/node_modules/mysql/lib/PoolNamespace.js new file mode 100644 index 0000000000000000000000000000000000000000..d3ea7860f6ba2e800550643e30863e065c2e668c --- /dev/null +++ b/node_modules/mysql/lib/PoolNamespace.js @@ -0,0 +1,136 @@ +var Connection = require('./Connection'); +var PoolSelector = require('./PoolSelector'); + +module.exports = PoolNamespace; + +/** + * PoolNamespace + * @constructor + * @param {PoolCluster} cluster The parent cluster for the namespace + * @param {string} pattern The selection pattern to use + * @param {string} selector The selector name to use + * @public + */ +function PoolNamespace(cluster, pattern, selector) { + this._cluster = cluster; + this._pattern = pattern; + this._selector = new PoolSelector[selector](); +} + +PoolNamespace.prototype.getConnection = function(cb) { + var clusterNode = this._getClusterNode(); + var cluster = this._cluster; + var namespace = this; + + if (clusterNode === null) { + var err = null; + + if (this._cluster._findNodeIds(this._pattern, true).length !== 0) { + err = new Error('Pool does not have online node.'); + err.code = 'POOL_NONEONLINE'; + } else { + err = new Error('Pool does not exist.'); + err.code = 'POOL_NOEXIST'; + } + + cb(err); + return; + } + + cluster._getConnection(clusterNode, function(err, connection) { + var retry = err && cluster._canRetry + && cluster._findNodeIds(namespace._pattern).length !== 0; + + if (retry) { + namespace.getConnection(cb); + return; + } + + if (err) { + cb(err); + return; + } + + cb(null, connection); + }); +}; + +PoolNamespace.prototype.query = function (sql, values, cb) { + var cluster = this._cluster; + var clusterNode = this._getClusterNode(); + var query = Connection.createQuery(sql, values, cb); + var namespace = this; + + if (clusterNode === null) { + var err = null; + + if (this._cluster._findNodeIds(this._pattern, true).length !== 0) { + err = new Error('Pool does not have online node.'); + err.code = 'POOL_NONEONLINE'; + } else { + err = new Error('Pool does not exist.'); + err.code = 'POOL_NOEXIST'; + } + + process.nextTick(function () { + query.on('error', function () {}); + query.end(err); + }); + return query; + } + + if (!(typeof sql === 'object' && 'typeCast' in sql)) { + query.typeCast = clusterNode.pool.config.connectionConfig.typeCast; + } + + if (clusterNode.pool.config.connectionConfig.trace) { + // Long stack trace support + query._callSite = new Error(); + } + + cluster._getConnection(clusterNode, function (err, conn) { + var retry = err && cluster._canRetry + && cluster._findNodeIds(namespace._pattern).length !== 0; + + if (retry) { + namespace.query(query); + return; + } + + if (err) { + query.on('error', function () {}); + query.end(err); + return; + } + + // Release connection based off event + query.once('end', function() { + conn.release(); + }); + + conn.query(query); + }); + + return query; +}; + +PoolNamespace.prototype._getClusterNode = function _getClusterNode() { + var foundNodeIds = this._cluster._findNodeIds(this._pattern); + var nodeId; + + switch (foundNodeIds.length) { + case 0: + nodeId = null; + break; + case 1: + nodeId = foundNodeIds[0]; + break; + default: + nodeId = this._selector(foundNodeIds); + break; + } + + return nodeId !== null + ? this._cluster._getNode(nodeId) + : null; +}; diff --git a/node_modules/mysql/lib/PoolSelector.js b/node_modules/mysql/lib/PoolSelector.js new file mode 100644 index 0000000000000000000000000000000000000000..9a3c455f2007efb33d9e866226c13ef05b642e47 --- /dev/null +++ b/node_modules/mysql/lib/PoolSelector.js @@ -0,0 +1,31 @@ + +/** + * PoolSelector + */ +var PoolSelector = module.exports = {}; + +PoolSelector.RR = function PoolSelectorRoundRobin() { + var index = 0; + + return function(clusterIds) { + if (index >= clusterIds.length) { + index = 0; + } + + var clusterId = clusterIds[index++]; + + return clusterId; + }; +}; + +PoolSelector.RANDOM = function PoolSelectorRandom() { + return function(clusterIds) { + return clusterIds[Math.floor(Math.random() * clusterIds.length)]; + }; +}; + +PoolSelector.ORDER = function PoolSelectorOrder() { + return function(clusterIds) { + return clusterIds[0]; + }; +}; diff --git a/node_modules/mysql/lib/protocol/Auth.js b/node_modules/mysql/lib/protocol/Auth.js new file mode 100644 index 0000000000000000000000000000000000000000..e00e893a4bb4a95a262114a55eafb453422732e2 --- /dev/null +++ b/node_modules/mysql/lib/protocol/Auth.js @@ -0,0 +1,152 @@ +var Buffer = require('safe-buffer').Buffer; +var Crypto = require('crypto'); +var Auth = exports; + +function sha1(msg) { + var hash = Crypto.createHash('sha1'); + hash.update(msg, 'binary'); + return hash.digest('binary'); +} +Auth.sha1 = sha1; + +function xor(a, b) { + a = Buffer.from(a, 'binary'); + b = Buffer.from(b, 'binary'); + var result = Buffer.allocUnsafe(a.length); + for (var i = 0; i < a.length; i++) { + result[i] = (a[i] ^ b[i]); + } + return result; +} +Auth.xor = xor; + +Auth.token = function(password, scramble) { + if (!password) { + return Buffer.alloc(0); + } + + // password must be in binary format, not utf8 + var stage1 = sha1((Buffer.from(password, 'utf8')).toString('binary')); + var stage2 = sha1(stage1); + var stage3 = sha1(scramble.toString('binary') + stage2); + return xor(stage3, stage1); +}; + +// This is a port of sql/password.c:hash_password which needs to be used for +// pre-4.1 passwords. +Auth.hashPassword = function(password) { + var nr = [0x5030, 0x5735]; + var add = 7; + var nr2 = [0x1234, 0x5671]; + var result = Buffer.alloc(8); + + if (typeof password === 'string'){ + password = Buffer.from(password); + } + + for (var i = 0; i < password.length; i++) { + var c = password[i]; + if (c === 32 || c === 9) { + // skip space in password + continue; + } + + // nr^= (((nr & 63)+add)*c)+ (nr << 8); + // nr = xor(nr, add(mul(add(and(nr, 63), add), c), shl(nr, 8))) + nr = this.xor32(nr, this.add32(this.mul32(this.add32(this.and32(nr, [0, 63]), [0, add]), [0, c]), this.shl32(nr, 8))); + + // nr2+=(nr2 << 8) ^ nr; + // nr2 = add(nr2, xor(shl(nr2, 8), nr)) + nr2 = this.add32(nr2, this.xor32(this.shl32(nr2, 8), nr)); + + // add+=tmp; + add += c; + } + + this.int31Write(result, nr, 0); + this.int31Write(result, nr2, 4); + + return result; +}; + +Auth.randomInit = function(seed1, seed2) { + return { + max_value : 0x3FFFFFFF, + max_value_dbl : 0x3FFFFFFF, + seed1 : seed1 % 0x3FFFFFFF, + seed2 : seed2 % 0x3FFFFFFF + }; +}; + +Auth.myRnd = function(r){ + r.seed1 = (r.seed1 * 3 + r.seed2) % r.max_value; + r.seed2 = (r.seed1 + r.seed2 + 33) % r.max_value; + + return r.seed1 / r.max_value_dbl; +}; + +Auth.scramble323 = function(message, password) { + var to = Buffer.allocUnsafe(8); + var hashPass = this.hashPassword(password); + var hashMessage = this.hashPassword(message.slice(0, 8)); + var seed1 = this.int32Read(hashPass, 0) ^ this.int32Read(hashMessage, 0); + var seed2 = this.int32Read(hashPass, 4) ^ this.int32Read(hashMessage, 4); + var r = this.randomInit(seed1, seed2); + + for (var i = 0; i < 8; i++){ + to[i] = Math.floor(this.myRnd(r) * 31) + 64; + } + var extra = (Math.floor(this.myRnd(r) * 31)); + + for (var i = 0; i < 8; i++){ + to[i] ^= extra; + } + + return to; +}; + +Auth.xor32 = function(a, b){ + return [a[0] ^ b[0], a[1] ^ b[1]]; +}; + +Auth.add32 = function(a, b){ + var w1 = a[1] + b[1]; + var w2 = a[0] + b[0] + ((w1 & 0xFFFF0000) >> 16); + + return [w2 & 0xFFFF, w1 & 0xFFFF]; +}; + +Auth.mul32 = function(a, b){ + // based on this example of multiplying 32b ints using 16b + // http://www.dsprelated.com/showmessage/89790/1.php + var w1 = a[1] * b[1]; + var w2 = (((a[1] * b[1]) >> 16) & 0xFFFF) + ((a[0] * b[1]) & 0xFFFF) + (a[1] * b[0] & 0xFFFF); + + return [w2 & 0xFFFF, w1 & 0xFFFF]; +}; + +Auth.and32 = function(a, b){ + return [a[0] & b[0], a[1] & b[1]]; +}; + +Auth.shl32 = function(a, b){ + // assume b is 16 or less + var w1 = a[1] << b; + var w2 = (a[0] << b) | ((w1 & 0xFFFF0000) >> 16); + + return [w2 & 0xFFFF, w1 & 0xFFFF]; +}; + +Auth.int31Write = function(buffer, number, offset) { + buffer[offset] = (number[0] >> 8) & 0x7F; + buffer[offset + 1] = (number[0]) & 0xFF; + buffer[offset + 2] = (number[1] >> 8) & 0xFF; + buffer[offset + 3] = (number[1]) & 0xFF; +}; + +Auth.int32Read = function(buffer, offset){ + return (buffer[offset] << 24) + + (buffer[offset + 1] << 16) + + (buffer[offset + 2] << 8) + + (buffer[offset + 3]); +}; diff --git a/node_modules/mysql/lib/protocol/BufferList.js b/node_modules/mysql/lib/protocol/BufferList.js new file mode 100644 index 0000000000000000000000000000000000000000..3cd01926a01ff6979cfd5754fc9f6a6e8c5d7008 --- /dev/null +++ b/node_modules/mysql/lib/protocol/BufferList.js @@ -0,0 +1,25 @@ + +module.exports = BufferList; +function BufferList() { + this.bufs = []; + this.size = 0; +} + +BufferList.prototype.shift = function shift() { + var buf = this.bufs.shift(); + + if (buf) { + this.size -= buf.length; + } + + return buf; +}; + +BufferList.prototype.push = function push(buf) { + if (!buf || !buf.length) { + return; + } + + this.bufs.push(buf); + this.size += buf.length; +}; diff --git a/node_modules/mysql/lib/protocol/PacketHeader.js b/node_modules/mysql/lib/protocol/PacketHeader.js new file mode 100644 index 0000000000000000000000000000000000000000..1bb282e4bb79356edd4e16f65c08e44aaef14c6e --- /dev/null +++ b/node_modules/mysql/lib/protocol/PacketHeader.js @@ -0,0 +1,5 @@ +module.exports = PacketHeader; +function PacketHeader(length, number) { + this.length = length; + this.number = number; +} diff --git a/node_modules/mysql/lib/protocol/PacketWriter.js b/node_modules/mysql/lib/protocol/PacketWriter.js new file mode 100644 index 0000000000000000000000000000000000000000..4d0afd2af34a5b099244ddeb8bb612f0c63e9235 --- /dev/null +++ b/node_modules/mysql/lib/protocol/PacketWriter.js @@ -0,0 +1,211 @@ +var BIT_16 = Math.pow(2, 16); +var BIT_24 = Math.pow(2, 24); +var BUFFER_ALLOC_SIZE = Math.pow(2, 8); +// The maximum precision JS Numbers can hold precisely +// Don't panic: Good enough to represent byte values up to 8192 TB +var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53); +var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1; +var Buffer = require('safe-buffer').Buffer; + +module.exports = PacketWriter; +function PacketWriter() { + this._buffer = null; + this._offset = 0; +} + +PacketWriter.prototype.toBuffer = function toBuffer(parser) { + if (!this._buffer) { + this._buffer = Buffer.alloc(0); + this._offset = 0; + } + + var buffer = this._buffer; + var length = this._offset; + var packets = Math.floor(length / MAX_PACKET_LENGTH) + 1; + + this._buffer = Buffer.allocUnsafe(length + packets * 4); + this._offset = 0; + + for (var packet = 0; packet < packets; packet++) { + var isLast = (packet + 1 === packets); + var packetLength = (isLast) + ? length % MAX_PACKET_LENGTH + : MAX_PACKET_LENGTH; + + var packetNumber = parser.incrementPacketNumber(); + + this.writeUnsignedNumber(3, packetLength); + this.writeUnsignedNumber(1, packetNumber); + + var start = packet * MAX_PACKET_LENGTH; + var end = start + packetLength; + + this.writeBuffer(buffer.slice(start, end)); + } + + return this._buffer; +}; + +PacketWriter.prototype.writeUnsignedNumber = function(bytes, value) { + this._allocate(bytes); + + for (var i = 0; i < bytes; i++) { + this._buffer[this._offset++] = (value >> (i * 8)) & 0xff; + } +}; + +PacketWriter.prototype.writeFiller = function(bytes) { + this._allocate(bytes); + + for (var i = 0; i < bytes; i++) { + this._buffer[this._offset++] = 0x00; + } +}; + +PacketWriter.prototype.writeNullTerminatedString = function(value, encoding) { + // Typecast undefined into '' and numbers into strings + value = value || ''; + value = value + ''; + + var bytes = Buffer.byteLength(value, encoding || 'utf-8') + 1; + this._allocate(bytes); + + this._buffer.write(value, this._offset, encoding); + this._buffer[this._offset + bytes - 1] = 0x00; + + this._offset += bytes; +}; + +PacketWriter.prototype.writeString = function(value) { + // Typecast undefined into '' and numbers into strings + value = value || ''; + value = value + ''; + + var bytes = Buffer.byteLength(value, 'utf-8'); + this._allocate(bytes); + + this._buffer.write(value, this._offset, 'utf-8'); + + this._offset += bytes; +}; + +PacketWriter.prototype.writeBuffer = function(value) { + var bytes = value.length; + + this._allocate(bytes); + value.copy(this._buffer, this._offset); + this._offset += bytes; +}; + +PacketWriter.prototype.writeLengthCodedNumber = function(value) { + if (value === null) { + this._allocate(1); + this._buffer[this._offset++] = 251; + return; + } + + if (value <= 250) { + this._allocate(1); + this._buffer[this._offset++] = value; + return; + } + + if (value > IEEE_754_BINARY_64_PRECISION) { + throw new Error( + 'writeLengthCodedNumber: JS precision range exceeded, your ' + + 'number is > 53 bit: "' + value + '"' + ); + } + + if (value < BIT_16) { + this._allocate(3); + this._buffer[this._offset++] = 252; + } else if (value < BIT_24) { + this._allocate(4); + this._buffer[this._offset++] = 253; + } else { + this._allocate(9); + this._buffer[this._offset++] = 254; + } + + // 16 Bit + this._buffer[this._offset++] = value & 0xff; + this._buffer[this._offset++] = (value >> 8) & 0xff; + + if (value < BIT_16) { + return; + } + + // 24 Bit + this._buffer[this._offset++] = (value >> 16) & 0xff; + + if (value < BIT_24) { + return; + } + + this._buffer[this._offset++] = (value >> 24) & 0xff; + + // Hack: Get the most significant 32 bit (JS bitwise operators are 32 bit) + value = value.toString(2); + value = value.substr(0, value.length - 32); + value = parseInt(value, 2); + + this._buffer[this._offset++] = value & 0xff; + this._buffer[this._offset++] = (value >> 8) & 0xff; + this._buffer[this._offset++] = (value >> 16) & 0xff; + + // Set last byte to 0, as we can only support 53 bits in JS (see above) + this._buffer[this._offset++] = 0; +}; + +PacketWriter.prototype.writeLengthCodedBuffer = function(value) { + var bytes = value.length; + this.writeLengthCodedNumber(bytes); + this.writeBuffer(value); +}; + +PacketWriter.prototype.writeNullTerminatedBuffer = function(value) { + this.writeBuffer(value); + this.writeFiller(1); // 0x00 terminator +}; + +PacketWriter.prototype.writeLengthCodedString = function(value) { + if (value === null) { + this.writeLengthCodedNumber(null); + return; + } + + value = (value === undefined) + ? '' + : String(value); + + var bytes = Buffer.byteLength(value, 'utf-8'); + this.writeLengthCodedNumber(bytes); + + if (!bytes) { + return; + } + + this._allocate(bytes); + this._buffer.write(value, this._offset, 'utf-8'); + this._offset += bytes; +}; + +PacketWriter.prototype._allocate = function _allocate(bytes) { + if (!this._buffer) { + this._buffer = Buffer.alloc(Math.max(BUFFER_ALLOC_SIZE, bytes)); + this._offset = 0; + return; + } + + var bytesRemaining = this._buffer.length - this._offset; + if (bytesRemaining >= bytes) { + return; + } + + var newSize = this._buffer.length + Math.max(BUFFER_ALLOC_SIZE, bytes); + var oldBuffer = this._buffer; + + this._buffer = Buffer.alloc(newSize); + oldBuffer.copy(this._buffer); +}; diff --git a/node_modules/mysql/lib/protocol/Parser.js b/node_modules/mysql/lib/protocol/Parser.js new file mode 100644 index 0000000000000000000000000000000000000000..a7f5859888af48d535c3f60f1589c23c7bf1a341 --- /dev/null +++ b/node_modules/mysql/lib/protocol/Parser.js @@ -0,0 +1,476 @@ +var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1; +var MUL_32BIT = Math.pow(2, 32); +var PacketHeader = require('./PacketHeader'); +var BigNumber = require('bignumber.js'); +var Buffer = require('safe-buffer').Buffer; +var BufferList = require('./BufferList'); + +module.exports = Parser; +function Parser(options) { + options = options || {}; + + this._supportBigNumbers = options.config && options.config.supportBigNumbers; + this._buffer = Buffer.alloc(0); + this._nextBuffers = new BufferList(); + this._longPacketBuffers = new BufferList(); + this._offset = 0; + this._packetEnd = null; + this._packetHeader = null; + this._packetOffset = null; + this._onError = options.onError || function(err) { throw err; }; + this._onPacket = options.onPacket || function() {}; + this._nextPacketNumber = 0; + this._encoding = 'utf-8'; + this._paused = false; +} + +Parser.prototype.write = function write(chunk) { + this._nextBuffers.push(chunk); + + while (!this._paused) { + if (!this._packetHeader) { + if (!this._combineNextBuffers(4)) { + break; + } + + this._packetHeader = new PacketHeader( + this.parseUnsignedNumber(3), + this.parseUnsignedNumber(1) + ); + + if (this._packetHeader.number !== this._nextPacketNumber) { + var err = new Error( + 'Packets out of order. Got: ' + this._packetHeader.number + ' ' + + 'Expected: ' + this._nextPacketNumber + ); + + err.code = 'PROTOCOL_PACKETS_OUT_OF_ORDER'; + err.fatal = true; + + this._onError(err); + } + + this.incrementPacketNumber(); + } + + if (!this._combineNextBuffers(this._packetHeader.length)) { + break; + } + + this._packetEnd = this._offset + this._packetHeader.length; + this._packetOffset = this._offset; + + if (this._packetHeader.length === MAX_PACKET_LENGTH) { + this._longPacketBuffers.push(this._buffer.slice(this._packetOffset, this._packetEnd)); + + this._advanceToNextPacket(); + continue; + } + + this._combineLongPacketBuffers(); + + // Try...finally to ensure exception safety. Unfortunately this is costing + // us up to ~10% performance in some benchmarks. + var hadException = true; + try { + this._onPacket(this._packetHeader); + hadException = false; + } catch (err) { + if (!err || typeof err.code !== 'string' || err.code.substr(0, 7) !== 'PARSER_') { + throw err; // Rethrow non-MySQL errors + } + + // Pass down parser errors + this._onError(err); + hadException = false; + } finally { + this._advanceToNextPacket(); + + // If we had an exception, the parser while loop will be broken out + // of after the finally block. So we need to make sure to re-enter it + // to continue parsing any bytes that may already have been received. + if (hadException) { + process.nextTick(this.write.bind(this)); + } + } + } +}; + +Parser.prototype.append = function append(chunk) { + if (!chunk || chunk.length === 0) { + return; + } + + // Calculate slice ranges + var sliceEnd = this._buffer.length; + var sliceStart = this._packetOffset === null + ? this._offset + : this._packetOffset; + var sliceLength = sliceEnd - sliceStart; + + // Get chunk data + var buffer = null; + var chunks = !(chunk instanceof Array || Array.isArray(chunk)) ? [chunk] : chunk; + var length = 0; + var offset = 0; + + for (var i = 0; i < chunks.length; i++) { + length += chunks[i].length; + } + + if (sliceLength !== 0) { + // Create a new Buffer + buffer = Buffer.allocUnsafe(sliceLength + length); + offset = 0; + + // Copy data slice + offset += this._buffer.copy(buffer, 0, sliceStart, sliceEnd); + + // Copy chunks + for (var i = 0; i < chunks.length; i++) { + offset += chunks[i].copy(buffer, offset); + } + } else if (chunks.length > 1) { + // Create a new Buffer + buffer = Buffer.allocUnsafe(length); + offset = 0; + + // Copy chunks + for (var i = 0; i < chunks.length; i++) { + offset += chunks[i].copy(buffer, offset); + } + } else { + // Buffer is the only chunk + buffer = chunks[0]; + } + + // Adjust data-tracking pointers + this._buffer = buffer; + this._offset = this._offset - sliceStart; + this._packetEnd = this._packetEnd !== null + ? this._packetEnd - sliceStart + : null; + this._packetOffset = this._packetOffset !== null + ? this._packetOffset - sliceStart + : null; +}; + +Parser.prototype.pause = function() { + this._paused = true; +}; + +Parser.prototype.resume = function() { + this._paused = false; + + // nextTick() to avoid entering write() multiple times within the same stack + // which would cause problems as write manipulates the state of the object. + process.nextTick(this.write.bind(this)); +}; + +Parser.prototype.peak = function peak(offset) { + return this._buffer[this._offset + (offset >>> 0)]; +}; + +Parser.prototype.parseUnsignedNumber = function parseUnsignedNumber(bytes) { + if (bytes === 1) { + return this._buffer[this._offset++]; + } + + var buffer = this._buffer; + var offset = this._offset + bytes - 1; + var value = 0; + + if (bytes > 4) { + var err = new Error('parseUnsignedNumber: Supports only up to 4 bytes'); + err.offset = (this._offset - this._packetOffset - 1); + err.code = 'PARSER_UNSIGNED_TOO_LONG'; + throw err; + } + + while (offset >= this._offset) { + value = ((value << 8) | buffer[offset]) >>> 0; + offset--; + } + + this._offset += bytes; + + return value; +}; + +Parser.prototype.parseLengthCodedString = function() { + var length = this.parseLengthCodedNumber(); + + if (length === null) { + return null; + } + + return this.parseString(length); +}; + +Parser.prototype.parseLengthCodedBuffer = function() { + var length = this.parseLengthCodedNumber(); + + if (length === null) { + return null; + } + + return this.parseBuffer(length); +}; + +Parser.prototype.parseLengthCodedNumber = function parseLengthCodedNumber() { + if (this._offset >= this._buffer.length) { + var err = new Error('Parser: read past end'); + err.offset = (this._offset - this._packetOffset); + err.code = 'PARSER_READ_PAST_END'; + throw err; + } + + var bits = this._buffer[this._offset++]; + + if (bits <= 250) { + return bits; + } + + switch (bits) { + case 251: + return null; + case 252: + return this.parseUnsignedNumber(2); + case 253: + return this.parseUnsignedNumber(3); + case 254: + break; + default: + var err = new Error('Unexpected first byte' + (bits ? ': 0x' + bits.toString(16) : '')); + err.offset = (this._offset - this._packetOffset - 1); + err.code = 'PARSER_BAD_LENGTH_BYTE'; + throw err; + } + + var low = this.parseUnsignedNumber(4); + var high = this.parseUnsignedNumber(4); + var value; + + if (high >>> 21) { + value = (new BigNumber(low)).plus((new BigNumber(MUL_32BIT)).times(high)).toString(); + + if (this._supportBigNumbers) { + return value; + } + + var err = new Error( + 'parseLengthCodedNumber: JS precision range exceeded, ' + + 'number is >= 53 bit: "' + value + '"' + ); + err.offset = (this._offset - this._packetOffset - 8); + err.code = 'PARSER_JS_PRECISION_RANGE_EXCEEDED'; + throw err; + } + + value = low + (MUL_32BIT * high); + + return value; +}; + +Parser.prototype.parseFiller = function(length) { + return this.parseBuffer(length); +}; + +Parser.prototype.parseNullTerminatedBuffer = function() { + var end = this._nullByteOffset(); + var value = this._buffer.slice(this._offset, end); + this._offset = end + 1; + + return value; +}; + +Parser.prototype.parseNullTerminatedString = function() { + var end = this._nullByteOffset(); + var value = this._buffer.toString(this._encoding, this._offset, end); + this._offset = end + 1; + + return value; +}; + +Parser.prototype._nullByteOffset = function() { + var offset = this._offset; + + while (this._buffer[offset] !== 0x00) { + offset++; + + if (offset >= this._buffer.length) { + var err = new Error('Offset of null terminated string not found.'); + err.offset = (this._offset - this._packetOffset); + err.code = 'PARSER_MISSING_NULL_BYTE'; + throw err; + } + } + + return offset; +}; + +Parser.prototype.parsePacketTerminatedBuffer = function parsePacketTerminatedBuffer() { + var length = this._packetEnd - this._offset; + return this.parseBuffer(length); +}; + +Parser.prototype.parsePacketTerminatedString = function() { + var length = this._packetEnd - this._offset; + return this.parseString(length); +}; + +Parser.prototype.parseBuffer = function(length) { + var response = Buffer.alloc(length); + this._buffer.copy(response, 0, this._offset, this._offset + length); + + this._offset += length; + return response; +}; + +Parser.prototype.parseString = function(length) { + var offset = this._offset; + var end = offset + length; + var value = this._buffer.toString(this._encoding, offset, end); + + this._offset = end; + return value; +}; + +Parser.prototype.parseGeometryValue = function() { + var buffer = this.parseLengthCodedBuffer(); + var offset = 4; + + if (buffer === null || !buffer.length) { + return null; + } + + function parseGeometry() { + var result = null; + var byteOrder = buffer.readUInt8(offset); offset += 1; + var wkbType = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; + switch (wkbType) { + case 1: // WKBPoint + var x = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + var y = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + result = {x: x, y: y}; + break; + case 2: // WKBLineString + var numPoints = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; + result = []; + for (var i = numPoints; i > 0; i--) { + var x = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + var y = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + result.push({x: x, y: y}); + } + break; + case 3: // WKBPolygon + var numRings = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; + result = []; + for (var i = numRings; i > 0; i--) { + var numPoints = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; + var line = []; + for (var j = numPoints; j > 0; j--) { + var x = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + var y = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8; + line.push({x: x, y: y}); + } + result.push(line); + } + break; + case 4: // WKBMultiPoint + case 5: // WKBMultiLineString + case 6: // WKBMultiPolygon + case 7: // WKBGeometryCollection + var num = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4; + var result = []; + for (var i = num; i > 0; i--) { + result.push(parseGeometry()); + } + break; + } + return result; + } + return parseGeometry(); +}; + +Parser.prototype.reachedPacketEnd = function() { + return this._offset === this._packetEnd; +}; + +Parser.prototype.incrementPacketNumber = function() { + var currentPacketNumber = this._nextPacketNumber; + this._nextPacketNumber = (this._nextPacketNumber + 1) % 256; + + return currentPacketNumber; +}; + +Parser.prototype.resetPacketNumber = function() { + this._nextPacketNumber = 0; +}; + +Parser.prototype.packetLength = function packetLength() { + if (!this._packetHeader) { + return null; + } + + return this._packetHeader.length + this._longPacketBuffers.size; +}; + +Parser.prototype._combineNextBuffers = function _combineNextBuffers(bytes) { + var length = this._buffer.length - this._offset; + + if (length >= bytes) { + return true; + } + + if ((length + this._nextBuffers.size) < bytes) { + return false; + } + + var buffers = []; + var bytesNeeded = bytes - length; + + while (bytesNeeded > 0) { + var buffer = this._nextBuffers.shift(); + buffers.push(buffer); + bytesNeeded -= buffer.length; + } + + this.append(buffers); + return true; +}; + +Parser.prototype._combineLongPacketBuffers = function _combineLongPacketBuffers() { + if (!this._longPacketBuffers.size) { + return; + } + + // Calculate bytes + var remainingBytes = this._buffer.length - this._offset; + var trailingPacketBytes = this._buffer.length - this._packetEnd; + + // Create buffer + var buf = null; + var buffer = Buffer.allocUnsafe(remainingBytes + this._longPacketBuffers.size); + var offset = 0; + + // Copy long buffers + while ((buf = this._longPacketBuffers.shift())) { + offset += buf.copy(buffer, offset); + } + + // Copy remaining bytes + this._buffer.copy(buffer, offset, this._offset); + + this._buffer = buffer; + this._offset = 0; + this._packetEnd = this._buffer.length - trailingPacketBytes; + this._packetOffset = 0; +}; + +Parser.prototype._advanceToNextPacket = function() { + this._offset = this._packetEnd; + this._packetHeader = null; + this._packetEnd = null; + this._packetOffset = null; +}; diff --git a/node_modules/mysql/lib/protocol/Protocol.js b/node_modules/mysql/lib/protocol/Protocol.js new file mode 100644 index 0000000000000000000000000000000000000000..5db4f56e564d72cba68c6119ea65c3716432d9f6 --- /dev/null +++ b/node_modules/mysql/lib/protocol/Protocol.js @@ -0,0 +1,457 @@ +var Parser = require('./Parser'); +var Sequences = require('./sequences'); +var Packets = require('./packets'); +var Stream = require('stream').Stream; +var Util = require('util'); +var PacketWriter = require('./PacketWriter'); + +module.exports = Protocol; +Util.inherits(Protocol, Stream); +function Protocol(options) { + Stream.call(this); + + options = options || {}; + + this.readable = true; + this.writable = true; + + this._config = options.config || {}; + this._connection = options.connection; + this._callback = null; + this._fatalError = null; + this._quitSequence = null; + this._handshake = false; + this._handshaked = false; + this._ended = false; + this._destroyed = false; + this._queue = []; + this._handshakeInitializationPacket = null; + + this._parser = new Parser({ + onError : this.handleParserError.bind(this), + onPacket : this._parsePacket.bind(this), + config : this._config + }); +} + +Protocol.prototype.write = function(buffer) { + this._parser.write(buffer); + return true; +}; + +Protocol.prototype.handshake = function handshake(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + options.config = this._config; + + var sequence = this._enqueue(new Sequences.Handshake(options, callback)); + + this._handshake = true; + + return sequence; +}; + +Protocol.prototype.query = function query(options, callback) { + return this._enqueue(new Sequences.Query(options, callback)); +}; + +Protocol.prototype.changeUser = function changeUser(options, callback) { + return this._enqueue(new Sequences.ChangeUser(options, callback)); +}; + +Protocol.prototype.ping = function ping(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + return this._enqueue(new Sequences.Ping(options, callback)); +}; + +Protocol.prototype.stats = function stats(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + return this._enqueue(new Sequences.Statistics(options, callback)); +}; + +Protocol.prototype.quit = function quit(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var self = this; + var sequence = this._enqueue(new Sequences.Quit(options, callback)); + + sequence.on('end', function () { + self.end(); + }); + + return this._quitSequence = sequence; +}; + +Protocol.prototype.end = function() { + if (this._ended) { + return; + } + this._ended = true; + + if (this._quitSequence && (this._quitSequence._ended || this._queue[0] === this._quitSequence)) { + this._quitSequence.end(); + this.emit('end'); + return; + } + + var err = new Error('Connection lost: The server closed the connection.'); + err.fatal = true; + err.code = 'PROTOCOL_CONNECTION_LOST'; + + this._delegateError(err); +}; + +Protocol.prototype.pause = function() { + this._parser.pause(); + // Since there is a file stream in query, we must transmit pause/resume event to current sequence. + var seq = this._queue[0]; + if (seq && seq.emit) { + seq.emit('pause'); + } +}; + +Protocol.prototype.resume = function() { + this._parser.resume(); + // Since there is a file stream in query, we must transmit pause/resume event to current sequence. + var seq = this._queue[0]; + if (seq && seq.emit) { + seq.emit('resume'); + } +}; + +Protocol.prototype._enqueue = function(sequence) { + if (!this._validateEnqueue(sequence)) { + return sequence; + } + + if (this._config.trace) { + // Long stack trace support + sequence._callSite = sequence._callSite || new Error(); + } + + this._queue.push(sequence); + this.emit('enqueue', sequence); + + var self = this; + sequence + .on('error', function(err) { + self._delegateError(err, sequence); + }) + .on('packet', function(packet) { + sequence._timer.active(); + self._emitPacket(packet); + }) + .on('end', function() { + self._dequeue(sequence); + }) + .on('timeout', function() { + var err = new Error(sequence.constructor.name + ' inactivity timeout'); + + err.code = 'PROTOCOL_SEQUENCE_TIMEOUT'; + err.fatal = true; + err.timeout = sequence._timeout; + + self._delegateError(err, sequence); + }) + .on('start-tls', function() { + sequence._timer.active(); + self._connection._startTLS(function(err) { + if (err) { + // SSL negotiation error are fatal + err.code = 'HANDSHAKE_SSL_ERROR'; + err.fatal = true; + sequence.end(err); + return; + } + + sequence._timer.active(); + sequence._tlsUpgradeCompleteHandler(); + }); + }); + + if (this._queue.length === 1) { + this._parser.resetPacketNumber(); + this._startSequence(sequence); + } + + return sequence; +}; + +Protocol.prototype._validateEnqueue = function _validateEnqueue(sequence) { + var err; + var prefix = 'Cannot enqueue ' + sequence.constructor.name; + + if (this._fatalError) { + err = new Error(prefix + ' after fatal error.'); + err.code = 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR'; + } else if (this._quitSequence) { + err = new Error(prefix + ' after invoking quit.'); + err.code = 'PROTOCOL_ENQUEUE_AFTER_QUIT'; + } else if (this._destroyed) { + err = new Error(prefix + ' after being destroyed.'); + err.code = 'PROTOCOL_ENQUEUE_AFTER_DESTROY'; + } else if ((this._handshake || this._handshaked) && sequence.constructor === Sequences.Handshake) { + err = new Error(prefix + ' after already enqueuing a Handshake.'); + err.code = 'PROTOCOL_ENQUEUE_HANDSHAKE_TWICE'; + } else { + return true; + } + + var self = this; + err.fatal = false; + + // add error handler + sequence.on('error', function (err) { + self._delegateError(err, sequence); + }); + + process.nextTick(function () { + sequence.end(err); + }); + + return false; +}; + +Protocol.prototype._parsePacket = function() { + var sequence = this._queue[0]; + + if (!sequence) { + var err = new Error('Received packet with no active sequence.'); + err.code = 'PROTOCOL_STRAY_PACKET'; + err.fatal = true; + + this._delegateError(err); + return; + } + + var Packet = this._determinePacket(sequence); + var packet = new Packet({protocol41: this._config.protocol41}); + var packetName = Packet.name; + + // Special case: Faster dispatch, and parsing done inside sequence + if (Packet === Packets.RowDataPacket) { + sequence.RowDataPacket(packet, this._parser, this._connection); + + if (this._config.debug) { + this._debugPacket(true, packet); + } + + return; + } + + if (this._config.debug) { + this._parsePacketDebug(packet); + } else { + packet.parse(this._parser); + } + + if (Packet === Packets.HandshakeInitializationPacket) { + this._handshakeInitializationPacket = packet; + } + + sequence._timer.active(); + + if (!sequence[packetName]) { + var err = new Error('Received packet in the wrong sequence.'); + err.code = 'PROTOCOL_INCORRECT_PACKET_SEQUENCE'; + err.fatal = true; + + this._delegateError(err); + return; + } + + sequence[packetName](packet); +}; + +Protocol.prototype._parsePacketDebug = function _parsePacketDebug(packet) { + try { + packet.parse(this._parser); + } finally { + this._debugPacket(true, packet); + } +}; + +Protocol.prototype._emitPacket = function(packet) { + var packetWriter = new PacketWriter(); + packet.write(packetWriter); + this.emit('data', packetWriter.toBuffer(this._parser)); + + if (this._config.debug) { + this._debugPacket(false, packet); + } +}; + +Protocol.prototype._determinePacket = function(sequence) { + var firstByte = this._parser.peak(); + + if (sequence.determinePacket) { + var Packet = sequence.determinePacket(firstByte, this._parser); + if (Packet) { + return Packet; + } + } + + switch (firstByte) { + case 0x00: + if (!this._handshaked) { + this._handshaked = true; + this.emit('handshake', this._handshakeInitializationPacket); + } + return Packets.OkPacket; + case 0xfe: return Packets.EofPacket; + case 0xff: return Packets.ErrorPacket; + } + + throw new Error('Could not determine packet, firstByte = ' + firstByte); +}; + +Protocol.prototype._dequeue = function(sequence) { + sequence._timer.stop(); + + // No point in advancing the queue, we are dead + if (this._fatalError) { + return; + } + + this._queue.shift(); + + var sequence = this._queue[0]; + if (!sequence) { + this.emit('drain'); + return; + } + + this._parser.resetPacketNumber(); + + this._startSequence(sequence); +}; + +Protocol.prototype._startSequence = function(sequence) { + if (sequence._timeout > 0 && isFinite(sequence._timeout)) { + sequence._timer.start(sequence._timeout); + } + + if (sequence.constructor === Sequences.ChangeUser) { + sequence.start(this._handshakeInitializationPacket); + } else { + sequence.start(); + } +}; + +Protocol.prototype.handleNetworkError = function(err) { + err.fatal = true; + + var sequence = this._queue[0]; + if (sequence) { + sequence.end(err); + } else { + this._delegateError(err); + } +}; + +Protocol.prototype.handleParserError = function handleParserError(err) { + var sequence = this._queue[0]; + if (sequence) { + sequence.end(err); + } else { + this._delegateError(err); + } +}; + +Protocol.prototype._delegateError = function(err, sequence) { + // Stop delegating errors after the first fatal error + if (this._fatalError) { + return; + } + + if (err.fatal) { + this._fatalError = err; + } + + if (this._shouldErrorBubbleUp(err, sequence)) { + // Can't use regular 'error' event here as that always destroys the pipe + // between socket and protocol which is not what we want (unless the + // exception was fatal). + this.emit('unhandledError', err); + } else if (err.fatal) { + // Send fatal error to all sequences in the queue + var queue = this._queue; + process.nextTick(function () { + queue.forEach(function (sequence) { + sequence.end(err); + }); + queue.length = 0; + }); + } + + // Make sure the stream we are piping to is getting closed + if (err.fatal) { + this.emit('end', err); + } +}; + +Protocol.prototype._shouldErrorBubbleUp = function(err, sequence) { + if (sequence) { + if (sequence.hasErrorHandler()) { + return false; + } else if (!err.fatal) { + return true; + } + } + + return (err.fatal && !this._hasPendingErrorHandlers()); +}; + +Protocol.prototype._hasPendingErrorHandlers = function() { + return this._queue.some(function(sequence) { + return sequence.hasErrorHandler(); + }); +}; + +Protocol.prototype.destroy = function() { + this._destroyed = true; + this._parser.pause(); + + if (this._connection.state !== 'disconnected') { + if (!this._ended) { + this.end(); + } + } +}; + +Protocol.prototype._debugPacket = function(incoming, packet) { + var connection = this._connection; + var headline = incoming + ? '<-- ' + : '--> '; + + if (connection && connection.threadId !== null) { + headline += '(' + connection.threadId + ') '; + } + + headline += packet.constructor.name; + + // check for debug packet restriction + if (Array.isArray(this._config.debug) && this._config.debug.indexOf(packet.constructor.name) === -1) { + return; + } + + console.log(headline); + console.log(packet); + console.log(''); +}; diff --git a/node_modules/mysql/lib/protocol/ResultSet.js b/node_modules/mysql/lib/protocol/ResultSet.js new file mode 100644 index 0000000000000000000000000000000000000000..f58d74fb21a00bba241ddd11a6e8c6fac80299a5 --- /dev/null +++ b/node_modules/mysql/lib/protocol/ResultSet.js @@ -0,0 +1,7 @@ +module.exports = ResultSet; +function ResultSet(resultSetHeaderPacket) { + this.resultSetHeaderPacket = resultSetHeaderPacket; + this.fieldPackets = []; + this.eofPackets = []; + this.rows = []; +} diff --git a/node_modules/mysql/lib/protocol/SqlString.js b/node_modules/mysql/lib/protocol/SqlString.js new file mode 100644 index 0000000000000000000000000000000000000000..30c63d82e310c27d2814363cfb56c37e6c6e8b72 --- /dev/null +++ b/node_modules/mysql/lib/protocol/SqlString.js @@ -0,0 +1 @@ +module.exports = require('sqlstring'); diff --git a/node_modules/mysql/lib/protocol/Timer.js b/node_modules/mysql/lib/protocol/Timer.js new file mode 100644 index 0000000000000000000000000000000000000000..45ed0292fa6b66c10fd4919b5413c0181bd70e27 --- /dev/null +++ b/node_modules/mysql/lib/protocol/Timer.js @@ -0,0 +1,33 @@ +var Timers = require('timers'); + +module.exports = Timer; +function Timer(object) { + this._object = object; + this._timeout = null; +} + +Timer.prototype.active = function active() { + if (this._timeout) { + if (this._timeout.refresh) { + this._timeout.refresh(); + } else { + Timers.active(this._timeout); + } + } +}; + +Timer.prototype.start = function start(msecs) { + this.stop(); + this._timeout = Timers.setTimeout(this._onTimeout.bind(this), msecs); +}; + +Timer.prototype.stop = function stop() { + if (this._timeout) { + Timers.clearTimeout(this._timeout); + this._timeout = null; + } +}; + +Timer.prototype._onTimeout = function _onTimeout() { + return this._object._onTimeout(); +}; diff --git a/node_modules/mysql/lib/protocol/constants/charsets.js b/node_modules/mysql/lib/protocol/constants/charsets.js new file mode 100644 index 0000000000000000000000000000000000000000..98b88eac11879a240fada41e913d2a7f73de61c4 --- /dev/null +++ b/node_modules/mysql/lib/protocol/constants/charsets.js @@ -0,0 +1,262 @@ +exports.BIG5_CHINESE_CI = 1; +exports.LATIN2_CZECH_CS = 2; +exports.DEC8_SWEDISH_CI = 3; +exports.CP850_GENERAL_CI = 4; +exports.LATIN1_GERMAN1_CI = 5; +exports.HP8_ENGLISH_CI = 6; +exports.KOI8R_GENERAL_CI = 7; +exports.LATIN1_SWEDISH_CI = 8; +exports.LATIN2_GENERAL_CI = 9; +exports.SWE7_SWEDISH_CI = 10; +exports.ASCII_GENERAL_CI = 11; +exports.UJIS_JAPANESE_CI = 12; +exports.SJIS_JAPANESE_CI = 13; +exports.CP1251_BULGARIAN_CI = 14; +exports.LATIN1_DANISH_CI = 15; +exports.HEBREW_GENERAL_CI = 16; +exports.TIS620_THAI_CI = 18; +exports.EUCKR_KOREAN_CI = 19; +exports.LATIN7_ESTONIAN_CS = 20; +exports.LATIN2_HUNGARIAN_CI = 21; +exports.KOI8U_GENERAL_CI = 22; +exports.CP1251_UKRAINIAN_CI = 23; +exports.GB2312_CHINESE_CI = 24; +exports.GREEK_GENERAL_CI = 25; +exports.CP1250_GENERAL_CI = 26; +exports.LATIN2_CROATIAN_CI = 27; +exports.GBK_CHINESE_CI = 28; +exports.CP1257_LITHUANIAN_CI = 29; +exports.LATIN5_TURKISH_CI = 30; +exports.LATIN1_GERMAN2_CI = 31; +exports.ARMSCII8_GENERAL_CI = 32; +exports.UTF8_GENERAL_CI = 33; +exports.CP1250_CZECH_CS = 34; +exports.UCS2_GENERAL_CI = 35; +exports.CP866_GENERAL_CI = 36; +exports.KEYBCS2_GENERAL_CI = 37; +exports.MACCE_GENERAL_CI = 38; +exports.MACROMAN_GENERAL_CI = 39; +exports.CP852_GENERAL_CI = 40; +exports.LATIN7_GENERAL_CI = 41; +exports.LATIN7_GENERAL_CS = 42; +exports.MACCE_BIN = 43; +exports.CP1250_CROATIAN_CI = 44; +exports.UTF8MB4_GENERAL_CI = 45; +exports.UTF8MB4_BIN = 46; +exports.LATIN1_BIN = 47; +exports.LATIN1_GENERAL_CI = 48; +exports.LATIN1_GENERAL_CS = 49; +exports.CP1251_BIN = 50; +exports.CP1251_GENERAL_CI = 51; +exports.CP1251_GENERAL_CS = 52; +exports.MACROMAN_BIN = 53; +exports.UTF16_GENERAL_CI = 54; +exports.UTF16_BIN = 55; +exports.UTF16LE_GENERAL_CI = 56; +exports.CP1256_GENERAL_CI = 57; +exports.CP1257_BIN = 58; +exports.CP1257_GENERAL_CI = 59; +exports.UTF32_GENERAL_CI = 60; +exports.UTF32_BIN = 61; +exports.UTF16LE_BIN = 62; +exports.BINARY = 63; +exports.ARMSCII8_BIN = 64; +exports.ASCII_BIN = 65; +exports.CP1250_BIN = 66; +exports.CP1256_BIN = 67; +exports.CP866_BIN = 68; +exports.DEC8_BIN = 69; +exports.GREEK_BIN = 70; +exports.HEBREW_BIN = 71; +exports.HP8_BIN = 72; +exports.KEYBCS2_BIN = 73; +exports.KOI8R_BIN = 74; +exports.KOI8U_BIN = 75; +exports.LATIN2_BIN = 77; +exports.LATIN5_BIN = 78; +exports.LATIN7_BIN = 79; +exports.CP850_BIN = 80; +exports.CP852_BIN = 81; +exports.SWE7_BIN = 82; +exports.UTF8_BIN = 83; +exports.BIG5_BIN = 84; +exports.EUCKR_BIN = 85; +exports.GB2312_BIN = 86; +exports.GBK_BIN = 87; +exports.SJIS_BIN = 88; +exports.TIS620_BIN = 89; +exports.UCS2_BIN = 90; +exports.UJIS_BIN = 91; +exports.GEOSTD8_GENERAL_CI = 92; +exports.GEOSTD8_BIN = 93; +exports.LATIN1_SPANISH_CI = 94; +exports.CP932_JAPANESE_CI = 95; +exports.CP932_BIN = 96; +exports.EUCJPMS_JAPANESE_CI = 97; +exports.EUCJPMS_BIN = 98; +exports.CP1250_POLISH_CI = 99; +exports.UTF16_UNICODE_CI = 101; +exports.UTF16_ICELANDIC_CI = 102; +exports.UTF16_LATVIAN_CI = 103; +exports.UTF16_ROMANIAN_CI = 104; +exports.UTF16_SLOVENIAN_CI = 105; +exports.UTF16_POLISH_CI = 106; +exports.UTF16_ESTONIAN_CI = 107; +exports.UTF16_SPANISH_CI = 108; +exports.UTF16_SWEDISH_CI = 109; +exports.UTF16_TURKISH_CI = 110; +exports.UTF16_CZECH_CI = 111; +exports.UTF16_DANISH_CI = 112; +exports.UTF16_LITHUANIAN_CI = 113; +exports.UTF16_SLOVAK_CI = 114; +exports.UTF16_SPANISH2_CI = 115; +exports.UTF16_ROMAN_CI = 116; +exports.UTF16_PERSIAN_CI = 117; +exports.UTF16_ESPERANTO_CI = 118; +exports.UTF16_HUNGARIAN_CI = 119; +exports.UTF16_SINHALA_CI = 120; +exports.UTF16_GERMAN2_CI = 121; +exports.UTF16_CROATIAN_MYSQL561_CI = 122; +exports.UTF16_UNICODE_520_CI = 123; +exports.UTF16_VIETNAMESE_CI = 124; +exports.UCS2_UNICODE_CI = 128; +exports.UCS2_ICELANDIC_CI = 129; +exports.UCS2_LATVIAN_CI = 130; +exports.UCS2_ROMANIAN_CI = 131; +exports.UCS2_SLOVENIAN_CI = 132; +exports.UCS2_POLISH_CI = 133; +exports.UCS2_ESTONIAN_CI = 134; +exports.UCS2_SPANISH_CI = 135; +exports.UCS2_SWEDISH_CI = 136; +exports.UCS2_TURKISH_CI = 137; +exports.UCS2_CZECH_CI = 138; +exports.UCS2_DANISH_CI = 139; +exports.UCS2_LITHUANIAN_CI = 140; +exports.UCS2_SLOVAK_CI = 141; +exports.UCS2_SPANISH2_CI = 142; +exports.UCS2_ROMAN_CI = 143; +exports.UCS2_PERSIAN_CI = 144; +exports.UCS2_ESPERANTO_CI = 145; +exports.UCS2_HUNGARIAN_CI = 146; +exports.UCS2_SINHALA_CI = 147; +exports.UCS2_GERMAN2_CI = 148; +exports.UCS2_CROATIAN_MYSQL561_CI = 149; +exports.UCS2_UNICODE_520_CI = 150; +exports.UCS2_VIETNAMESE_CI = 151; +exports.UCS2_GENERAL_MYSQL500_CI = 159; +exports.UTF32_UNICODE_CI = 160; +exports.UTF32_ICELANDIC_CI = 161; +exports.UTF32_LATVIAN_CI = 162; +exports.UTF32_ROMANIAN_CI = 163; +exports.UTF32_SLOVENIAN_CI = 164; +exports.UTF32_POLISH_CI = 165; +exports.UTF32_ESTONIAN_CI = 166; +exports.UTF32_SPANISH_CI = 167; +exports.UTF32_SWEDISH_CI = 168; +exports.UTF32_TURKISH_CI = 169; +exports.UTF32_CZECH_CI = 170; +exports.UTF32_DANISH_CI = 171; +exports.UTF32_LITHUANIAN_CI = 172; +exports.UTF32_SLOVAK_CI = 173; +exports.UTF32_SPANISH2_CI = 174; +exports.UTF32_ROMAN_CI = 175; +exports.UTF32_PERSIAN_CI = 176; +exports.UTF32_ESPERANTO_CI = 177; +exports.UTF32_HUNGARIAN_CI = 178; +exports.UTF32_SINHALA_CI = 179; +exports.UTF32_GERMAN2_CI = 180; +exports.UTF32_CROATIAN_MYSQL561_CI = 181; +exports.UTF32_UNICODE_520_CI = 182; +exports.UTF32_VIETNAMESE_CI = 183; +exports.UTF8_UNICODE_CI = 192; +exports.UTF8_ICELANDIC_CI = 193; +exports.UTF8_LATVIAN_CI = 194; +exports.UTF8_ROMANIAN_CI = 195; +exports.UTF8_SLOVENIAN_CI = 196; +exports.UTF8_POLISH_CI = 197; +exports.UTF8_ESTONIAN_CI = 198; +exports.UTF8_SPANISH_CI = 199; +exports.UTF8_SWEDISH_CI = 200; +exports.UTF8_TURKISH_CI = 201; +exports.UTF8_CZECH_CI = 202; +exports.UTF8_DANISH_CI = 203; +exports.UTF8_LITHUANIAN_CI = 204; +exports.UTF8_SLOVAK_CI = 205; +exports.UTF8_SPANISH2_CI = 206; +exports.UTF8_ROMAN_CI = 207; +exports.UTF8_PERSIAN_CI = 208; +exports.UTF8_ESPERANTO_CI = 209; +exports.UTF8_HUNGARIAN_CI = 210; +exports.UTF8_SINHALA_CI = 211; +exports.UTF8_GERMAN2_CI = 212; +exports.UTF8_CROATIAN_MYSQL561_CI = 213; +exports.UTF8_UNICODE_520_CI = 214; +exports.UTF8_VIETNAMESE_CI = 215; +exports.UTF8_GENERAL_MYSQL500_CI = 223; +exports.UTF8MB4_UNICODE_CI = 224; +exports.UTF8MB4_ICELANDIC_CI = 225; +exports.UTF8MB4_LATVIAN_CI = 226; +exports.UTF8MB4_ROMANIAN_CI = 227; +exports.UTF8MB4_SLOVENIAN_CI = 228; +exports.UTF8MB4_POLISH_CI = 229; +exports.UTF8MB4_ESTONIAN_CI = 230; +exports.UTF8MB4_SPANISH_CI = 231; +exports.UTF8MB4_SWEDISH_CI = 232; +exports.UTF8MB4_TURKISH_CI = 233; +exports.UTF8MB4_CZECH_CI = 234; +exports.UTF8MB4_DANISH_CI = 235; +exports.UTF8MB4_LITHUANIAN_CI = 236; +exports.UTF8MB4_SLOVAK_CI = 237; +exports.UTF8MB4_SPANISH2_CI = 238; +exports.UTF8MB4_ROMAN_CI = 239; +exports.UTF8MB4_PERSIAN_CI = 240; +exports.UTF8MB4_ESPERANTO_CI = 241; +exports.UTF8MB4_HUNGARIAN_CI = 242; +exports.UTF8MB4_SINHALA_CI = 243; +exports.UTF8MB4_GERMAN2_CI = 244; +exports.UTF8MB4_CROATIAN_MYSQL561_CI = 245; +exports.UTF8MB4_UNICODE_520_CI = 246; +exports.UTF8MB4_VIETNAMESE_CI = 247; +exports.UTF8_GENERAL50_CI = 253; + +// short aliases +exports.ARMSCII8 = exports.ARMSCII8_GENERAL_CI; +exports.ASCII = exports.ASCII_GENERAL_CI; +exports.BIG5 = exports.BIG5_CHINESE_CI; +exports.BINARY = exports.BINARY; +exports.CP1250 = exports.CP1250_GENERAL_CI; +exports.CP1251 = exports.CP1251_GENERAL_CI; +exports.CP1256 = exports.CP1256_GENERAL_CI; +exports.CP1257 = exports.CP1257_GENERAL_CI; +exports.CP866 = exports.CP866_GENERAL_CI; +exports.CP850 = exports.CP850_GENERAL_CI; +exports.CP852 = exports.CP852_GENERAL_CI; +exports.CP932 = exports.CP932_JAPANESE_CI; +exports.DEC8 = exports.DEC8_SWEDISH_CI; +exports.EUCJPMS = exports.EUCJPMS_JAPANESE_CI; +exports.EUCKR = exports.EUCKR_KOREAN_CI; +exports.GB2312 = exports.GB2312_CHINESE_CI; +exports.GBK = exports.GBK_CHINESE_CI; +exports.GEOSTD8 = exports.GEOSTD8_GENERAL_CI; +exports.GREEK = exports.GREEK_GENERAL_CI; +exports.HEBREW = exports.HEBREW_GENERAL_CI; +exports.HP8 = exports.HP8_ENGLISH_CI; +exports.KEYBCS2 = exports.KEYBCS2_GENERAL_CI; +exports.KOI8R = exports.KOI8R_GENERAL_CI; +exports.KOI8U = exports.KOI8U_GENERAL_CI; +exports.LATIN1 = exports.LATIN1_SWEDISH_CI; +exports.LATIN2 = exports.LATIN2_GENERAL_CI; +exports.LATIN5 = exports.LATIN5_TURKISH_CI; +exports.LATIN7 = exports.LATIN7_GENERAL_CI; +exports.MACCE = exports.MACCE_GENERAL_CI; +exports.MACROMAN = exports.MACROMAN_GENERAL_CI; +exports.SJIS = exports.SJIS_JAPANESE_CI; +exports.SWE7 = exports.SWE7_SWEDISH_CI; +exports.TIS620 = exports.TIS620_THAI_CI; +exports.UCS2 = exports.UCS2_GENERAL_CI; +exports.UJIS = exports.UJIS_JAPANESE_CI; +exports.UTF16 = exports.UTF16_GENERAL_CI; +exports.UTF16LE = exports.UTF16LE_GENERAL_CI; +exports.UTF8 = exports.UTF8_GENERAL_CI; +exports.UTF8MB4 = exports.UTF8MB4_GENERAL_CI; +exports.UTF32 = exports.UTF32_GENERAL_CI; diff --git a/node_modules/mysql/lib/protocol/constants/client.js b/node_modules/mysql/lib/protocol/constants/client.js new file mode 100644 index 0000000000000000000000000000000000000000..59aadc609ee832dab6e71beeaae6145b16a4bc1a --- /dev/null +++ b/node_modules/mysql/lib/protocol/constants/client.js @@ -0,0 +1,26 @@ +// Manually extracted from mysql-5.5.23/include/mysql_com.h +exports.CLIENT_LONG_PASSWORD = 1; /* new more secure passwords */ +exports.CLIENT_FOUND_ROWS = 2; /* Found instead of affected rows */ +exports.CLIENT_LONG_FLAG = 4; /* Get all column flags */ +exports.CLIENT_CONNECT_WITH_DB = 8; /* One can specify db on connect */ +exports.CLIENT_NO_SCHEMA = 16; /* Don't allow database.table.column */ +exports.CLIENT_COMPRESS = 32; /* Can use compression protocol */ +exports.CLIENT_ODBC = 64; /* Odbc client */ +exports.CLIENT_LOCAL_FILES = 128; /* Can use LOAD DATA LOCAL */ +exports.CLIENT_IGNORE_SPACE = 256; /* Ignore spaces before '(' */ +exports.CLIENT_PROTOCOL_41 = 512; /* New 4.1 protocol */ +exports.CLIENT_INTERACTIVE = 1024; /* This is an interactive client */ +exports.CLIENT_SSL = 2048; /* Switch to SSL after handshake */ +exports.CLIENT_IGNORE_SIGPIPE = 4096; /* IGNORE sigpipes */ +exports.CLIENT_TRANSACTIONS = 8192; /* Client knows about transactions */ +exports.CLIENT_RESERVED = 16384; /* Old flag for 4.1 protocol */ +exports.CLIENT_SECURE_CONNECTION = 32768; /* New 4.1 authentication */ + +exports.CLIENT_MULTI_STATEMENTS = 65536; /* Enable/disable multi-stmt support */ +exports.CLIENT_MULTI_RESULTS = 131072; /* Enable/disable multi-results */ +exports.CLIENT_PS_MULTI_RESULTS = 262144; /* Multi-results in PS-protocol */ + +exports.CLIENT_PLUGIN_AUTH = 524288; /* Client supports plugin authentication */ + +exports.CLIENT_SSL_VERIFY_SERVER_CERT = 1073741824; +exports.CLIENT_REMEMBER_OPTIONS = 2147483648; diff --git a/node_modules/mysql/lib/protocol/constants/errors.js b/node_modules/mysql/lib/protocol/constants/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..9bc0f534d323a1309d15b6899915a8ffdf071ff8 --- /dev/null +++ b/node_modules/mysql/lib/protocol/constants/errors.js @@ -0,0 +1,2416 @@ +/** + * MySQL error constants + * + * Extracted from version 5.7.21 + * + * !! Generated by generate-error-constants.js, do not modify by hand !! + */ + +exports.EE_CANTCREATEFILE = 1; +exports.EE_READ = 2; +exports.EE_WRITE = 3; +exports.EE_BADCLOSE = 4; +exports.EE_OUTOFMEMORY = 5; +exports.EE_DELETE = 6; +exports.EE_LINK = 7; +exports.EE_EOFERR = 9; +exports.EE_CANTLOCK = 10; +exports.EE_CANTUNLOCK = 11; +exports.EE_DIR = 12; +exports.EE_STAT = 13; +exports.EE_CANT_CHSIZE = 14; +exports.EE_CANT_OPEN_STREAM = 15; +exports.EE_GETWD = 16; +exports.EE_SETWD = 17; +exports.EE_LINK_WARNING = 18; +exports.EE_OPEN_WARNING = 19; +exports.EE_DISK_FULL = 20; +exports.EE_CANT_MKDIR = 21; +exports.EE_UNKNOWN_CHARSET = 22; +exports.EE_OUT_OF_FILERESOURCES = 23; +exports.EE_CANT_READLINK = 24; +exports.EE_CANT_SYMLINK = 25; +exports.EE_REALPATH = 26; +exports.EE_SYNC = 27; +exports.EE_UNKNOWN_COLLATION = 28; +exports.EE_FILENOTFOUND = 29; +exports.EE_FILE_NOT_CLOSED = 30; +exports.EE_CHANGE_OWNERSHIP = 31; +exports.EE_CHANGE_PERMISSIONS = 32; +exports.EE_CANT_SEEK = 33; +exports.EE_CAPACITY_EXCEEDED = 34; +exports.HA_ERR_KEY_NOT_FOUND = 120; +exports.HA_ERR_FOUND_DUPP_KEY = 121; +exports.HA_ERR_INTERNAL_ERROR = 122; +exports.HA_ERR_RECORD_CHANGED = 123; +exports.HA_ERR_WRONG_INDEX = 124; +exports.HA_ERR_CRASHED = 126; +exports.HA_ERR_WRONG_IN_RECORD = 127; +exports.HA_ERR_OUT_OF_MEM = 128; +exports.HA_ERR_NOT_A_TABLE = 130; +exports.HA_ERR_WRONG_COMMAND = 131; +exports.HA_ERR_OLD_FILE = 132; +exports.HA_ERR_NO_ACTIVE_RECORD = 133; +exports.HA_ERR_RECORD_DELETED = 134; +exports.HA_ERR_RECORD_FILE_FULL = 135; +exports.HA_ERR_INDEX_FILE_FULL = 136; +exports.HA_ERR_END_OF_FILE = 137; +exports.HA_ERR_UNSUPPORTED = 138; +exports.HA_ERR_TOO_BIG_ROW = 139; +exports.HA_WRONG_CREATE_OPTION = 140; +exports.HA_ERR_FOUND_DUPP_UNIQUE = 141; +exports.HA_ERR_UNKNOWN_CHARSET = 142; +exports.HA_ERR_WRONG_MRG_TABLE_DEF = 143; +exports.HA_ERR_CRASHED_ON_REPAIR = 144; +exports.HA_ERR_CRASHED_ON_USAGE = 145; +exports.HA_ERR_LOCK_WAIT_TIMEOUT = 146; +exports.HA_ERR_LOCK_TABLE_FULL = 147; +exports.HA_ERR_READ_ONLY_TRANSACTION = 148; +exports.HA_ERR_LOCK_DEADLOCK = 149; +exports.HA_ERR_CANNOT_ADD_FOREIGN = 150; +exports.HA_ERR_NO_REFERENCED_ROW = 151; +exports.HA_ERR_ROW_IS_REFERENCED = 152; +exports.HA_ERR_NO_SAVEPOINT = 153; +exports.HA_ERR_NON_UNIQUE_BLOCK_SIZE = 154; +exports.HA_ERR_NO_SUCH_TABLE = 155; +exports.HA_ERR_TABLE_EXIST = 156; +exports.HA_ERR_NO_CONNECTION = 157; +exports.HA_ERR_NULL_IN_SPATIAL = 158; +exports.HA_ERR_TABLE_DEF_CHANGED = 159; +exports.HA_ERR_NO_PARTITION_FOUND = 160; +exports.HA_ERR_RBR_LOGGING_FAILED = 161; +exports.HA_ERR_DROP_INDEX_FK = 162; +exports.HA_ERR_FOREIGN_DUPLICATE_KEY = 163; +exports.HA_ERR_TABLE_NEEDS_UPGRADE = 164; +exports.HA_ERR_TABLE_READONLY = 165; +exports.HA_ERR_AUTOINC_READ_FAILED = 166; +exports.HA_ERR_AUTOINC_ERANGE = 167; +exports.HA_ERR_GENERIC = 168; +exports.HA_ERR_RECORD_IS_THE_SAME = 169; +exports.HA_ERR_LOGGING_IMPOSSIBLE = 170; +exports.HA_ERR_CORRUPT_EVENT = 171; +exports.HA_ERR_NEW_FILE = 172; +exports.HA_ERR_ROWS_EVENT_APPLY = 173; +exports.HA_ERR_INITIALIZATION = 174; +exports.HA_ERR_FILE_TOO_SHORT = 175; +exports.HA_ERR_WRONG_CRC = 176; +exports.HA_ERR_TOO_MANY_CONCURRENT_TRXS = 177; +exports.HA_ERR_NOT_IN_LOCK_PARTITIONS = 178; +exports.HA_ERR_INDEX_COL_TOO_LONG = 179; +exports.HA_ERR_INDEX_CORRUPT = 180; +exports.HA_ERR_UNDO_REC_TOO_BIG = 181; +exports.HA_FTS_INVALID_DOCID = 182; +exports.HA_ERR_TABLE_IN_FK_CHECK = 183; +exports.HA_ERR_TABLESPACE_EXISTS = 184; +exports.HA_ERR_TOO_MANY_FIELDS = 185; +exports.HA_ERR_ROW_IN_WRONG_PARTITION = 186; +exports.HA_ERR_INNODB_READ_ONLY = 187; +exports.HA_ERR_FTS_EXCEED_RESULT_CACHE_LIMIT = 188; +exports.HA_ERR_TEMP_FILE_WRITE_FAILURE = 189; +exports.HA_ERR_INNODB_FORCED_RECOVERY = 190; +exports.HA_ERR_FTS_TOO_MANY_WORDS_IN_PHRASE = 191; +exports.HA_ERR_FK_DEPTH_EXCEEDED = 192; +exports.HA_MISSING_CREATE_OPTION = 193; +exports.HA_ERR_SE_OUT_OF_MEMORY = 194; +exports.HA_ERR_TABLE_CORRUPT = 195; +exports.HA_ERR_QUERY_INTERRUPTED = 196; +exports.HA_ERR_TABLESPACE_MISSING = 197; +exports.HA_ERR_TABLESPACE_IS_NOT_EMPTY = 198; +exports.HA_ERR_WRONG_FILE_NAME = 199; +exports.HA_ERR_NOT_ALLOWED_COMMAND = 200; +exports.HA_ERR_COMPUTE_FAILED = 201; +exports.ER_HASHCHK = 1000; +exports.ER_NISAMCHK = 1001; +exports.ER_NO = 1002; +exports.ER_YES = 1003; +exports.ER_CANT_CREATE_FILE = 1004; +exports.ER_CANT_CREATE_TABLE = 1005; +exports.ER_CANT_CREATE_DB = 1006; +exports.ER_DB_CREATE_EXISTS = 1007; +exports.ER_DB_DROP_EXISTS = 1008; +exports.ER_DB_DROP_DELETE = 1009; +exports.ER_DB_DROP_RMDIR = 1010; +exports.ER_CANT_DELETE_FILE = 1011; +exports.ER_CANT_FIND_SYSTEM_REC = 1012; +exports.ER_CANT_GET_STAT = 1013; +exports.ER_CANT_GET_WD = 1014; +exports.ER_CANT_LOCK = 1015; +exports.ER_CANT_OPEN_FILE = 1016; +exports.ER_FILE_NOT_FOUND = 1017; +exports.ER_CANT_READ_DIR = 1018; +exports.ER_CANT_SET_WD = 1019; +exports.ER_CHECKREAD = 1020; +exports.ER_DISK_FULL = 1021; +exports.ER_DUP_KEY = 1022; +exports.ER_ERROR_ON_CLOSE = 1023; +exports.ER_ERROR_ON_READ = 1024; +exports.ER_ERROR_ON_RENAME = 1025; +exports.ER_ERROR_ON_WRITE = 1026; +exports.ER_FILE_USED = 1027; +exports.ER_FILSORT_ABORT = 1028; +exports.ER_FORM_NOT_FOUND = 1029; +exports.ER_GET_ERRNO = 1030; +exports.ER_ILLEGAL_HA = 1031; +exports.ER_KEY_NOT_FOUND = 1032; +exports.ER_NOT_FORM_FILE = 1033; +exports.ER_NOT_KEYFILE = 1034; +exports.ER_OLD_KEYFILE = 1035; +exports.ER_OPEN_AS_READONLY = 1036; +exports.ER_OUTOFMEMORY = 1037; +exports.ER_OUT_OF_SORTMEMORY = 1038; +exports.ER_UNEXPECTED_EOF = 1039; +exports.ER_CON_COUNT_ERROR = 1040; +exports.ER_OUT_OF_RESOURCES = 1041; +exports.ER_BAD_HOST_ERROR = 1042; +exports.ER_HANDSHAKE_ERROR = 1043; +exports.ER_DBACCESS_DENIED_ERROR = 1044; +exports.ER_ACCESS_DENIED_ERROR = 1045; +exports.ER_NO_DB_ERROR = 1046; +exports.ER_UNKNOWN_COM_ERROR = 1047; +exports.ER_BAD_NULL_ERROR = 1048; +exports.ER_BAD_DB_ERROR = 1049; +exports.ER_TABLE_EXISTS_ERROR = 1050; +exports.ER_BAD_TABLE_ERROR = 1051; +exports.ER_NON_UNIQ_ERROR = 1052; +exports.ER_SERVER_SHUTDOWN = 1053; +exports.ER_BAD_FIELD_ERROR = 1054; +exports.ER_WRONG_FIELD_WITH_GROUP = 1055; +exports.ER_WRONG_GROUP_FIELD = 1056; +exports.ER_WRONG_SUM_SELECT = 1057; +exports.ER_WRONG_VALUE_COUNT = 1058; +exports.ER_TOO_LONG_IDENT = 1059; +exports.ER_DUP_FIELDNAME = 1060; +exports.ER_DUP_KEYNAME = 1061; +exports.ER_DUP_ENTRY = 1062; +exports.ER_WRONG_FIELD_SPEC = 1063; +exports.ER_PARSE_ERROR = 1064; +exports.ER_EMPTY_QUERY = 1065; +exports.ER_NONUNIQ_TABLE = 1066; +exports.ER_INVALID_DEFAULT = 1067; +exports.ER_MULTIPLE_PRI_KEY = 1068; +exports.ER_TOO_MANY_KEYS = 1069; +exports.ER_TOO_MANY_KEY_PARTS = 1070; +exports.ER_TOO_LONG_KEY = 1071; +exports.ER_KEY_COLUMN_DOES_NOT_EXITS = 1072; +exports.ER_BLOB_USED_AS_KEY = 1073; +exports.ER_TOO_BIG_FIELDLENGTH = 1074; +exports.ER_WRONG_AUTO_KEY = 1075; +exports.ER_READY = 1076; +exports.ER_NORMAL_SHUTDOWN = 1077; +exports.ER_GOT_SIGNAL = 1078; +exports.ER_SHUTDOWN_COMPLETE = 1079; +exports.ER_FORCING_CLOSE = 1080; +exports.ER_IPSOCK_ERROR = 1081; +exports.ER_NO_SUCH_INDEX = 1082; +exports.ER_WRONG_FIELD_TERMINATORS = 1083; +exports.ER_BLOBS_AND_NO_TERMINATED = 1084; +exports.ER_TEXTFILE_NOT_READABLE = 1085; +exports.ER_FILE_EXISTS_ERROR = 1086; +exports.ER_LOAD_INFO = 1087; +exports.ER_ALTER_INFO = 1088; +exports.ER_WRONG_SUB_KEY = 1089; +exports.ER_CANT_REMOVE_ALL_FIELDS = 1090; +exports.ER_CANT_DROP_FIELD_OR_KEY = 1091; +exports.ER_INSERT_INFO = 1092; +exports.ER_UPDATE_TABLE_USED = 1093; +exports.ER_NO_SUCH_THREAD = 1094; +exports.ER_KILL_DENIED_ERROR = 1095; +exports.ER_NO_TABLES_USED = 1096; +exports.ER_TOO_BIG_SET = 1097; +exports.ER_NO_UNIQUE_LOGFILE = 1098; +exports.ER_TABLE_NOT_LOCKED_FOR_WRITE = 1099; +exports.ER_TABLE_NOT_LOCKED = 1100; +exports.ER_BLOB_CANT_HAVE_DEFAULT = 1101; +exports.ER_WRONG_DB_NAME = 1102; +exports.ER_WRONG_TABLE_NAME = 1103; +exports.ER_TOO_BIG_SELECT = 1104; +exports.ER_UNKNOWN_ERROR = 1105; +exports.ER_UNKNOWN_PROCEDURE = 1106; +exports.ER_WRONG_PARAMCOUNT_TO_PROCEDURE = 1107; +exports.ER_WRONG_PARAMETERS_TO_PROCEDURE = 1108; +exports.ER_UNKNOWN_TABLE = 1109; +exports.ER_FIELD_SPECIFIED_TWICE = 1110; +exports.ER_INVALID_GROUP_FUNC_USE = 1111; +exports.ER_UNSUPPORTED_EXTENSION = 1112; +exports.ER_TABLE_MUST_HAVE_COLUMNS = 1113; +exports.ER_RECORD_FILE_FULL = 1114; +exports.ER_UNKNOWN_CHARACTER_SET = 1115; +exports.ER_TOO_MANY_TABLES = 1116; +exports.ER_TOO_MANY_FIELDS = 1117; +exports.ER_TOO_BIG_ROWSIZE = 1118; +exports.ER_STACK_OVERRUN = 1119; +exports.ER_WRONG_OUTER_JOIN = 1120; +exports.ER_NULL_COLUMN_IN_INDEX = 1121; +exports.ER_CANT_FIND_UDF = 1122; +exports.ER_CANT_INITIALIZE_UDF = 1123; +exports.ER_UDF_NO_PATHS = 1124; +exports.ER_UDF_EXISTS = 1125; +exports.ER_CANT_OPEN_LIBRARY = 1126; +exports.ER_CANT_FIND_DL_ENTRY = 1127; +exports.ER_FUNCTION_NOT_DEFINED = 1128; +exports.ER_HOST_IS_BLOCKED = 1129; +exports.ER_HOST_NOT_PRIVILEGED = 1130; +exports.ER_PASSWORD_ANONYMOUS_USER = 1131; +exports.ER_PASSWORD_NOT_ALLOWED = 1132; +exports.ER_PASSWORD_NO_MATCH = 1133; +exports.ER_UPDATE_INFO = 1134; +exports.ER_CANT_CREATE_THREAD = 1135; +exports.ER_WRONG_VALUE_COUNT_ON_ROW = 1136; +exports.ER_CANT_REOPEN_TABLE = 1137; +exports.ER_INVALID_USE_OF_NULL = 1138; +exports.ER_REGEXP_ERROR = 1139; +exports.ER_MIX_OF_GROUP_FUNC_AND_FIELDS = 1140; +exports.ER_NONEXISTING_GRANT = 1141; +exports.ER_TABLEACCESS_DENIED_ERROR = 1142; +exports.ER_COLUMNACCESS_DENIED_ERROR = 1143; +exports.ER_ILLEGAL_GRANT_FOR_TABLE = 1144; +exports.ER_GRANT_WRONG_HOST_OR_USER = 1145; +exports.ER_NO_SUCH_TABLE = 1146; +exports.ER_NONEXISTING_TABLE_GRANT = 1147; +exports.ER_NOT_ALLOWED_COMMAND = 1148; +exports.ER_SYNTAX_ERROR = 1149; +exports.ER_DELAYED_CANT_CHANGE_LOCK = 1150; +exports.ER_TOO_MANY_DELAYED_THREADS = 1151; +exports.ER_ABORTING_CONNECTION = 1152; +exports.ER_NET_PACKET_TOO_LARGE = 1153; +exports.ER_NET_READ_ERROR_FROM_PIPE = 1154; +exports.ER_NET_FCNTL_ERROR = 1155; +exports.ER_NET_PACKETS_OUT_OF_ORDER = 1156; +exports.ER_NET_UNCOMPRESS_ERROR = 1157; +exports.ER_NET_READ_ERROR = 1158; +exports.ER_NET_READ_INTERRUPTED = 1159; +exports.ER_NET_ERROR_ON_WRITE = 1160; +exports.ER_NET_WRITE_INTERRUPTED = 1161; +exports.ER_TOO_LONG_STRING = 1162; +exports.ER_TABLE_CANT_HANDLE_BLOB = 1163; +exports.ER_TABLE_CANT_HANDLE_AUTO_INCREMENT = 1164; +exports.ER_DELAYED_INSERT_TABLE_LOCKED = 1165; +exports.ER_WRONG_COLUMN_NAME = 1166; +exports.ER_WRONG_KEY_COLUMN = 1167; +exports.ER_WRONG_MRG_TABLE = 1168; +exports.ER_DUP_UNIQUE = 1169; +exports.ER_BLOB_KEY_WITHOUT_LENGTH = 1170; +exports.ER_PRIMARY_CANT_HAVE_NULL = 1171; +exports.ER_TOO_MANY_ROWS = 1172; +exports.ER_REQUIRES_PRIMARY_KEY = 1173; +exports.ER_NO_RAID_COMPILED = 1174; +exports.ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE = 1175; +exports.ER_KEY_DOES_NOT_EXITS = 1176; +exports.ER_CHECK_NO_SUCH_TABLE = 1177; +exports.ER_CHECK_NOT_IMPLEMENTED = 1178; +exports.ER_CANT_DO_THIS_DURING_AN_TRANSACTION = 1179; +exports.ER_ERROR_DURING_COMMIT = 1180; +exports.ER_ERROR_DURING_ROLLBACK = 1181; +exports.ER_ERROR_DURING_FLUSH_LOGS = 1182; +exports.ER_ERROR_DURING_CHECKPOINT = 1183; +exports.ER_NEW_ABORTING_CONNECTION = 1184; +exports.ER_DUMP_NOT_IMPLEMENTED = 1185; +exports.ER_FLUSH_MASTER_BINLOG_CLOSED = 1186; +exports.ER_INDEX_REBUILD = 1187; +exports.ER_MASTER = 1188; +exports.ER_MASTER_NET_READ = 1189; +exports.ER_MASTER_NET_WRITE = 1190; +exports.ER_FT_MATCHING_KEY_NOT_FOUND = 1191; +exports.ER_LOCK_OR_ACTIVE_TRANSACTION = 1192; +exports.ER_UNKNOWN_SYSTEM_VARIABLE = 1193; +exports.ER_CRASHED_ON_USAGE = 1194; +exports.ER_CRASHED_ON_REPAIR = 1195; +exports.ER_WARNING_NOT_COMPLETE_ROLLBACK = 1196; +exports.ER_TRANS_CACHE_FULL = 1197; +exports.ER_SLAVE_MUST_STOP = 1198; +exports.ER_SLAVE_NOT_RUNNING = 1199; +exports.ER_BAD_SLAVE = 1200; +exports.ER_MASTER_INFO = 1201; +exports.ER_SLAVE_THREAD = 1202; +exports.ER_TOO_MANY_USER_CONNECTIONS = 1203; +exports.ER_SET_CONSTANTS_ONLY = 1204; +exports.ER_LOCK_WAIT_TIMEOUT = 1205; +exports.ER_LOCK_TABLE_FULL = 1206; +exports.ER_READ_ONLY_TRANSACTION = 1207; +exports.ER_DROP_DB_WITH_READ_LOCK = 1208; +exports.ER_CREATE_DB_WITH_READ_LOCK = 1209; +exports.ER_WRONG_ARGUMENTS = 1210; +exports.ER_NO_PERMISSION_TO_CREATE_USER = 1211; +exports.ER_UNION_TABLES_IN_DIFFERENT_DIR = 1212; +exports.ER_LOCK_DEADLOCK = 1213; +exports.ER_TABLE_CANT_HANDLE_FT = 1214; +exports.ER_CANNOT_ADD_FOREIGN = 1215; +exports.ER_NO_REFERENCED_ROW = 1216; +exports.ER_ROW_IS_REFERENCED = 1217; +exports.ER_CONNECT_TO_MASTER = 1218; +exports.ER_QUERY_ON_MASTER = 1219; +exports.ER_ERROR_WHEN_EXECUTING_COMMAND = 1220; +exports.ER_WRONG_USAGE = 1221; +exports.ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT = 1222; +exports.ER_CANT_UPDATE_WITH_READLOCK = 1223; +exports.ER_MIXING_NOT_ALLOWED = 1224; +exports.ER_DUP_ARGUMENT = 1225; +exports.ER_USER_LIMIT_REACHED = 1226; +exports.ER_SPECIFIC_ACCESS_DENIED_ERROR = 1227; +exports.ER_LOCAL_VARIABLE = 1228; +exports.ER_GLOBAL_VARIABLE = 1229; +exports.ER_NO_DEFAULT = 1230; +exports.ER_WRONG_VALUE_FOR_VAR = 1231; +exports.ER_WRONG_TYPE_FOR_VAR = 1232; +exports.ER_VAR_CANT_BE_READ = 1233; +exports.ER_CANT_USE_OPTION_HERE = 1234; +exports.ER_NOT_SUPPORTED_YET = 1235; +exports.ER_MASTER_FATAL_ERROR_READING_BINLOG = 1236; +exports.ER_SLAVE_IGNORED_TABLE = 1237; +exports.ER_INCORRECT_GLOBAL_LOCAL_VAR = 1238; +exports.ER_WRONG_FK_DEF = 1239; +exports.ER_KEY_REF_DO_NOT_MATCH_TABLE_REF = 1240; +exports.ER_OPERAND_COLUMNS = 1241; +exports.ER_SUBQUERY_NO_1_ROW = 1242; +exports.ER_UNKNOWN_STMT_HANDLER = 1243; +exports.ER_CORRUPT_HELP_DB = 1244; +exports.ER_CYCLIC_REFERENCE = 1245; +exports.ER_AUTO_CONVERT = 1246; +exports.ER_ILLEGAL_REFERENCE = 1247; +exports.ER_DERIVED_MUST_HAVE_ALIAS = 1248; +exports.ER_SELECT_REDUCED = 1249; +exports.ER_TABLENAME_NOT_ALLOWED_HERE = 1250; +exports.ER_NOT_SUPPORTED_AUTH_MODE = 1251; +exports.ER_SPATIAL_CANT_HAVE_NULL = 1252; +exports.ER_COLLATION_CHARSET_MISMATCH = 1253; +exports.ER_SLAVE_WAS_RUNNING = 1254; +exports.ER_SLAVE_WAS_NOT_RUNNING = 1255; +exports.ER_TOO_BIG_FOR_UNCOMPRESS = 1256; +exports.ER_ZLIB_Z_MEM_ERROR = 1257; +exports.ER_ZLIB_Z_BUF_ERROR = 1258; +exports.ER_ZLIB_Z_DATA_ERROR = 1259; +exports.ER_CUT_VALUE_GROUP_CONCAT = 1260; +exports.ER_WARN_TOO_FEW_RECORDS = 1261; +exports.ER_WARN_TOO_MANY_RECORDS = 1262; +exports.ER_WARN_NULL_TO_NOTNULL = 1263; +exports.ER_WARN_DATA_OUT_OF_RANGE = 1264; +exports.WARN_DATA_TRUNCATED = 1265; +exports.ER_WARN_USING_OTHER_HANDLER = 1266; +exports.ER_CANT_AGGREGATE_2COLLATIONS = 1267; +exports.ER_DROP_USER = 1268; +exports.ER_REVOKE_GRANTS = 1269; +exports.ER_CANT_AGGREGATE_3COLLATIONS = 1270; +exports.ER_CANT_AGGREGATE_NCOLLATIONS = 1271; +exports.ER_VARIABLE_IS_NOT_STRUCT = 1272; +exports.ER_UNKNOWN_COLLATION = 1273; +exports.ER_SLAVE_IGNORED_SSL_PARAMS = 1274; +exports.ER_SERVER_IS_IN_SECURE_AUTH_MODE = 1275; +exports.ER_WARN_FIELD_RESOLVED = 1276; +exports.ER_BAD_SLAVE_UNTIL_COND = 1277; +exports.ER_MISSING_SKIP_SLAVE = 1278; +exports.ER_UNTIL_COND_IGNORED = 1279; +exports.ER_WRONG_NAME_FOR_INDEX = 1280; +exports.ER_WRONG_NAME_FOR_CATALOG = 1281; +exports.ER_WARN_QC_RESIZE = 1282; +exports.ER_BAD_FT_COLUMN = 1283; +exports.ER_UNKNOWN_KEY_CACHE = 1284; +exports.ER_WARN_HOSTNAME_WONT_WORK = 1285; +exports.ER_UNKNOWN_STORAGE_ENGINE = 1286; +exports.ER_WARN_DEPRECATED_SYNTAX = 1287; +exports.ER_NON_UPDATABLE_TABLE = 1288; +exports.ER_FEATURE_DISABLED = 1289; +exports.ER_OPTION_PREVENTS_STATEMENT = 1290; +exports.ER_DUPLICATED_VALUE_IN_TYPE = 1291; +exports.ER_TRUNCATED_WRONG_VALUE = 1292; +exports.ER_TOO_MUCH_AUTO_TIMESTAMP_COLS = 1293; +exports.ER_INVALID_ON_UPDATE = 1294; +exports.ER_UNSUPPORTED_PS = 1295; +exports.ER_GET_ERRMSG = 1296; +exports.ER_GET_TEMPORARY_ERRMSG = 1297; +exports.ER_UNKNOWN_TIME_ZONE = 1298; +exports.ER_WARN_INVALID_TIMESTAMP = 1299; +exports.ER_INVALID_CHARACTER_STRING = 1300; +exports.ER_WARN_ALLOWED_PACKET_OVERFLOWED = 1301; +exports.ER_CONFLICTING_DECLARATIONS = 1302; +exports.ER_SP_NO_RECURSIVE_CREATE = 1303; +exports.ER_SP_ALREADY_EXISTS = 1304; +exports.ER_SP_DOES_NOT_EXIST = 1305; +exports.ER_SP_DROP_FAILED = 1306; +exports.ER_SP_STORE_FAILED = 1307; +exports.ER_SP_LILABEL_MISMATCH = 1308; +exports.ER_SP_LABEL_REDEFINE = 1309; +exports.ER_SP_LABEL_MISMATCH = 1310; +exports.ER_SP_UNINIT_VAR = 1311; +exports.ER_SP_BADSELECT = 1312; +exports.ER_SP_BADRETURN = 1313; +exports.ER_SP_BADSTATEMENT = 1314; +exports.ER_UPDATE_LOG_DEPRECATED_IGNORED = 1315; +exports.ER_UPDATE_LOG_DEPRECATED_TRANSLATED = 1316; +exports.ER_QUERY_INTERRUPTED = 1317; +exports.ER_SP_WRONG_NO_OF_ARGS = 1318; +exports.ER_SP_COND_MISMATCH = 1319; +exports.ER_SP_NORETURN = 1320; +exports.ER_SP_NORETURNEND = 1321; +exports.ER_SP_BAD_CURSOR_QUERY = 1322; +exports.ER_SP_BAD_CURSOR_SELECT = 1323; +exports.ER_SP_CURSOR_MISMATCH = 1324; +exports.ER_SP_CURSOR_ALREADY_OPEN = 1325; +exports.ER_SP_CURSOR_NOT_OPEN = 1326; +exports.ER_SP_UNDECLARED_VAR = 1327; +exports.ER_SP_WRONG_NO_OF_FETCH_ARGS = 1328; +exports.ER_SP_FETCH_NO_DATA = 1329; +exports.ER_SP_DUP_PARAM = 1330; +exports.ER_SP_DUP_VAR = 1331; +exports.ER_SP_DUP_COND = 1332; +exports.ER_SP_DUP_CURS = 1333; +exports.ER_SP_CANT_ALTER = 1334; +exports.ER_SP_SUBSELECT_NYI = 1335; +exports.ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG = 1336; +exports.ER_SP_VARCOND_AFTER_CURSHNDLR = 1337; +exports.ER_SP_CURSOR_AFTER_HANDLER = 1338; +exports.ER_SP_CASE_NOT_FOUND = 1339; +exports.ER_FPARSER_TOO_BIG_FILE = 1340; +exports.ER_FPARSER_BAD_HEADER = 1341; +exports.ER_FPARSER_EOF_IN_COMMENT = 1342; +exports.ER_FPARSER_ERROR_IN_PARAMETER = 1343; +exports.ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER = 1344; +exports.ER_VIEW_NO_EXPLAIN = 1345; +exports.ER_FRM_UNKNOWN_TYPE = 1346; +exports.ER_WRONG_OBJECT = 1347; +exports.ER_NONUPDATEABLE_COLUMN = 1348; +exports.ER_VIEW_SELECT_DERIVED = 1349; +exports.ER_VIEW_SELECT_CLAUSE = 1350; +exports.ER_VIEW_SELECT_VARIABLE = 1351; +exports.ER_VIEW_SELECT_TMPTABLE = 1352; +exports.ER_VIEW_WRONG_LIST = 1353; +exports.ER_WARN_VIEW_MERGE = 1354; +exports.ER_WARN_VIEW_WITHOUT_KEY = 1355; +exports.ER_VIEW_INVALID = 1356; +exports.ER_SP_NO_DROP_SP = 1357; +exports.ER_SP_GOTO_IN_HNDLR = 1358; +exports.ER_TRG_ALREADY_EXISTS = 1359; +exports.ER_TRG_DOES_NOT_EXIST = 1360; +exports.ER_TRG_ON_VIEW_OR_TEMP_TABLE = 1361; +exports.ER_TRG_CANT_CHANGE_ROW = 1362; +exports.ER_TRG_NO_SUCH_ROW_IN_TRG = 1363; +exports.ER_NO_DEFAULT_FOR_FIELD = 1364; +exports.ER_DIVISION_BY_ZERO = 1365; +exports.ER_TRUNCATED_WRONG_VALUE_FOR_FIELD = 1366; +exports.ER_ILLEGAL_VALUE_FOR_TYPE = 1367; +exports.ER_VIEW_NONUPD_CHECK = 1368; +exports.ER_VIEW_CHECK_FAILED = 1369; +exports.ER_PROCACCESS_DENIED_ERROR = 1370; +exports.ER_RELAY_LOG_FAIL = 1371; +exports.ER_PASSWD_LENGTH = 1372; +exports.ER_UNKNOWN_TARGET_BINLOG = 1373; +exports.ER_IO_ERR_LOG_INDEX_READ = 1374; +exports.ER_BINLOG_PURGE_PROHIBITED = 1375; +exports.ER_FSEEK_FAIL = 1376; +exports.ER_BINLOG_PURGE_FATAL_ERR = 1377; +exports.ER_LOG_IN_USE = 1378; +exports.ER_LOG_PURGE_UNKNOWN_ERR = 1379; +exports.ER_RELAY_LOG_INIT = 1380; +exports.ER_NO_BINARY_LOGGING = 1381; +exports.ER_RESERVED_SYNTAX = 1382; +exports.ER_WSAS_FAILED = 1383; +exports.ER_DIFF_GROUPS_PROC = 1384; +exports.ER_NO_GROUP_FOR_PROC = 1385; +exports.ER_ORDER_WITH_PROC = 1386; +exports.ER_LOGGING_PROHIBIT_CHANGING_OF = 1387; +exports.ER_NO_FILE_MAPPING = 1388; +exports.ER_WRONG_MAGIC = 1389; +exports.ER_PS_MANY_PARAM = 1390; +exports.ER_KEY_PART_0 = 1391; +exports.ER_VIEW_CHECKSUM = 1392; +exports.ER_VIEW_MULTIUPDATE = 1393; +exports.ER_VIEW_NO_INSERT_FIELD_LIST = 1394; +exports.ER_VIEW_DELETE_MERGE_VIEW = 1395; +exports.ER_CANNOT_USER = 1396; +exports.ER_XAER_NOTA = 1397; +exports.ER_XAER_INVAL = 1398; +exports.ER_XAER_RMFAIL = 1399; +exports.ER_XAER_OUTSIDE = 1400; +exports.ER_XAER_RMERR = 1401; +exports.ER_XA_RBROLLBACK = 1402; +exports.ER_NONEXISTING_PROC_GRANT = 1403; +exports.ER_PROC_AUTO_GRANT_FAIL = 1404; +exports.ER_PROC_AUTO_REVOKE_FAIL = 1405; +exports.ER_DATA_TOO_LONG = 1406; +exports.ER_SP_BAD_SQLSTATE = 1407; +exports.ER_STARTUP = 1408; +exports.ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR = 1409; +exports.ER_CANT_CREATE_USER_WITH_GRANT = 1410; +exports.ER_WRONG_VALUE_FOR_TYPE = 1411; +exports.ER_TABLE_DEF_CHANGED = 1412; +exports.ER_SP_DUP_HANDLER = 1413; +exports.ER_SP_NOT_VAR_ARG = 1414; +exports.ER_SP_NO_RETSET = 1415; +exports.ER_CANT_CREATE_GEOMETRY_OBJECT = 1416; +exports.ER_FAILED_ROUTINE_BREAK_BINLOG = 1417; +exports.ER_BINLOG_UNSAFE_ROUTINE = 1418; +exports.ER_BINLOG_CREATE_ROUTINE_NEED_SUPER = 1419; +exports.ER_EXEC_STMT_WITH_OPEN_CURSOR = 1420; +exports.ER_STMT_HAS_NO_OPEN_CURSOR = 1421; +exports.ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG = 1422; +exports.ER_NO_DEFAULT_FOR_VIEW_FIELD = 1423; +exports.ER_SP_NO_RECURSION = 1424; +exports.ER_TOO_BIG_SCALE = 1425; +exports.ER_TOO_BIG_PRECISION = 1426; +exports.ER_M_BIGGER_THAN_D = 1427; +exports.ER_WRONG_LOCK_OF_SYSTEM_TABLE = 1428; +exports.ER_CONNECT_TO_FOREIGN_DATA_SOURCE = 1429; +exports.ER_QUERY_ON_FOREIGN_DATA_SOURCE = 1430; +exports.ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST = 1431; +exports.ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE = 1432; +exports.ER_FOREIGN_DATA_STRING_INVALID = 1433; +exports.ER_CANT_CREATE_FEDERATED_TABLE = 1434; +exports.ER_TRG_IN_WRONG_SCHEMA = 1435; +exports.ER_STACK_OVERRUN_NEED_MORE = 1436; +exports.ER_TOO_LONG_BODY = 1437; +exports.ER_WARN_CANT_DROP_DEFAULT_KEYCACHE = 1438; +exports.ER_TOO_BIG_DISPLAYWIDTH = 1439; +exports.ER_XAER_DUPID = 1440; +exports.ER_DATETIME_FUNCTION_OVERFLOW = 1441; +exports.ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG = 1442; +exports.ER_VIEW_PREVENT_UPDATE = 1443; +exports.ER_PS_NO_RECURSION = 1444; +exports.ER_SP_CANT_SET_AUTOCOMMIT = 1445; +exports.ER_MALFORMED_DEFINER = 1446; +exports.ER_VIEW_FRM_NO_USER = 1447; +exports.ER_VIEW_OTHER_USER = 1448; +exports.ER_NO_SUCH_USER = 1449; +exports.ER_FORBID_SCHEMA_CHANGE = 1450; +exports.ER_ROW_IS_REFERENCED_2 = 1451; +exports.ER_NO_REFERENCED_ROW_2 = 1452; +exports.ER_SP_BAD_VAR_SHADOW = 1453; +exports.ER_TRG_NO_DEFINER = 1454; +exports.ER_OLD_FILE_FORMAT = 1455; +exports.ER_SP_RECURSION_LIMIT = 1456; +exports.ER_SP_PROC_TABLE_CORRUPT = 1457; +exports.ER_SP_WRONG_NAME = 1458; +exports.ER_TABLE_NEEDS_UPGRADE = 1459; +exports.ER_SP_NO_AGGREGATE = 1460; +exports.ER_MAX_PREPARED_STMT_COUNT_REACHED = 1461; +exports.ER_VIEW_RECURSIVE = 1462; +exports.ER_NON_GROUPING_FIELD_USED = 1463; +exports.ER_TABLE_CANT_HANDLE_SPKEYS = 1464; +exports.ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA = 1465; +exports.ER_REMOVED_SPACES = 1466; +exports.ER_AUTOINC_READ_FAILED = 1467; +exports.ER_USERNAME = 1468; +exports.ER_HOSTNAME = 1469; +exports.ER_WRONG_STRING_LENGTH = 1470; +exports.ER_NON_INSERTABLE_TABLE = 1471; +exports.ER_ADMIN_WRONG_MRG_TABLE = 1472; +exports.ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT = 1473; +exports.ER_NAME_BECOMES_EMPTY = 1474; +exports.ER_AMBIGUOUS_FIELD_TERM = 1475; +exports.ER_FOREIGN_SERVER_EXISTS = 1476; +exports.ER_FOREIGN_SERVER_DOESNT_EXIST = 1477; +exports.ER_ILLEGAL_HA_CREATE_OPTION = 1478; +exports.ER_PARTITION_REQUIRES_VALUES_ERROR = 1479; +exports.ER_PARTITION_WRONG_VALUES_ERROR = 1480; +exports.ER_PARTITION_MAXVALUE_ERROR = 1481; +exports.ER_PARTITION_SUBPARTITION_ERROR = 1482; +exports.ER_PARTITION_SUBPART_MIX_ERROR = 1483; +exports.ER_PARTITION_WRONG_NO_PART_ERROR = 1484; +exports.ER_PARTITION_WRONG_NO_SUBPART_ERROR = 1485; +exports.ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR = 1486; +exports.ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR = 1487; +exports.ER_FIELD_NOT_FOUND_PART_ERROR = 1488; +exports.ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR = 1489; +exports.ER_INCONSISTENT_PARTITION_INFO_ERROR = 1490; +exports.ER_PARTITION_FUNC_NOT_ALLOWED_ERROR = 1491; +exports.ER_PARTITIONS_MUST_BE_DEFINED_ERROR = 1492; +exports.ER_RANGE_NOT_INCREASING_ERROR = 1493; +exports.ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR = 1494; +exports.ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR = 1495; +exports.ER_PARTITION_ENTRY_ERROR = 1496; +exports.ER_MIX_HANDLER_ERROR = 1497; +exports.ER_PARTITION_NOT_DEFINED_ERROR = 1498; +exports.ER_TOO_MANY_PARTITIONS_ERROR = 1499; +exports.ER_SUBPARTITION_ERROR = 1500; +exports.ER_CANT_CREATE_HANDLER_FILE = 1501; +exports.ER_BLOB_FIELD_IN_PART_FUNC_ERROR = 1502; +exports.ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF = 1503; +exports.ER_NO_PARTS_ERROR = 1504; +exports.ER_PARTITION_MGMT_ON_NONPARTITIONED = 1505; +exports.ER_FOREIGN_KEY_ON_PARTITIONED = 1506; +exports.ER_DROP_PARTITION_NON_EXISTENT = 1507; +exports.ER_DROP_LAST_PARTITION = 1508; +exports.ER_COALESCE_ONLY_ON_HASH_PARTITION = 1509; +exports.ER_REORG_HASH_ONLY_ON_SAME_NO = 1510; +exports.ER_REORG_NO_PARAM_ERROR = 1511; +exports.ER_ONLY_ON_RANGE_LIST_PARTITION = 1512; +exports.ER_ADD_PARTITION_SUBPART_ERROR = 1513; +exports.ER_ADD_PARTITION_NO_NEW_PARTITION = 1514; +exports.ER_COALESCE_PARTITION_NO_PARTITION = 1515; +exports.ER_REORG_PARTITION_NOT_EXIST = 1516; +exports.ER_SAME_NAME_PARTITION = 1517; +exports.ER_NO_BINLOG_ERROR = 1518; +exports.ER_CONSECUTIVE_REORG_PARTITIONS = 1519; +exports.ER_REORG_OUTSIDE_RANGE = 1520; +exports.ER_PARTITION_FUNCTION_FAILURE = 1521; +exports.ER_PART_STATE_ERROR = 1522; +exports.ER_LIMITED_PART_RANGE = 1523; +exports.ER_PLUGIN_IS_NOT_LOADED = 1524; +exports.ER_WRONG_VALUE = 1525; +exports.ER_NO_PARTITION_FOR_GIVEN_VALUE = 1526; +exports.ER_FILEGROUP_OPTION_ONLY_ONCE = 1527; +exports.ER_CREATE_FILEGROUP_FAILED = 1528; +exports.ER_DROP_FILEGROUP_FAILED = 1529; +exports.ER_TABLESPACE_AUTO_EXTEND_ERROR = 1530; +exports.ER_WRONG_SIZE_NUMBER = 1531; +exports.ER_SIZE_OVERFLOW_ERROR = 1532; +exports.ER_ALTER_FILEGROUP_FAILED = 1533; +exports.ER_BINLOG_ROW_LOGGING_FAILED = 1534; +exports.ER_BINLOG_ROW_WRONG_TABLE_DEF = 1535; +exports.ER_BINLOG_ROW_RBR_TO_SBR = 1536; +exports.ER_EVENT_ALREADY_EXISTS = 1537; +exports.ER_EVENT_STORE_FAILED = 1538; +exports.ER_EVENT_DOES_NOT_EXIST = 1539; +exports.ER_EVENT_CANT_ALTER = 1540; +exports.ER_EVENT_DROP_FAILED = 1541; +exports.ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG = 1542; +exports.ER_EVENT_ENDS_BEFORE_STARTS = 1543; +exports.ER_EVENT_EXEC_TIME_IN_THE_PAST = 1544; +exports.ER_EVENT_OPEN_TABLE_FAILED = 1545; +exports.ER_EVENT_NEITHER_M_EXPR_NOR_M_AT = 1546; +exports.ER_COL_COUNT_DOESNT_MATCH_CORRUPTED = 1547; +exports.ER_CANNOT_LOAD_FROM_TABLE = 1548; +exports.ER_EVENT_CANNOT_DELETE = 1549; +exports.ER_EVENT_COMPILE_ERROR = 1550; +exports.ER_EVENT_SAME_NAME = 1551; +exports.ER_EVENT_DATA_TOO_LONG = 1552; +exports.ER_DROP_INDEX_FK = 1553; +exports.ER_WARN_DEPRECATED_SYNTAX_WITH_VER = 1554; +exports.ER_CANT_WRITE_LOCK_LOG_TABLE = 1555; +exports.ER_CANT_LOCK_LOG_TABLE = 1556; +exports.ER_FOREIGN_DUPLICATE_KEY = 1557; +exports.ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE = 1558; +exports.ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR = 1559; +exports.ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT = 1560; +exports.ER_NDB_CANT_SWITCH_BINLOG_FORMAT = 1561; +exports.ER_PARTITION_NO_TEMPORARY = 1562; +exports.ER_PARTITION_CONST_DOMAIN_ERROR = 1563; +exports.ER_PARTITION_FUNCTION_IS_NOT_ALLOWED = 1564; +exports.ER_DDL_LOG_ERROR = 1565; +exports.ER_NULL_IN_VALUES_LESS_THAN = 1566; +exports.ER_WRONG_PARTITION_NAME = 1567; +exports.ER_CANT_CHANGE_TX_CHARACTERISTICS = 1568; +exports.ER_DUP_ENTRY_AUTOINCREMENT_CASE = 1569; +exports.ER_EVENT_MODIFY_QUEUE_ERROR = 1570; +exports.ER_EVENT_SET_VAR_ERROR = 1571; +exports.ER_PARTITION_MERGE_ERROR = 1572; +exports.ER_CANT_ACTIVATE_LOG = 1573; +exports.ER_RBR_NOT_AVAILABLE = 1574; +exports.ER_BASE64_DECODE_ERROR = 1575; +exports.ER_EVENT_RECURSION_FORBIDDEN = 1576; +exports.ER_EVENTS_DB_ERROR = 1577; +exports.ER_ONLY_INTEGERS_ALLOWED = 1578; +exports.ER_UNSUPORTED_LOG_ENGINE = 1579; +exports.ER_BAD_LOG_STATEMENT = 1580; +exports.ER_CANT_RENAME_LOG_TABLE = 1581; +exports.ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT = 1582; +exports.ER_WRONG_PARAMETERS_TO_NATIVE_FCT = 1583; +exports.ER_WRONG_PARAMETERS_TO_STORED_FCT = 1584; +exports.ER_NATIVE_FCT_NAME_COLLISION = 1585; +exports.ER_DUP_ENTRY_WITH_KEY_NAME = 1586; +exports.ER_BINLOG_PURGE_EMFILE = 1587; +exports.ER_EVENT_CANNOT_CREATE_IN_THE_PAST = 1588; +exports.ER_EVENT_CANNOT_ALTER_IN_THE_PAST = 1589; +exports.ER_SLAVE_INCIDENT = 1590; +exports.ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT = 1591; +exports.ER_BINLOG_UNSAFE_STATEMENT = 1592; +exports.ER_SLAVE_FATAL_ERROR = 1593; +exports.ER_SLAVE_RELAY_LOG_READ_FAILURE = 1594; +exports.ER_SLAVE_RELAY_LOG_WRITE_FAILURE = 1595; +exports.ER_SLAVE_CREATE_EVENT_FAILURE = 1596; +exports.ER_SLAVE_MASTER_COM_FAILURE = 1597; +exports.ER_BINLOG_LOGGING_IMPOSSIBLE = 1598; +exports.ER_VIEW_NO_CREATION_CTX = 1599; +exports.ER_VIEW_INVALID_CREATION_CTX = 1600; +exports.ER_SR_INVALID_CREATION_CTX = 1601; +exports.ER_TRG_CORRUPTED_FILE = 1602; +exports.ER_TRG_NO_CREATION_CTX = 1603; +exports.ER_TRG_INVALID_CREATION_CTX = 1604; +exports.ER_EVENT_INVALID_CREATION_CTX = 1605; +exports.ER_TRG_CANT_OPEN_TABLE = 1606; +exports.ER_CANT_CREATE_SROUTINE = 1607; +exports.ER_NEVER_USED = 1608; +exports.ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT = 1609; +exports.ER_SLAVE_CORRUPT_EVENT = 1610; +exports.ER_LOAD_DATA_INVALID_COLUMN = 1611; +exports.ER_LOG_PURGE_NO_FILE = 1612; +exports.ER_XA_RBTIMEOUT = 1613; +exports.ER_XA_RBDEADLOCK = 1614; +exports.ER_NEED_REPREPARE = 1615; +exports.ER_DELAYED_NOT_SUPPORTED = 1616; +exports.WARN_NO_MASTER_INFO = 1617; +exports.WARN_OPTION_IGNORED = 1618; +exports.ER_PLUGIN_DELETE_BUILTIN = 1619; +exports.WARN_PLUGIN_BUSY = 1620; +exports.ER_VARIABLE_IS_READONLY = 1621; +exports.ER_WARN_ENGINE_TRANSACTION_ROLLBACK = 1622; +exports.ER_SLAVE_HEARTBEAT_FAILURE = 1623; +exports.ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE = 1624; +exports.ER_NDB_REPLICATION_SCHEMA_ERROR = 1625; +exports.ER_CONFLICT_FN_PARSE_ERROR = 1626; +exports.ER_EXCEPTIONS_WRITE_ERROR = 1627; +exports.ER_TOO_LONG_TABLE_COMMENT = 1628; +exports.ER_TOO_LONG_FIELD_COMMENT = 1629; +exports.ER_FUNC_INEXISTENT_NAME_COLLISION = 1630; +exports.ER_DATABASE_NAME = 1631; +exports.ER_TABLE_NAME = 1632; +exports.ER_PARTITION_NAME = 1633; +exports.ER_SUBPARTITION_NAME = 1634; +exports.ER_TEMPORARY_NAME = 1635; +exports.ER_RENAMED_NAME = 1636; +exports.ER_TOO_MANY_CONCURRENT_TRXS = 1637; +exports.WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED = 1638; +exports.ER_DEBUG_SYNC_TIMEOUT = 1639; +exports.ER_DEBUG_SYNC_HIT_LIMIT = 1640; +exports.ER_DUP_SIGNAL_SET = 1641; +exports.ER_SIGNAL_WARN = 1642; +exports.ER_SIGNAL_NOT_FOUND = 1643; +exports.ER_SIGNAL_EXCEPTION = 1644; +exports.ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER = 1645; +exports.ER_SIGNAL_BAD_CONDITION_TYPE = 1646; +exports.WARN_COND_ITEM_TRUNCATED = 1647; +exports.ER_COND_ITEM_TOO_LONG = 1648; +exports.ER_UNKNOWN_LOCALE = 1649; +exports.ER_SLAVE_IGNORE_SERVER_IDS = 1650; +exports.ER_QUERY_CACHE_DISABLED = 1651; +exports.ER_SAME_NAME_PARTITION_FIELD = 1652; +exports.ER_PARTITION_COLUMN_LIST_ERROR = 1653; +exports.ER_WRONG_TYPE_COLUMN_VALUE_ERROR = 1654; +exports.ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR = 1655; +exports.ER_MAXVALUE_IN_VALUES_IN = 1656; +exports.ER_TOO_MANY_VALUES_ERROR = 1657; +exports.ER_ROW_SINGLE_PARTITION_FIELD_ERROR = 1658; +exports.ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD = 1659; +exports.ER_PARTITION_FIELDS_TOO_LONG = 1660; +exports.ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE = 1661; +exports.ER_BINLOG_ROW_MODE_AND_STMT_ENGINE = 1662; +exports.ER_BINLOG_UNSAFE_AND_STMT_ENGINE = 1663; +exports.ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE = 1664; +exports.ER_BINLOG_STMT_MODE_AND_ROW_ENGINE = 1665; +exports.ER_BINLOG_ROW_INJECTION_AND_STMT_MODE = 1666; +exports.ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE = 1667; +exports.ER_BINLOG_UNSAFE_LIMIT = 1668; +exports.ER_BINLOG_UNSAFE_INSERT_DELAYED = 1669; +exports.ER_BINLOG_UNSAFE_SYSTEM_TABLE = 1670; +exports.ER_BINLOG_UNSAFE_AUTOINC_COLUMNS = 1671; +exports.ER_BINLOG_UNSAFE_UDF = 1672; +exports.ER_BINLOG_UNSAFE_SYSTEM_VARIABLE = 1673; +exports.ER_BINLOG_UNSAFE_SYSTEM_FUNCTION = 1674; +exports.ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS = 1675; +exports.ER_MESSAGE_AND_STATEMENT = 1676; +exports.ER_SLAVE_CONVERSION_FAILED = 1677; +exports.ER_SLAVE_CANT_CREATE_CONVERSION = 1678; +exports.ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT = 1679; +exports.ER_PATH_LENGTH = 1680; +exports.ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT = 1681; +exports.ER_WRONG_NATIVE_TABLE_STRUCTURE = 1682; +exports.ER_WRONG_PERFSCHEMA_USAGE = 1683; +exports.ER_WARN_I_S_SKIPPED_TABLE = 1684; +exports.ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT = 1685; +exports.ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT = 1686; +exports.ER_SPATIAL_MUST_HAVE_GEOM_COL = 1687; +exports.ER_TOO_LONG_INDEX_COMMENT = 1688; +exports.ER_LOCK_ABORTED = 1689; +exports.ER_DATA_OUT_OF_RANGE = 1690; +exports.ER_WRONG_SPVAR_TYPE_IN_LIMIT = 1691; +exports.ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE = 1692; +exports.ER_BINLOG_UNSAFE_MIXED_STATEMENT = 1693; +exports.ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN = 1694; +exports.ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN = 1695; +exports.ER_FAILED_READ_FROM_PAR_FILE = 1696; +exports.ER_VALUES_IS_NOT_INT_TYPE_ERROR = 1697; +exports.ER_ACCESS_DENIED_NO_PASSWORD_ERROR = 1698; +exports.ER_SET_PASSWORD_AUTH_PLUGIN = 1699; +exports.ER_GRANT_PLUGIN_USER_EXISTS = 1700; +exports.ER_TRUNCATE_ILLEGAL_FK = 1701; +exports.ER_PLUGIN_IS_PERMANENT = 1702; +exports.ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN = 1703; +exports.ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX = 1704; +exports.ER_STMT_CACHE_FULL = 1705; +exports.ER_MULTI_UPDATE_KEY_CONFLICT = 1706; +exports.ER_TABLE_NEEDS_REBUILD = 1707; +exports.WARN_OPTION_BELOW_LIMIT = 1708; +exports.ER_INDEX_COLUMN_TOO_LONG = 1709; +exports.ER_ERROR_IN_TRIGGER_BODY = 1710; +exports.ER_ERROR_IN_UNKNOWN_TRIGGER_BODY = 1711; +exports.ER_INDEX_CORRUPT = 1712; +exports.ER_UNDO_RECORD_TOO_BIG = 1713; +exports.ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT = 1714; +exports.ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE = 1715; +exports.ER_BINLOG_UNSAFE_REPLACE_SELECT = 1716; +exports.ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT = 1717; +exports.ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT = 1718; +exports.ER_BINLOG_UNSAFE_UPDATE_IGNORE = 1719; +exports.ER_PLUGIN_NO_UNINSTALL = 1720; +exports.ER_PLUGIN_NO_INSTALL = 1721; +exports.ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT = 1722; +exports.ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC = 1723; +exports.ER_BINLOG_UNSAFE_INSERT_TWO_KEYS = 1724; +exports.ER_TABLE_IN_FK_CHECK = 1725; +exports.ER_UNSUPPORTED_ENGINE = 1726; +exports.ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST = 1727; +exports.ER_CANNOT_LOAD_FROM_TABLE_V2 = 1728; +exports.ER_MASTER_DELAY_VALUE_OUT_OF_RANGE = 1729; +exports.ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT = 1730; +exports.ER_PARTITION_EXCHANGE_DIFFERENT_OPTION = 1731; +exports.ER_PARTITION_EXCHANGE_PART_TABLE = 1732; +exports.ER_PARTITION_EXCHANGE_TEMP_TABLE = 1733; +exports.ER_PARTITION_INSTEAD_OF_SUBPARTITION = 1734; +exports.ER_UNKNOWN_PARTITION = 1735; +exports.ER_TABLES_DIFFERENT_METADATA = 1736; +exports.ER_ROW_DOES_NOT_MATCH_PARTITION = 1737; +exports.ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX = 1738; +exports.ER_WARN_INDEX_NOT_APPLICABLE = 1739; +exports.ER_PARTITION_EXCHANGE_FOREIGN_KEY = 1740; +exports.ER_NO_SUCH_KEY_VALUE = 1741; +exports.ER_RPL_INFO_DATA_TOO_LONG = 1742; +exports.ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE = 1743; +exports.ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE = 1744; +exports.ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX = 1745; +exports.ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT = 1746; +exports.ER_PARTITION_CLAUSE_ON_NONPARTITIONED = 1747; +exports.ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET = 1748; +exports.ER_NO_SUCH_PARTITION = 1749; +exports.ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE = 1750; +exports.ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE = 1751; +exports.ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE = 1752; +exports.ER_MTS_FEATURE_IS_NOT_SUPPORTED = 1753; +exports.ER_MTS_UPDATED_DBS_GREATER_MAX = 1754; +exports.ER_MTS_CANT_PARALLEL = 1755; +exports.ER_MTS_INCONSISTENT_DATA = 1756; +exports.ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING = 1757; +exports.ER_DA_INVALID_CONDITION_NUMBER = 1758; +exports.ER_INSECURE_PLAIN_TEXT = 1759; +exports.ER_INSECURE_CHANGE_MASTER = 1760; +exports.ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO = 1761; +exports.ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO = 1762; +exports.ER_SQLTHREAD_WITH_SECURE_SLAVE = 1763; +exports.ER_TABLE_HAS_NO_FT = 1764; +exports.ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER = 1765; +exports.ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION = 1766; +exports.ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST = 1767; +exports.ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION = 1768; +exports.ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION = 1769; +exports.ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL = 1770; +exports.ER_SKIPPING_LOGGED_TRANSACTION = 1771; +exports.ER_MALFORMED_GTID_SET_SPECIFICATION = 1772; +exports.ER_MALFORMED_GTID_SET_ENCODING = 1773; +exports.ER_MALFORMED_GTID_SPECIFICATION = 1774; +exports.ER_GNO_EXHAUSTED = 1775; +exports.ER_BAD_SLAVE_AUTO_POSITION = 1776; +exports.ER_AUTO_POSITION_REQUIRES_GTID_MODE_NOT_OFF = 1777; +exports.ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET = 1778; +exports.ER_GTID_MODE_ON_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON = 1779; +exports.ER_GTID_MODE_REQUIRES_BINLOG = 1780; +exports.ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF = 1781; +exports.ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON = 1782; +exports.ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF = 1783; +exports.ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF = 1784; +exports.ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE = 1785; +exports.ER_GTID_UNSAFE_CREATE_SELECT = 1786; +exports.ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION = 1787; +exports.ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME = 1788; +exports.ER_MASTER_HAS_PURGED_REQUIRED_GTIDS = 1789; +exports.ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID = 1790; +exports.ER_UNKNOWN_EXPLAIN_FORMAT = 1791; +exports.ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION = 1792; +exports.ER_TOO_LONG_TABLE_PARTITION_COMMENT = 1793; +exports.ER_SLAVE_CONFIGURATION = 1794; +exports.ER_INNODB_FT_LIMIT = 1795; +exports.ER_INNODB_NO_FT_TEMP_TABLE = 1796; +exports.ER_INNODB_FT_WRONG_DOCID_COLUMN = 1797; +exports.ER_INNODB_FT_WRONG_DOCID_INDEX = 1798; +exports.ER_INNODB_ONLINE_LOG_TOO_BIG = 1799; +exports.ER_UNKNOWN_ALTER_ALGORITHM = 1800; +exports.ER_UNKNOWN_ALTER_LOCK = 1801; +exports.ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS = 1802; +exports.ER_MTS_RECOVERY_FAILURE = 1803; +exports.ER_MTS_RESET_WORKERS = 1804; +exports.ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2 = 1805; +exports.ER_SLAVE_SILENT_RETRY_TRANSACTION = 1806; +exports.ER_DISCARD_FK_CHECKS_RUNNING = 1807; +exports.ER_TABLE_SCHEMA_MISMATCH = 1808; +exports.ER_TABLE_IN_SYSTEM_TABLESPACE = 1809; +exports.ER_IO_READ_ERROR = 1810; +exports.ER_IO_WRITE_ERROR = 1811; +exports.ER_TABLESPACE_MISSING = 1812; +exports.ER_TABLESPACE_EXISTS = 1813; +exports.ER_TABLESPACE_DISCARDED = 1814; +exports.ER_INTERNAL_ERROR = 1815; +exports.ER_INNODB_IMPORT_ERROR = 1816; +exports.ER_INNODB_INDEX_CORRUPT = 1817; +exports.ER_INVALID_YEAR_COLUMN_LENGTH = 1818; +exports.ER_NOT_VALID_PASSWORD = 1819; +exports.ER_MUST_CHANGE_PASSWORD = 1820; +exports.ER_FK_NO_INDEX_CHILD = 1821; +exports.ER_FK_NO_INDEX_PARENT = 1822; +exports.ER_FK_FAIL_ADD_SYSTEM = 1823; +exports.ER_FK_CANNOT_OPEN_PARENT = 1824; +exports.ER_FK_INCORRECT_OPTION = 1825; +exports.ER_FK_DUP_NAME = 1826; +exports.ER_PASSWORD_FORMAT = 1827; +exports.ER_FK_COLUMN_CANNOT_DROP = 1828; +exports.ER_FK_COLUMN_CANNOT_DROP_CHILD = 1829; +exports.ER_FK_COLUMN_NOT_NULL = 1830; +exports.ER_DUP_INDEX = 1831; +exports.ER_FK_COLUMN_CANNOT_CHANGE = 1832; +exports.ER_FK_COLUMN_CANNOT_CHANGE_CHILD = 1833; +exports.ER_FK_CANNOT_DELETE_PARENT = 1834; +exports.ER_MALFORMED_PACKET = 1835; +exports.ER_READ_ONLY_MODE = 1836; +exports.ER_GTID_NEXT_TYPE_UNDEFINED_GROUP = 1837; +exports.ER_VARIABLE_NOT_SETTABLE_IN_SP = 1838; +exports.ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF = 1839; +exports.ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY = 1840; +exports.ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY = 1841; +exports.ER_GTID_PURGED_WAS_CHANGED = 1842; +exports.ER_GTID_EXECUTED_WAS_CHANGED = 1843; +exports.ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES = 1844; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED = 1845; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON = 1846; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY = 1847; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION = 1848; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME = 1849; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE = 1850; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK = 1851; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE = 1852; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK = 1853; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC = 1854; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS = 1855; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS = 1856; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS = 1857; +exports.ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE = 1858; +exports.ER_DUP_UNKNOWN_IN_INDEX = 1859; +exports.ER_IDENT_CAUSES_TOO_LONG_PATH = 1860; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL = 1861; +exports.ER_MUST_CHANGE_PASSWORD_LOGIN = 1862; +exports.ER_ROW_IN_WRONG_PARTITION = 1863; +exports.ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX = 1864; +exports.ER_INNODB_NO_FT_USES_PARSER = 1865; +exports.ER_BINLOG_LOGICAL_CORRUPTION = 1866; +exports.ER_WARN_PURGE_LOG_IN_USE = 1867; +exports.ER_WARN_PURGE_LOG_IS_ACTIVE = 1868; +exports.ER_AUTO_INCREMENT_CONFLICT = 1869; +exports.WARN_ON_BLOCKHOLE_IN_RBR = 1870; +exports.ER_SLAVE_MI_INIT_REPOSITORY = 1871; +exports.ER_SLAVE_RLI_INIT_REPOSITORY = 1872; +exports.ER_ACCESS_DENIED_CHANGE_USER_ERROR = 1873; +exports.ER_INNODB_READ_ONLY = 1874; +exports.ER_STOP_SLAVE_SQL_THREAD_TIMEOUT = 1875; +exports.ER_STOP_SLAVE_IO_THREAD_TIMEOUT = 1876; +exports.ER_TABLE_CORRUPT = 1877; +exports.ER_TEMP_FILE_WRITE_FAILURE = 1878; +exports.ER_INNODB_FT_AUX_NOT_HEX_ID = 1879; +exports.ER_OLD_TEMPORALS_UPGRADED = 1880; +exports.ER_INNODB_FORCED_RECOVERY = 1881; +exports.ER_AES_INVALID_IV = 1882; +exports.ER_PLUGIN_CANNOT_BE_UNINSTALLED = 1883; +exports.ER_GTID_UNSAFE_BINLOG_SPLITTABLE_STATEMENT_AND_GTID_GROUP = 1884; +exports.ER_SLAVE_HAS_MORE_GTIDS_THAN_MASTER = 1885; +exports.ER_FILE_CORRUPT = 3000; +exports.ER_ERROR_ON_MASTER = 3001; +exports.ER_INCONSISTENT_ERROR = 3002; +exports.ER_STORAGE_ENGINE_NOT_LOADED = 3003; +exports.ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER = 3004; +exports.ER_WARN_LEGACY_SYNTAX_CONVERTED = 3005; +exports.ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN = 3006; +exports.ER_CANNOT_DISCARD_TEMPORARY_TABLE = 3007; +exports.ER_FK_DEPTH_EXCEEDED = 3008; +exports.ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2 = 3009; +exports.ER_WARN_TRIGGER_DOESNT_HAVE_CREATED = 3010; +exports.ER_REFERENCED_TRG_DOES_NOT_EXIST = 3011; +exports.ER_EXPLAIN_NOT_SUPPORTED = 3012; +exports.ER_INVALID_FIELD_SIZE = 3013; +exports.ER_MISSING_HA_CREATE_OPTION = 3014; +exports.ER_ENGINE_OUT_OF_MEMORY = 3015; +exports.ER_PASSWORD_EXPIRE_ANONYMOUS_USER = 3016; +exports.ER_SLAVE_SQL_THREAD_MUST_STOP = 3017; +exports.ER_NO_FT_MATERIALIZED_SUBQUERY = 3018; +exports.ER_INNODB_UNDO_LOG_FULL = 3019; +exports.ER_INVALID_ARGUMENT_FOR_LOGARITHM = 3020; +exports.ER_SLAVE_CHANNEL_IO_THREAD_MUST_STOP = 3021; +exports.ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO = 3022; +exports.ER_WARN_ONLY_MASTER_LOG_FILE_NO_POS = 3023; +exports.ER_QUERY_TIMEOUT = 3024; +exports.ER_NON_RO_SELECT_DISABLE_TIMER = 3025; +exports.ER_DUP_LIST_ENTRY = 3026; +exports.ER_SQL_MODE_NO_EFFECT = 3027; +exports.ER_AGGREGATE_ORDER_FOR_UNION = 3028; +exports.ER_AGGREGATE_ORDER_NON_AGG_QUERY = 3029; +exports.ER_SLAVE_WORKER_STOPPED_PREVIOUS_THD_ERROR = 3030; +exports.ER_DONT_SUPPORT_SLAVE_PRESERVE_COMMIT_ORDER = 3031; +exports.ER_SERVER_OFFLINE_MODE = 3032; +exports.ER_GIS_DIFFERENT_SRIDS = 3033; +exports.ER_GIS_UNSUPPORTED_ARGUMENT = 3034; +exports.ER_GIS_UNKNOWN_ERROR = 3035; +exports.ER_GIS_UNKNOWN_EXCEPTION = 3036; +exports.ER_GIS_INVALID_DATA = 3037; +exports.ER_BOOST_GEOMETRY_EMPTY_INPUT_EXCEPTION = 3038; +exports.ER_BOOST_GEOMETRY_CENTROID_EXCEPTION = 3039; +exports.ER_BOOST_GEOMETRY_OVERLAY_INVALID_INPUT_EXCEPTION = 3040; +exports.ER_BOOST_GEOMETRY_TURN_INFO_EXCEPTION = 3041; +exports.ER_BOOST_GEOMETRY_SELF_INTERSECTION_POINT_EXCEPTION = 3042; +exports.ER_BOOST_GEOMETRY_UNKNOWN_EXCEPTION = 3043; +exports.ER_STD_BAD_ALLOC_ERROR = 3044; +exports.ER_STD_DOMAIN_ERROR = 3045; +exports.ER_STD_LENGTH_ERROR = 3046; +exports.ER_STD_INVALID_ARGUMENT = 3047; +exports.ER_STD_OUT_OF_RANGE_ERROR = 3048; +exports.ER_STD_OVERFLOW_ERROR = 3049; +exports.ER_STD_RANGE_ERROR = 3050; +exports.ER_STD_UNDERFLOW_ERROR = 3051; +exports.ER_STD_LOGIC_ERROR = 3052; +exports.ER_STD_RUNTIME_ERROR = 3053; +exports.ER_STD_UNKNOWN_EXCEPTION = 3054; +exports.ER_GIS_DATA_WRONG_ENDIANESS = 3055; +exports.ER_CHANGE_MASTER_PASSWORD_LENGTH = 3056; +exports.ER_USER_LOCK_WRONG_NAME = 3057; +exports.ER_USER_LOCK_DEADLOCK = 3058; +exports.ER_REPLACE_INACCESSIBLE_ROWS = 3059; +exports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS = 3060; +exports.ER_ILLEGAL_USER_VAR = 3061; +exports.ER_GTID_MODE_OFF = 3062; +exports.ER_UNSUPPORTED_BY_REPLICATION_THREAD = 3063; +exports.ER_INCORRECT_TYPE = 3064; +exports.ER_FIELD_IN_ORDER_NOT_SELECT = 3065; +exports.ER_AGGREGATE_IN_ORDER_NOT_SELECT = 3066; +exports.ER_INVALID_RPL_WILD_TABLE_FILTER_PATTERN = 3067; +exports.ER_NET_OK_PACKET_TOO_LARGE = 3068; +exports.ER_INVALID_JSON_DATA = 3069; +exports.ER_INVALID_GEOJSON_MISSING_MEMBER = 3070; +exports.ER_INVALID_GEOJSON_WRONG_TYPE = 3071; +exports.ER_INVALID_GEOJSON_UNSPECIFIED = 3072; +exports.ER_DIMENSION_UNSUPPORTED = 3073; +exports.ER_SLAVE_CHANNEL_DOES_NOT_EXIST = 3074; +exports.ER_SLAVE_MULTIPLE_CHANNELS_HOST_PORT = 3075; +exports.ER_SLAVE_CHANNEL_NAME_INVALID_OR_TOO_LONG = 3076; +exports.ER_SLAVE_NEW_CHANNEL_WRONG_REPOSITORY = 3077; +exports.ER_SLAVE_CHANNEL_DELETE = 3078; +exports.ER_SLAVE_MULTIPLE_CHANNELS_CMD = 3079; +exports.ER_SLAVE_MAX_CHANNELS_EXCEEDED = 3080; +exports.ER_SLAVE_CHANNEL_MUST_STOP = 3081; +exports.ER_SLAVE_CHANNEL_NOT_RUNNING = 3082; +exports.ER_SLAVE_CHANNEL_WAS_RUNNING = 3083; +exports.ER_SLAVE_CHANNEL_WAS_NOT_RUNNING = 3084; +exports.ER_SLAVE_CHANNEL_SQL_THREAD_MUST_STOP = 3085; +exports.ER_SLAVE_CHANNEL_SQL_SKIP_COUNTER = 3086; +exports.ER_WRONG_FIELD_WITH_GROUP_V2 = 3087; +exports.ER_MIX_OF_GROUP_FUNC_AND_FIELDS_V2 = 3088; +exports.ER_WARN_DEPRECATED_SYSVAR_UPDATE = 3089; +exports.ER_WARN_DEPRECATED_SQLMODE = 3090; +exports.ER_CANNOT_LOG_PARTIAL_DROP_DATABASE_WITH_GTID = 3091; +exports.ER_GROUP_REPLICATION_CONFIGURATION = 3092; +exports.ER_GROUP_REPLICATION_RUNNING = 3093; +exports.ER_GROUP_REPLICATION_APPLIER_INIT_ERROR = 3094; +exports.ER_GROUP_REPLICATION_STOP_APPLIER_THREAD_TIMEOUT = 3095; +exports.ER_GROUP_REPLICATION_COMMUNICATION_LAYER_SESSION_ERROR = 3096; +exports.ER_GROUP_REPLICATION_COMMUNICATION_LAYER_JOIN_ERROR = 3097; +exports.ER_BEFORE_DML_VALIDATION_ERROR = 3098; +exports.ER_PREVENTS_VARIABLE_WITHOUT_RBR = 3099; +exports.ER_RUN_HOOK_ERROR = 3100; +exports.ER_TRANSACTION_ROLLBACK_DURING_COMMIT = 3101; +exports.ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED = 3102; +exports.ER_UNSUPPORTED_ALTER_INPLACE_ON_VIRTUAL_COLUMN = 3103; +exports.ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN = 3104; +exports.ER_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN = 3105; +exports.ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN = 3106; +exports.ER_GENERATED_COLUMN_NON_PRIOR = 3107; +exports.ER_DEPENDENT_BY_GENERATED_COLUMN = 3108; +exports.ER_GENERATED_COLUMN_REF_AUTO_INC = 3109; +exports.ER_FEATURE_NOT_AVAILABLE = 3110; +exports.ER_CANT_SET_GTID_MODE = 3111; +exports.ER_CANT_USE_AUTO_POSITION_WITH_GTID_MODE_OFF = 3112; +exports.ER_CANT_REPLICATE_ANONYMOUS_WITH_AUTO_POSITION = 3113; +exports.ER_CANT_REPLICATE_ANONYMOUS_WITH_GTID_MODE_ON = 3114; +exports.ER_CANT_REPLICATE_GTID_WITH_GTID_MODE_OFF = 3115; +exports.ER_CANT_SET_ENFORCE_GTID_CONSISTENCY_ON_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS = 3116; +exports.ER_SET_ENFORCE_GTID_CONSISTENCY_WARN_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS = 3117; +exports.ER_ACCOUNT_HAS_BEEN_LOCKED = 3118; +exports.ER_WRONG_TABLESPACE_NAME = 3119; +exports.ER_TABLESPACE_IS_NOT_EMPTY = 3120; +exports.ER_WRONG_FILE_NAME = 3121; +exports.ER_BOOST_GEOMETRY_INCONSISTENT_TURNS_EXCEPTION = 3122; +exports.ER_WARN_OPTIMIZER_HINT_SYNTAX_ERROR = 3123; +exports.ER_WARN_BAD_MAX_EXECUTION_TIME = 3124; +exports.ER_WARN_UNSUPPORTED_MAX_EXECUTION_TIME = 3125; +exports.ER_WARN_CONFLICTING_HINT = 3126; +exports.ER_WARN_UNKNOWN_QB_NAME = 3127; +exports.ER_UNRESOLVED_HINT_NAME = 3128; +exports.ER_WARN_ON_MODIFYING_GTID_EXECUTED_TABLE = 3129; +exports.ER_PLUGGABLE_PROTOCOL_COMMAND_NOT_SUPPORTED = 3130; +exports.ER_LOCKING_SERVICE_WRONG_NAME = 3131; +exports.ER_LOCKING_SERVICE_DEADLOCK = 3132; +exports.ER_LOCKING_SERVICE_TIMEOUT = 3133; +exports.ER_GIS_MAX_POINTS_IN_GEOMETRY_OVERFLOWED = 3134; +exports.ER_SQL_MODE_MERGED = 3135; +exports.ER_VTOKEN_PLUGIN_TOKEN_MISMATCH = 3136; +exports.ER_VTOKEN_PLUGIN_TOKEN_NOT_FOUND = 3137; +exports.ER_CANT_SET_VARIABLE_WHEN_OWNING_GTID = 3138; +exports.ER_SLAVE_CHANNEL_OPERATION_NOT_ALLOWED = 3139; +exports.ER_INVALID_JSON_TEXT = 3140; +exports.ER_INVALID_JSON_TEXT_IN_PARAM = 3141; +exports.ER_INVALID_JSON_BINARY_DATA = 3142; +exports.ER_INVALID_JSON_PATH = 3143; +exports.ER_INVALID_JSON_CHARSET = 3144; +exports.ER_INVALID_JSON_CHARSET_IN_FUNCTION = 3145; +exports.ER_INVALID_TYPE_FOR_JSON = 3146; +exports.ER_INVALID_CAST_TO_JSON = 3147; +exports.ER_INVALID_JSON_PATH_CHARSET = 3148; +exports.ER_INVALID_JSON_PATH_WILDCARD = 3149; +exports.ER_JSON_VALUE_TOO_BIG = 3150; +exports.ER_JSON_KEY_TOO_BIG = 3151; +exports.ER_JSON_USED_AS_KEY = 3152; +exports.ER_JSON_VACUOUS_PATH = 3153; +exports.ER_JSON_BAD_ONE_OR_ALL_ARG = 3154; +exports.ER_NUMERIC_JSON_VALUE_OUT_OF_RANGE = 3155; +exports.ER_INVALID_JSON_VALUE_FOR_CAST = 3156; +exports.ER_JSON_DOCUMENT_TOO_DEEP = 3157; +exports.ER_JSON_DOCUMENT_NULL_KEY = 3158; +exports.ER_SECURE_TRANSPORT_REQUIRED = 3159; +exports.ER_NO_SECURE_TRANSPORTS_CONFIGURED = 3160; +exports.ER_DISABLED_STORAGE_ENGINE = 3161; +exports.ER_USER_DOES_NOT_EXIST = 3162; +exports.ER_USER_ALREADY_EXISTS = 3163; +exports.ER_AUDIT_API_ABORT = 3164; +exports.ER_INVALID_JSON_PATH_ARRAY_CELL = 3165; +exports.ER_BUFPOOL_RESIZE_INPROGRESS = 3166; +exports.ER_FEATURE_DISABLED_SEE_DOC = 3167; +exports.ER_SERVER_ISNT_AVAILABLE = 3168; +exports.ER_SESSION_WAS_KILLED = 3169; +exports.ER_CAPACITY_EXCEEDED = 3170; +exports.ER_CAPACITY_EXCEEDED_IN_RANGE_OPTIMIZER = 3171; +exports.ER_TABLE_NEEDS_UPG_PART = 3172; +exports.ER_CANT_WAIT_FOR_EXECUTED_GTID_SET_WHILE_OWNING_A_GTID = 3173; +exports.ER_CANNOT_ADD_FOREIGN_BASE_COL_VIRTUAL = 3174; +exports.ER_CANNOT_CREATE_VIRTUAL_INDEX_CONSTRAINT = 3175; +exports.ER_ERROR_ON_MODIFYING_GTID_EXECUTED_TABLE = 3176; +exports.ER_LOCK_REFUSED_BY_ENGINE = 3177; +exports.ER_UNSUPPORTED_ALTER_ONLINE_ON_VIRTUAL_COLUMN = 3178; +exports.ER_MASTER_KEY_ROTATION_NOT_SUPPORTED_BY_SE = 3179; +exports.ER_MASTER_KEY_ROTATION_ERROR_BY_SE = 3180; +exports.ER_MASTER_KEY_ROTATION_BINLOG_FAILED = 3181; +exports.ER_MASTER_KEY_ROTATION_SE_UNAVAILABLE = 3182; +exports.ER_TABLESPACE_CANNOT_ENCRYPT = 3183; +exports.ER_INVALID_ENCRYPTION_OPTION = 3184; +exports.ER_CANNOT_FIND_KEY_IN_KEYRING = 3185; +exports.ER_CAPACITY_EXCEEDED_IN_PARSER = 3186; +exports.ER_UNSUPPORTED_ALTER_ENCRYPTION_INPLACE = 3187; +exports.ER_KEYRING_UDF_KEYRING_SERVICE_ERROR = 3188; +exports.ER_USER_COLUMN_OLD_LENGTH = 3189; +exports.ER_CANT_RESET_MASTER = 3190; +exports.ER_GROUP_REPLICATION_MAX_GROUP_SIZE = 3191; +exports.ER_CANNOT_ADD_FOREIGN_BASE_COL_STORED = 3192; +exports.ER_TABLE_REFERENCED = 3193; +exports.ER_PARTITION_ENGINE_DEPRECATED_FOR_TABLE = 3194; +exports.ER_WARN_USING_GEOMFROMWKB_TO_SET_SRID_ZERO = 3195; +exports.ER_WARN_USING_GEOMFROMWKB_TO_SET_SRID = 3196; +exports.ER_XA_RETRY = 3197; +exports.ER_KEYRING_AWS_UDF_AWS_KMS_ERROR = 3198; +exports.ER_BINLOG_UNSAFE_XA = 3199; +exports.ER_UDF_ERROR = 3200; +exports.ER_KEYRING_MIGRATION_FAILURE = 3201; +exports.ER_KEYRING_ACCESS_DENIED_ERROR = 3202; +exports.ER_KEYRING_MIGRATION_STATUS = 3203; + +// Lookup-by-number table +exports[1] = 'EE_CANTCREATEFILE'; +exports[2] = 'EE_READ'; +exports[3] = 'EE_WRITE'; +exports[4] = 'EE_BADCLOSE'; +exports[5] = 'EE_OUTOFMEMORY'; +exports[6] = 'EE_DELETE'; +exports[7] = 'EE_LINK'; +exports[9] = 'EE_EOFERR'; +exports[10] = 'EE_CANTLOCK'; +exports[11] = 'EE_CANTUNLOCK'; +exports[12] = 'EE_DIR'; +exports[13] = 'EE_STAT'; +exports[14] = 'EE_CANT_CHSIZE'; +exports[15] = 'EE_CANT_OPEN_STREAM'; +exports[16] = 'EE_GETWD'; +exports[17] = 'EE_SETWD'; +exports[18] = 'EE_LINK_WARNING'; +exports[19] = 'EE_OPEN_WARNING'; +exports[20] = 'EE_DISK_FULL'; +exports[21] = 'EE_CANT_MKDIR'; +exports[22] = 'EE_UNKNOWN_CHARSET'; +exports[23] = 'EE_OUT_OF_FILERESOURCES'; +exports[24] = 'EE_CANT_READLINK'; +exports[25] = 'EE_CANT_SYMLINK'; +exports[26] = 'EE_REALPATH'; +exports[27] = 'EE_SYNC'; +exports[28] = 'EE_UNKNOWN_COLLATION'; +exports[29] = 'EE_FILENOTFOUND'; +exports[30] = 'EE_FILE_NOT_CLOSED'; +exports[31] = 'EE_CHANGE_OWNERSHIP'; +exports[32] = 'EE_CHANGE_PERMISSIONS'; +exports[33] = 'EE_CANT_SEEK'; +exports[34] = 'EE_CAPACITY_EXCEEDED'; +exports[120] = 'HA_ERR_KEY_NOT_FOUND'; +exports[121] = 'HA_ERR_FOUND_DUPP_KEY'; +exports[122] = 'HA_ERR_INTERNAL_ERROR'; +exports[123] = 'HA_ERR_RECORD_CHANGED'; +exports[124] = 'HA_ERR_WRONG_INDEX'; +exports[126] = 'HA_ERR_CRASHED'; +exports[127] = 'HA_ERR_WRONG_IN_RECORD'; +exports[128] = 'HA_ERR_OUT_OF_MEM'; +exports[130] = 'HA_ERR_NOT_A_TABLE'; +exports[131] = 'HA_ERR_WRONG_COMMAND'; +exports[132] = 'HA_ERR_OLD_FILE'; +exports[133] = 'HA_ERR_NO_ACTIVE_RECORD'; +exports[134] = 'HA_ERR_RECORD_DELETED'; +exports[135] = 'HA_ERR_RECORD_FILE_FULL'; +exports[136] = 'HA_ERR_INDEX_FILE_FULL'; +exports[137] = 'HA_ERR_END_OF_FILE'; +exports[138] = 'HA_ERR_UNSUPPORTED'; +exports[139] = 'HA_ERR_TOO_BIG_ROW'; +exports[140] = 'HA_WRONG_CREATE_OPTION'; +exports[141] = 'HA_ERR_FOUND_DUPP_UNIQUE'; +exports[142] = 'HA_ERR_UNKNOWN_CHARSET'; +exports[143] = 'HA_ERR_WRONG_MRG_TABLE_DEF'; +exports[144] = 'HA_ERR_CRASHED_ON_REPAIR'; +exports[145] = 'HA_ERR_CRASHED_ON_USAGE'; +exports[146] = 'HA_ERR_LOCK_WAIT_TIMEOUT'; +exports[147] = 'HA_ERR_LOCK_TABLE_FULL'; +exports[148] = 'HA_ERR_READ_ONLY_TRANSACTION'; +exports[149] = 'HA_ERR_LOCK_DEADLOCK'; +exports[150] = 'HA_ERR_CANNOT_ADD_FOREIGN'; +exports[151] = 'HA_ERR_NO_REFERENCED_ROW'; +exports[152] = 'HA_ERR_ROW_IS_REFERENCED'; +exports[153] = 'HA_ERR_NO_SAVEPOINT'; +exports[154] = 'HA_ERR_NON_UNIQUE_BLOCK_SIZE'; +exports[155] = 'HA_ERR_NO_SUCH_TABLE'; +exports[156] = 'HA_ERR_TABLE_EXIST'; +exports[157] = 'HA_ERR_NO_CONNECTION'; +exports[158] = 'HA_ERR_NULL_IN_SPATIAL'; +exports[159] = 'HA_ERR_TABLE_DEF_CHANGED'; +exports[160] = 'HA_ERR_NO_PARTITION_FOUND'; +exports[161] = 'HA_ERR_RBR_LOGGING_FAILED'; +exports[162] = 'HA_ERR_DROP_INDEX_FK'; +exports[163] = 'HA_ERR_FOREIGN_DUPLICATE_KEY'; +exports[164] = 'HA_ERR_TABLE_NEEDS_UPGRADE'; +exports[165] = 'HA_ERR_TABLE_READONLY'; +exports[166] = 'HA_ERR_AUTOINC_READ_FAILED'; +exports[167] = 'HA_ERR_AUTOINC_ERANGE'; +exports[168] = 'HA_ERR_GENERIC'; +exports[169] = 'HA_ERR_RECORD_IS_THE_SAME'; +exports[170] = 'HA_ERR_LOGGING_IMPOSSIBLE'; +exports[171] = 'HA_ERR_CORRUPT_EVENT'; +exports[172] = 'HA_ERR_NEW_FILE'; +exports[173] = 'HA_ERR_ROWS_EVENT_APPLY'; +exports[174] = 'HA_ERR_INITIALIZATION'; +exports[175] = 'HA_ERR_FILE_TOO_SHORT'; +exports[176] = 'HA_ERR_WRONG_CRC'; +exports[177] = 'HA_ERR_TOO_MANY_CONCURRENT_TRXS'; +exports[178] = 'HA_ERR_NOT_IN_LOCK_PARTITIONS'; +exports[179] = 'HA_ERR_INDEX_COL_TOO_LONG'; +exports[180] = 'HA_ERR_INDEX_CORRUPT'; +exports[181] = 'HA_ERR_UNDO_REC_TOO_BIG'; +exports[182] = 'HA_FTS_INVALID_DOCID'; +exports[183] = 'HA_ERR_TABLE_IN_FK_CHECK'; +exports[184] = 'HA_ERR_TABLESPACE_EXISTS'; +exports[185] = 'HA_ERR_TOO_MANY_FIELDS'; +exports[186] = 'HA_ERR_ROW_IN_WRONG_PARTITION'; +exports[187] = 'HA_ERR_INNODB_READ_ONLY'; +exports[188] = 'HA_ERR_FTS_EXCEED_RESULT_CACHE_LIMIT'; +exports[189] = 'HA_ERR_TEMP_FILE_WRITE_FAILURE'; +exports[190] = 'HA_ERR_INNODB_FORCED_RECOVERY'; +exports[191] = 'HA_ERR_FTS_TOO_MANY_WORDS_IN_PHRASE'; +exports[192] = 'HA_ERR_FK_DEPTH_EXCEEDED'; +exports[193] = 'HA_MISSING_CREATE_OPTION'; +exports[194] = 'HA_ERR_SE_OUT_OF_MEMORY'; +exports[195] = 'HA_ERR_TABLE_CORRUPT'; +exports[196] = 'HA_ERR_QUERY_INTERRUPTED'; +exports[197] = 'HA_ERR_TABLESPACE_MISSING'; +exports[198] = 'HA_ERR_TABLESPACE_IS_NOT_EMPTY'; +exports[199] = 'HA_ERR_WRONG_FILE_NAME'; +exports[200] = 'HA_ERR_NOT_ALLOWED_COMMAND'; +exports[201] = 'HA_ERR_COMPUTE_FAILED'; +exports[1000] = 'ER_HASHCHK'; +exports[1001] = 'ER_NISAMCHK'; +exports[1002] = 'ER_NO'; +exports[1003] = 'ER_YES'; +exports[1004] = 'ER_CANT_CREATE_FILE'; +exports[1005] = 'ER_CANT_CREATE_TABLE'; +exports[1006] = 'ER_CANT_CREATE_DB'; +exports[1007] = 'ER_DB_CREATE_EXISTS'; +exports[1008] = 'ER_DB_DROP_EXISTS'; +exports[1009] = 'ER_DB_DROP_DELETE'; +exports[1010] = 'ER_DB_DROP_RMDIR'; +exports[1011] = 'ER_CANT_DELETE_FILE'; +exports[1012] = 'ER_CANT_FIND_SYSTEM_REC'; +exports[1013] = 'ER_CANT_GET_STAT'; +exports[1014] = 'ER_CANT_GET_WD'; +exports[1015] = 'ER_CANT_LOCK'; +exports[1016] = 'ER_CANT_OPEN_FILE'; +exports[1017] = 'ER_FILE_NOT_FOUND'; +exports[1018] = 'ER_CANT_READ_DIR'; +exports[1019] = 'ER_CANT_SET_WD'; +exports[1020] = 'ER_CHECKREAD'; +exports[1021] = 'ER_DISK_FULL'; +exports[1022] = 'ER_DUP_KEY'; +exports[1023] = 'ER_ERROR_ON_CLOSE'; +exports[1024] = 'ER_ERROR_ON_READ'; +exports[1025] = 'ER_ERROR_ON_RENAME'; +exports[1026] = 'ER_ERROR_ON_WRITE'; +exports[1027] = 'ER_FILE_USED'; +exports[1028] = 'ER_FILSORT_ABORT'; +exports[1029] = 'ER_FORM_NOT_FOUND'; +exports[1030] = 'ER_GET_ERRNO'; +exports[1031] = 'ER_ILLEGAL_HA'; +exports[1032] = 'ER_KEY_NOT_FOUND'; +exports[1033] = 'ER_NOT_FORM_FILE'; +exports[1034] = 'ER_NOT_KEYFILE'; +exports[1035] = 'ER_OLD_KEYFILE'; +exports[1036] = 'ER_OPEN_AS_READONLY'; +exports[1037] = 'ER_OUTOFMEMORY'; +exports[1038] = 'ER_OUT_OF_SORTMEMORY'; +exports[1039] = 'ER_UNEXPECTED_EOF'; +exports[1040] = 'ER_CON_COUNT_ERROR'; +exports[1041] = 'ER_OUT_OF_RESOURCES'; +exports[1042] = 'ER_BAD_HOST_ERROR'; +exports[1043] = 'ER_HANDSHAKE_ERROR'; +exports[1044] = 'ER_DBACCESS_DENIED_ERROR'; +exports[1045] = 'ER_ACCESS_DENIED_ERROR'; +exports[1046] = 'ER_NO_DB_ERROR'; +exports[1047] = 'ER_UNKNOWN_COM_ERROR'; +exports[1048] = 'ER_BAD_NULL_ERROR'; +exports[1049] = 'ER_BAD_DB_ERROR'; +exports[1050] = 'ER_TABLE_EXISTS_ERROR'; +exports[1051] = 'ER_BAD_TABLE_ERROR'; +exports[1052] = 'ER_NON_UNIQ_ERROR'; +exports[1053] = 'ER_SERVER_SHUTDOWN'; +exports[1054] = 'ER_BAD_FIELD_ERROR'; +exports[1055] = 'ER_WRONG_FIELD_WITH_GROUP'; +exports[1056] = 'ER_WRONG_GROUP_FIELD'; +exports[1057] = 'ER_WRONG_SUM_SELECT'; +exports[1058] = 'ER_WRONG_VALUE_COUNT'; +exports[1059] = 'ER_TOO_LONG_IDENT'; +exports[1060] = 'ER_DUP_FIELDNAME'; +exports[1061] = 'ER_DUP_KEYNAME'; +exports[1062] = 'ER_DUP_ENTRY'; +exports[1063] = 'ER_WRONG_FIELD_SPEC'; +exports[1064] = 'ER_PARSE_ERROR'; +exports[1065] = 'ER_EMPTY_QUERY'; +exports[1066] = 'ER_NONUNIQ_TABLE'; +exports[1067] = 'ER_INVALID_DEFAULT'; +exports[1068] = 'ER_MULTIPLE_PRI_KEY'; +exports[1069] = 'ER_TOO_MANY_KEYS'; +exports[1070] = 'ER_TOO_MANY_KEY_PARTS'; +exports[1071] = 'ER_TOO_LONG_KEY'; +exports[1072] = 'ER_KEY_COLUMN_DOES_NOT_EXITS'; +exports[1073] = 'ER_BLOB_USED_AS_KEY'; +exports[1074] = 'ER_TOO_BIG_FIELDLENGTH'; +exports[1075] = 'ER_WRONG_AUTO_KEY'; +exports[1076] = 'ER_READY'; +exports[1077] = 'ER_NORMAL_SHUTDOWN'; +exports[1078] = 'ER_GOT_SIGNAL'; +exports[1079] = 'ER_SHUTDOWN_COMPLETE'; +exports[1080] = 'ER_FORCING_CLOSE'; +exports[1081] = 'ER_IPSOCK_ERROR'; +exports[1082] = 'ER_NO_SUCH_INDEX'; +exports[1083] = 'ER_WRONG_FIELD_TERMINATORS'; +exports[1084] = 'ER_BLOBS_AND_NO_TERMINATED'; +exports[1085] = 'ER_TEXTFILE_NOT_READABLE'; +exports[1086] = 'ER_FILE_EXISTS_ERROR'; +exports[1087] = 'ER_LOAD_INFO'; +exports[1088] = 'ER_ALTER_INFO'; +exports[1089] = 'ER_WRONG_SUB_KEY'; +exports[1090] = 'ER_CANT_REMOVE_ALL_FIELDS'; +exports[1091] = 'ER_CANT_DROP_FIELD_OR_KEY'; +exports[1092] = 'ER_INSERT_INFO'; +exports[1093] = 'ER_UPDATE_TABLE_USED'; +exports[1094] = 'ER_NO_SUCH_THREAD'; +exports[1095] = 'ER_KILL_DENIED_ERROR'; +exports[1096] = 'ER_NO_TABLES_USED'; +exports[1097] = 'ER_TOO_BIG_SET'; +exports[1098] = 'ER_NO_UNIQUE_LOGFILE'; +exports[1099] = 'ER_TABLE_NOT_LOCKED_FOR_WRITE'; +exports[1100] = 'ER_TABLE_NOT_LOCKED'; +exports[1101] = 'ER_BLOB_CANT_HAVE_DEFAULT'; +exports[1102] = 'ER_WRONG_DB_NAME'; +exports[1103] = 'ER_WRONG_TABLE_NAME'; +exports[1104] = 'ER_TOO_BIG_SELECT'; +exports[1105] = 'ER_UNKNOWN_ERROR'; +exports[1106] = 'ER_UNKNOWN_PROCEDURE'; +exports[1107] = 'ER_WRONG_PARAMCOUNT_TO_PROCEDURE'; +exports[1108] = 'ER_WRONG_PARAMETERS_TO_PROCEDURE'; +exports[1109] = 'ER_UNKNOWN_TABLE'; +exports[1110] = 'ER_FIELD_SPECIFIED_TWICE'; +exports[1111] = 'ER_INVALID_GROUP_FUNC_USE'; +exports[1112] = 'ER_UNSUPPORTED_EXTENSION'; +exports[1113] = 'ER_TABLE_MUST_HAVE_COLUMNS'; +exports[1114] = 'ER_RECORD_FILE_FULL'; +exports[1115] = 'ER_UNKNOWN_CHARACTER_SET'; +exports[1116] = 'ER_TOO_MANY_TABLES'; +exports[1117] = 'ER_TOO_MANY_FIELDS'; +exports[1118] = 'ER_TOO_BIG_ROWSIZE'; +exports[1119] = 'ER_STACK_OVERRUN'; +exports[1120] = 'ER_WRONG_OUTER_JOIN'; +exports[1121] = 'ER_NULL_COLUMN_IN_INDEX'; +exports[1122] = 'ER_CANT_FIND_UDF'; +exports[1123] = 'ER_CANT_INITIALIZE_UDF'; +exports[1124] = 'ER_UDF_NO_PATHS'; +exports[1125] = 'ER_UDF_EXISTS'; +exports[1126] = 'ER_CANT_OPEN_LIBRARY'; +exports[1127] = 'ER_CANT_FIND_DL_ENTRY'; +exports[1128] = 'ER_FUNCTION_NOT_DEFINED'; +exports[1129] = 'ER_HOST_IS_BLOCKED'; +exports[1130] = 'ER_HOST_NOT_PRIVILEGED'; +exports[1131] = 'ER_PASSWORD_ANONYMOUS_USER'; +exports[1132] = 'ER_PASSWORD_NOT_ALLOWED'; +exports[1133] = 'ER_PASSWORD_NO_MATCH'; +exports[1134] = 'ER_UPDATE_INFO'; +exports[1135] = 'ER_CANT_CREATE_THREAD'; +exports[1136] = 'ER_WRONG_VALUE_COUNT_ON_ROW'; +exports[1137] = 'ER_CANT_REOPEN_TABLE'; +exports[1138] = 'ER_INVALID_USE_OF_NULL'; +exports[1139] = 'ER_REGEXP_ERROR'; +exports[1140] = 'ER_MIX_OF_GROUP_FUNC_AND_FIELDS'; +exports[1141] = 'ER_NONEXISTING_GRANT'; +exports[1142] = 'ER_TABLEACCESS_DENIED_ERROR'; +exports[1143] = 'ER_COLUMNACCESS_DENIED_ERROR'; +exports[1144] = 'ER_ILLEGAL_GRANT_FOR_TABLE'; +exports[1145] = 'ER_GRANT_WRONG_HOST_OR_USER'; +exports[1146] = 'ER_NO_SUCH_TABLE'; +exports[1147] = 'ER_NONEXISTING_TABLE_GRANT'; +exports[1148] = 'ER_NOT_ALLOWED_COMMAND'; +exports[1149] = 'ER_SYNTAX_ERROR'; +exports[1150] = 'ER_DELAYED_CANT_CHANGE_LOCK'; +exports[1151] = 'ER_TOO_MANY_DELAYED_THREADS'; +exports[1152] = 'ER_ABORTING_CONNECTION'; +exports[1153] = 'ER_NET_PACKET_TOO_LARGE'; +exports[1154] = 'ER_NET_READ_ERROR_FROM_PIPE'; +exports[1155] = 'ER_NET_FCNTL_ERROR'; +exports[1156] = 'ER_NET_PACKETS_OUT_OF_ORDER'; +exports[1157] = 'ER_NET_UNCOMPRESS_ERROR'; +exports[1158] = 'ER_NET_READ_ERROR'; +exports[1159] = 'ER_NET_READ_INTERRUPTED'; +exports[1160] = 'ER_NET_ERROR_ON_WRITE'; +exports[1161] = 'ER_NET_WRITE_INTERRUPTED'; +exports[1162] = 'ER_TOO_LONG_STRING'; +exports[1163] = 'ER_TABLE_CANT_HANDLE_BLOB'; +exports[1164] = 'ER_TABLE_CANT_HANDLE_AUTO_INCREMENT'; +exports[1165] = 'ER_DELAYED_INSERT_TABLE_LOCKED'; +exports[1166] = 'ER_WRONG_COLUMN_NAME'; +exports[1167] = 'ER_WRONG_KEY_COLUMN'; +exports[1168] = 'ER_WRONG_MRG_TABLE'; +exports[1169] = 'ER_DUP_UNIQUE'; +exports[1170] = 'ER_BLOB_KEY_WITHOUT_LENGTH'; +exports[1171] = 'ER_PRIMARY_CANT_HAVE_NULL'; +exports[1172] = 'ER_TOO_MANY_ROWS'; +exports[1173] = 'ER_REQUIRES_PRIMARY_KEY'; +exports[1174] = 'ER_NO_RAID_COMPILED'; +exports[1175] = 'ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE'; +exports[1176] = 'ER_KEY_DOES_NOT_EXITS'; +exports[1177] = 'ER_CHECK_NO_SUCH_TABLE'; +exports[1178] = 'ER_CHECK_NOT_IMPLEMENTED'; +exports[1179] = 'ER_CANT_DO_THIS_DURING_AN_TRANSACTION'; +exports[1180] = 'ER_ERROR_DURING_COMMIT'; +exports[1181] = 'ER_ERROR_DURING_ROLLBACK'; +exports[1182] = 'ER_ERROR_DURING_FLUSH_LOGS'; +exports[1183] = 'ER_ERROR_DURING_CHECKPOINT'; +exports[1184] = 'ER_NEW_ABORTING_CONNECTION'; +exports[1185] = 'ER_DUMP_NOT_IMPLEMENTED'; +exports[1186] = 'ER_FLUSH_MASTER_BINLOG_CLOSED'; +exports[1187] = 'ER_INDEX_REBUILD'; +exports[1188] = 'ER_MASTER'; +exports[1189] = 'ER_MASTER_NET_READ'; +exports[1190] = 'ER_MASTER_NET_WRITE'; +exports[1191] = 'ER_FT_MATCHING_KEY_NOT_FOUND'; +exports[1192] = 'ER_LOCK_OR_ACTIVE_TRANSACTION'; +exports[1193] = 'ER_UNKNOWN_SYSTEM_VARIABLE'; +exports[1194] = 'ER_CRASHED_ON_USAGE'; +exports[1195] = 'ER_CRASHED_ON_REPAIR'; +exports[1196] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK'; +exports[1197] = 'ER_TRANS_CACHE_FULL'; +exports[1198] = 'ER_SLAVE_MUST_STOP'; +exports[1199] = 'ER_SLAVE_NOT_RUNNING'; +exports[1200] = 'ER_BAD_SLAVE'; +exports[1201] = 'ER_MASTER_INFO'; +exports[1202] = 'ER_SLAVE_THREAD'; +exports[1203] = 'ER_TOO_MANY_USER_CONNECTIONS'; +exports[1204] = 'ER_SET_CONSTANTS_ONLY'; +exports[1205] = 'ER_LOCK_WAIT_TIMEOUT'; +exports[1206] = 'ER_LOCK_TABLE_FULL'; +exports[1207] = 'ER_READ_ONLY_TRANSACTION'; +exports[1208] = 'ER_DROP_DB_WITH_READ_LOCK'; +exports[1209] = 'ER_CREATE_DB_WITH_READ_LOCK'; +exports[1210] = 'ER_WRONG_ARGUMENTS'; +exports[1211] = 'ER_NO_PERMISSION_TO_CREATE_USER'; +exports[1212] = 'ER_UNION_TABLES_IN_DIFFERENT_DIR'; +exports[1213] = 'ER_LOCK_DEADLOCK'; +exports[1214] = 'ER_TABLE_CANT_HANDLE_FT'; +exports[1215] = 'ER_CANNOT_ADD_FOREIGN'; +exports[1216] = 'ER_NO_REFERENCED_ROW'; +exports[1217] = 'ER_ROW_IS_REFERENCED'; +exports[1218] = 'ER_CONNECT_TO_MASTER'; +exports[1219] = 'ER_QUERY_ON_MASTER'; +exports[1220] = 'ER_ERROR_WHEN_EXECUTING_COMMAND'; +exports[1221] = 'ER_WRONG_USAGE'; +exports[1222] = 'ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT'; +exports[1223] = 'ER_CANT_UPDATE_WITH_READLOCK'; +exports[1224] = 'ER_MIXING_NOT_ALLOWED'; +exports[1225] = 'ER_DUP_ARGUMENT'; +exports[1226] = 'ER_USER_LIMIT_REACHED'; +exports[1227] = 'ER_SPECIFIC_ACCESS_DENIED_ERROR'; +exports[1228] = 'ER_LOCAL_VARIABLE'; +exports[1229] = 'ER_GLOBAL_VARIABLE'; +exports[1230] = 'ER_NO_DEFAULT'; +exports[1231] = 'ER_WRONG_VALUE_FOR_VAR'; +exports[1232] = 'ER_WRONG_TYPE_FOR_VAR'; +exports[1233] = 'ER_VAR_CANT_BE_READ'; +exports[1234] = 'ER_CANT_USE_OPTION_HERE'; +exports[1235] = 'ER_NOT_SUPPORTED_YET'; +exports[1236] = 'ER_MASTER_FATAL_ERROR_READING_BINLOG'; +exports[1237] = 'ER_SLAVE_IGNORED_TABLE'; +exports[1238] = 'ER_INCORRECT_GLOBAL_LOCAL_VAR'; +exports[1239] = 'ER_WRONG_FK_DEF'; +exports[1240] = 'ER_KEY_REF_DO_NOT_MATCH_TABLE_REF'; +exports[1241] = 'ER_OPERAND_COLUMNS'; +exports[1242] = 'ER_SUBQUERY_NO_1_ROW'; +exports[1243] = 'ER_UNKNOWN_STMT_HANDLER'; +exports[1244] = 'ER_CORRUPT_HELP_DB'; +exports[1245] = 'ER_CYCLIC_REFERENCE'; +exports[1246] = 'ER_AUTO_CONVERT'; +exports[1247] = 'ER_ILLEGAL_REFERENCE'; +exports[1248] = 'ER_DERIVED_MUST_HAVE_ALIAS'; +exports[1249] = 'ER_SELECT_REDUCED'; +exports[1250] = 'ER_TABLENAME_NOT_ALLOWED_HERE'; +exports[1251] = 'ER_NOT_SUPPORTED_AUTH_MODE'; +exports[1252] = 'ER_SPATIAL_CANT_HAVE_NULL'; +exports[1253] = 'ER_COLLATION_CHARSET_MISMATCH'; +exports[1254] = 'ER_SLAVE_WAS_RUNNING'; +exports[1255] = 'ER_SLAVE_WAS_NOT_RUNNING'; +exports[1256] = 'ER_TOO_BIG_FOR_UNCOMPRESS'; +exports[1257] = 'ER_ZLIB_Z_MEM_ERROR'; +exports[1258] = 'ER_ZLIB_Z_BUF_ERROR'; +exports[1259] = 'ER_ZLIB_Z_DATA_ERROR'; +exports[1260] = 'ER_CUT_VALUE_GROUP_CONCAT'; +exports[1261] = 'ER_WARN_TOO_FEW_RECORDS'; +exports[1262] = 'ER_WARN_TOO_MANY_RECORDS'; +exports[1263] = 'ER_WARN_NULL_TO_NOTNULL'; +exports[1264] = 'ER_WARN_DATA_OUT_OF_RANGE'; +exports[1265] = 'WARN_DATA_TRUNCATED'; +exports[1266] = 'ER_WARN_USING_OTHER_HANDLER'; +exports[1267] = 'ER_CANT_AGGREGATE_2COLLATIONS'; +exports[1268] = 'ER_DROP_USER'; +exports[1269] = 'ER_REVOKE_GRANTS'; +exports[1270] = 'ER_CANT_AGGREGATE_3COLLATIONS'; +exports[1271] = 'ER_CANT_AGGREGATE_NCOLLATIONS'; +exports[1272] = 'ER_VARIABLE_IS_NOT_STRUCT'; +exports[1273] = 'ER_UNKNOWN_COLLATION'; +exports[1274] = 'ER_SLAVE_IGNORED_SSL_PARAMS'; +exports[1275] = 'ER_SERVER_IS_IN_SECURE_AUTH_MODE'; +exports[1276] = 'ER_WARN_FIELD_RESOLVED'; +exports[1277] = 'ER_BAD_SLAVE_UNTIL_COND'; +exports[1278] = 'ER_MISSING_SKIP_SLAVE'; +exports[1279] = 'ER_UNTIL_COND_IGNORED'; +exports[1280] = 'ER_WRONG_NAME_FOR_INDEX'; +exports[1281] = 'ER_WRONG_NAME_FOR_CATALOG'; +exports[1282] = 'ER_WARN_QC_RESIZE'; +exports[1283] = 'ER_BAD_FT_COLUMN'; +exports[1284] = 'ER_UNKNOWN_KEY_CACHE'; +exports[1285] = 'ER_WARN_HOSTNAME_WONT_WORK'; +exports[1286] = 'ER_UNKNOWN_STORAGE_ENGINE'; +exports[1287] = 'ER_WARN_DEPRECATED_SYNTAX'; +exports[1288] = 'ER_NON_UPDATABLE_TABLE'; +exports[1289] = 'ER_FEATURE_DISABLED'; +exports[1290] = 'ER_OPTION_PREVENTS_STATEMENT'; +exports[1291] = 'ER_DUPLICATED_VALUE_IN_TYPE'; +exports[1292] = 'ER_TRUNCATED_WRONG_VALUE'; +exports[1293] = 'ER_TOO_MUCH_AUTO_TIMESTAMP_COLS'; +exports[1294] = 'ER_INVALID_ON_UPDATE'; +exports[1295] = 'ER_UNSUPPORTED_PS'; +exports[1296] = 'ER_GET_ERRMSG'; +exports[1297] = 'ER_GET_TEMPORARY_ERRMSG'; +exports[1298] = 'ER_UNKNOWN_TIME_ZONE'; +exports[1299] = 'ER_WARN_INVALID_TIMESTAMP'; +exports[1300] = 'ER_INVALID_CHARACTER_STRING'; +exports[1301] = 'ER_WARN_ALLOWED_PACKET_OVERFLOWED'; +exports[1302] = 'ER_CONFLICTING_DECLARATIONS'; +exports[1303] = 'ER_SP_NO_RECURSIVE_CREATE'; +exports[1304] = 'ER_SP_ALREADY_EXISTS'; +exports[1305] = 'ER_SP_DOES_NOT_EXIST'; +exports[1306] = 'ER_SP_DROP_FAILED'; +exports[1307] = 'ER_SP_STORE_FAILED'; +exports[1308] = 'ER_SP_LILABEL_MISMATCH'; +exports[1309] = 'ER_SP_LABEL_REDEFINE'; +exports[1310] = 'ER_SP_LABEL_MISMATCH'; +exports[1311] = 'ER_SP_UNINIT_VAR'; +exports[1312] = 'ER_SP_BADSELECT'; +exports[1313] = 'ER_SP_BADRETURN'; +exports[1314] = 'ER_SP_BADSTATEMENT'; +exports[1315] = 'ER_UPDATE_LOG_DEPRECATED_IGNORED'; +exports[1316] = 'ER_UPDATE_LOG_DEPRECATED_TRANSLATED'; +exports[1317] = 'ER_QUERY_INTERRUPTED'; +exports[1318] = 'ER_SP_WRONG_NO_OF_ARGS'; +exports[1319] = 'ER_SP_COND_MISMATCH'; +exports[1320] = 'ER_SP_NORETURN'; +exports[1321] = 'ER_SP_NORETURNEND'; +exports[1322] = 'ER_SP_BAD_CURSOR_QUERY'; +exports[1323] = 'ER_SP_BAD_CURSOR_SELECT'; +exports[1324] = 'ER_SP_CURSOR_MISMATCH'; +exports[1325] = 'ER_SP_CURSOR_ALREADY_OPEN'; +exports[1326] = 'ER_SP_CURSOR_NOT_OPEN'; +exports[1327] = 'ER_SP_UNDECLARED_VAR'; +exports[1328] = 'ER_SP_WRONG_NO_OF_FETCH_ARGS'; +exports[1329] = 'ER_SP_FETCH_NO_DATA'; +exports[1330] = 'ER_SP_DUP_PARAM'; +exports[1331] = 'ER_SP_DUP_VAR'; +exports[1332] = 'ER_SP_DUP_COND'; +exports[1333] = 'ER_SP_DUP_CURS'; +exports[1334] = 'ER_SP_CANT_ALTER'; +exports[1335] = 'ER_SP_SUBSELECT_NYI'; +exports[1336] = 'ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG'; +exports[1337] = 'ER_SP_VARCOND_AFTER_CURSHNDLR'; +exports[1338] = 'ER_SP_CURSOR_AFTER_HANDLER'; +exports[1339] = 'ER_SP_CASE_NOT_FOUND'; +exports[1340] = 'ER_FPARSER_TOO_BIG_FILE'; +exports[1341] = 'ER_FPARSER_BAD_HEADER'; +exports[1342] = 'ER_FPARSER_EOF_IN_COMMENT'; +exports[1343] = 'ER_FPARSER_ERROR_IN_PARAMETER'; +exports[1344] = 'ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER'; +exports[1345] = 'ER_VIEW_NO_EXPLAIN'; +exports[1346] = 'ER_FRM_UNKNOWN_TYPE'; +exports[1347] = 'ER_WRONG_OBJECT'; +exports[1348] = 'ER_NONUPDATEABLE_COLUMN'; +exports[1349] = 'ER_VIEW_SELECT_DERIVED'; +exports[1350] = 'ER_VIEW_SELECT_CLAUSE'; +exports[1351] = 'ER_VIEW_SELECT_VARIABLE'; +exports[1352] = 'ER_VIEW_SELECT_TMPTABLE'; +exports[1353] = 'ER_VIEW_WRONG_LIST'; +exports[1354] = 'ER_WARN_VIEW_MERGE'; +exports[1355] = 'ER_WARN_VIEW_WITHOUT_KEY'; +exports[1356] = 'ER_VIEW_INVALID'; +exports[1357] = 'ER_SP_NO_DROP_SP'; +exports[1358] = 'ER_SP_GOTO_IN_HNDLR'; +exports[1359] = 'ER_TRG_ALREADY_EXISTS'; +exports[1360] = 'ER_TRG_DOES_NOT_EXIST'; +exports[1361] = 'ER_TRG_ON_VIEW_OR_TEMP_TABLE'; +exports[1362] = 'ER_TRG_CANT_CHANGE_ROW'; +exports[1363] = 'ER_TRG_NO_SUCH_ROW_IN_TRG'; +exports[1364] = 'ER_NO_DEFAULT_FOR_FIELD'; +exports[1365] = 'ER_DIVISION_BY_ZERO'; +exports[1366] = 'ER_TRUNCATED_WRONG_VALUE_FOR_FIELD'; +exports[1367] = 'ER_ILLEGAL_VALUE_FOR_TYPE'; +exports[1368] = 'ER_VIEW_NONUPD_CHECK'; +exports[1369] = 'ER_VIEW_CHECK_FAILED'; +exports[1370] = 'ER_PROCACCESS_DENIED_ERROR'; +exports[1371] = 'ER_RELAY_LOG_FAIL'; +exports[1372] = 'ER_PASSWD_LENGTH'; +exports[1373] = 'ER_UNKNOWN_TARGET_BINLOG'; +exports[1374] = 'ER_IO_ERR_LOG_INDEX_READ'; +exports[1375] = 'ER_BINLOG_PURGE_PROHIBITED'; +exports[1376] = 'ER_FSEEK_FAIL'; +exports[1377] = 'ER_BINLOG_PURGE_FATAL_ERR'; +exports[1378] = 'ER_LOG_IN_USE'; +exports[1379] = 'ER_LOG_PURGE_UNKNOWN_ERR'; +exports[1380] = 'ER_RELAY_LOG_INIT'; +exports[1381] = 'ER_NO_BINARY_LOGGING'; +exports[1382] = 'ER_RESERVED_SYNTAX'; +exports[1383] = 'ER_WSAS_FAILED'; +exports[1384] = 'ER_DIFF_GROUPS_PROC'; +exports[1385] = 'ER_NO_GROUP_FOR_PROC'; +exports[1386] = 'ER_ORDER_WITH_PROC'; +exports[1387] = 'ER_LOGGING_PROHIBIT_CHANGING_OF'; +exports[1388] = 'ER_NO_FILE_MAPPING'; +exports[1389] = 'ER_WRONG_MAGIC'; +exports[1390] = 'ER_PS_MANY_PARAM'; +exports[1391] = 'ER_KEY_PART_0'; +exports[1392] = 'ER_VIEW_CHECKSUM'; +exports[1393] = 'ER_VIEW_MULTIUPDATE'; +exports[1394] = 'ER_VIEW_NO_INSERT_FIELD_LIST'; +exports[1395] = 'ER_VIEW_DELETE_MERGE_VIEW'; +exports[1396] = 'ER_CANNOT_USER'; +exports[1397] = 'ER_XAER_NOTA'; +exports[1398] = 'ER_XAER_INVAL'; +exports[1399] = 'ER_XAER_RMFAIL'; +exports[1400] = 'ER_XAER_OUTSIDE'; +exports[1401] = 'ER_XAER_RMERR'; +exports[1402] = 'ER_XA_RBROLLBACK'; +exports[1403] = 'ER_NONEXISTING_PROC_GRANT'; +exports[1404] = 'ER_PROC_AUTO_GRANT_FAIL'; +exports[1405] = 'ER_PROC_AUTO_REVOKE_FAIL'; +exports[1406] = 'ER_DATA_TOO_LONG'; +exports[1407] = 'ER_SP_BAD_SQLSTATE'; +exports[1408] = 'ER_STARTUP'; +exports[1409] = 'ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR'; +exports[1410] = 'ER_CANT_CREATE_USER_WITH_GRANT'; +exports[1411] = 'ER_WRONG_VALUE_FOR_TYPE'; +exports[1412] = 'ER_TABLE_DEF_CHANGED'; +exports[1413] = 'ER_SP_DUP_HANDLER'; +exports[1414] = 'ER_SP_NOT_VAR_ARG'; +exports[1415] = 'ER_SP_NO_RETSET'; +exports[1416] = 'ER_CANT_CREATE_GEOMETRY_OBJECT'; +exports[1417] = 'ER_FAILED_ROUTINE_BREAK_BINLOG'; +exports[1418] = 'ER_BINLOG_UNSAFE_ROUTINE'; +exports[1419] = 'ER_BINLOG_CREATE_ROUTINE_NEED_SUPER'; +exports[1420] = 'ER_EXEC_STMT_WITH_OPEN_CURSOR'; +exports[1421] = 'ER_STMT_HAS_NO_OPEN_CURSOR'; +exports[1422] = 'ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG'; +exports[1423] = 'ER_NO_DEFAULT_FOR_VIEW_FIELD'; +exports[1424] = 'ER_SP_NO_RECURSION'; +exports[1425] = 'ER_TOO_BIG_SCALE'; +exports[1426] = 'ER_TOO_BIG_PRECISION'; +exports[1427] = 'ER_M_BIGGER_THAN_D'; +exports[1428] = 'ER_WRONG_LOCK_OF_SYSTEM_TABLE'; +exports[1429] = 'ER_CONNECT_TO_FOREIGN_DATA_SOURCE'; +exports[1430] = 'ER_QUERY_ON_FOREIGN_DATA_SOURCE'; +exports[1431] = 'ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST'; +exports[1432] = 'ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE'; +exports[1433] = 'ER_FOREIGN_DATA_STRING_INVALID'; +exports[1434] = 'ER_CANT_CREATE_FEDERATED_TABLE'; +exports[1435] = 'ER_TRG_IN_WRONG_SCHEMA'; +exports[1436] = 'ER_STACK_OVERRUN_NEED_MORE'; +exports[1437] = 'ER_TOO_LONG_BODY'; +exports[1438] = 'ER_WARN_CANT_DROP_DEFAULT_KEYCACHE'; +exports[1439] = 'ER_TOO_BIG_DISPLAYWIDTH'; +exports[1440] = 'ER_XAER_DUPID'; +exports[1441] = 'ER_DATETIME_FUNCTION_OVERFLOW'; +exports[1442] = 'ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG'; +exports[1443] = 'ER_VIEW_PREVENT_UPDATE'; +exports[1444] = 'ER_PS_NO_RECURSION'; +exports[1445] = 'ER_SP_CANT_SET_AUTOCOMMIT'; +exports[1446] = 'ER_MALFORMED_DEFINER'; +exports[1447] = 'ER_VIEW_FRM_NO_USER'; +exports[1448] = 'ER_VIEW_OTHER_USER'; +exports[1449] = 'ER_NO_SUCH_USER'; +exports[1450] = 'ER_FORBID_SCHEMA_CHANGE'; +exports[1451] = 'ER_ROW_IS_REFERENCED_2'; +exports[1452] = 'ER_NO_REFERENCED_ROW_2'; +exports[1453] = 'ER_SP_BAD_VAR_SHADOW'; +exports[1454] = 'ER_TRG_NO_DEFINER'; +exports[1455] = 'ER_OLD_FILE_FORMAT'; +exports[1456] = 'ER_SP_RECURSION_LIMIT'; +exports[1457] = 'ER_SP_PROC_TABLE_CORRUPT'; +exports[1458] = 'ER_SP_WRONG_NAME'; +exports[1459] = 'ER_TABLE_NEEDS_UPGRADE'; +exports[1460] = 'ER_SP_NO_AGGREGATE'; +exports[1461] = 'ER_MAX_PREPARED_STMT_COUNT_REACHED'; +exports[1462] = 'ER_VIEW_RECURSIVE'; +exports[1463] = 'ER_NON_GROUPING_FIELD_USED'; +exports[1464] = 'ER_TABLE_CANT_HANDLE_SPKEYS'; +exports[1465] = 'ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA'; +exports[1466] = 'ER_REMOVED_SPACES'; +exports[1467] = 'ER_AUTOINC_READ_FAILED'; +exports[1468] = 'ER_USERNAME'; +exports[1469] = 'ER_HOSTNAME'; +exports[1470] = 'ER_WRONG_STRING_LENGTH'; +exports[1471] = 'ER_NON_INSERTABLE_TABLE'; +exports[1472] = 'ER_ADMIN_WRONG_MRG_TABLE'; +exports[1473] = 'ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT'; +exports[1474] = 'ER_NAME_BECOMES_EMPTY'; +exports[1475] = 'ER_AMBIGUOUS_FIELD_TERM'; +exports[1476] = 'ER_FOREIGN_SERVER_EXISTS'; +exports[1477] = 'ER_FOREIGN_SERVER_DOESNT_EXIST'; +exports[1478] = 'ER_ILLEGAL_HA_CREATE_OPTION'; +exports[1479] = 'ER_PARTITION_REQUIRES_VALUES_ERROR'; +exports[1480] = 'ER_PARTITION_WRONG_VALUES_ERROR'; +exports[1481] = 'ER_PARTITION_MAXVALUE_ERROR'; +exports[1482] = 'ER_PARTITION_SUBPARTITION_ERROR'; +exports[1483] = 'ER_PARTITION_SUBPART_MIX_ERROR'; +exports[1484] = 'ER_PARTITION_WRONG_NO_PART_ERROR'; +exports[1485] = 'ER_PARTITION_WRONG_NO_SUBPART_ERROR'; +exports[1486] = 'ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR'; +exports[1487] = 'ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR'; +exports[1488] = 'ER_FIELD_NOT_FOUND_PART_ERROR'; +exports[1489] = 'ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR'; +exports[1490] = 'ER_INCONSISTENT_PARTITION_INFO_ERROR'; +exports[1491] = 'ER_PARTITION_FUNC_NOT_ALLOWED_ERROR'; +exports[1492] = 'ER_PARTITIONS_MUST_BE_DEFINED_ERROR'; +exports[1493] = 'ER_RANGE_NOT_INCREASING_ERROR'; +exports[1494] = 'ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR'; +exports[1495] = 'ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR'; +exports[1496] = 'ER_PARTITION_ENTRY_ERROR'; +exports[1497] = 'ER_MIX_HANDLER_ERROR'; +exports[1498] = 'ER_PARTITION_NOT_DEFINED_ERROR'; +exports[1499] = 'ER_TOO_MANY_PARTITIONS_ERROR'; +exports[1500] = 'ER_SUBPARTITION_ERROR'; +exports[1501] = 'ER_CANT_CREATE_HANDLER_FILE'; +exports[1502] = 'ER_BLOB_FIELD_IN_PART_FUNC_ERROR'; +exports[1503] = 'ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF'; +exports[1504] = 'ER_NO_PARTS_ERROR'; +exports[1505] = 'ER_PARTITION_MGMT_ON_NONPARTITIONED'; +exports[1506] = 'ER_FOREIGN_KEY_ON_PARTITIONED'; +exports[1507] = 'ER_DROP_PARTITION_NON_EXISTENT'; +exports[1508] = 'ER_DROP_LAST_PARTITION'; +exports[1509] = 'ER_COALESCE_ONLY_ON_HASH_PARTITION'; +exports[1510] = 'ER_REORG_HASH_ONLY_ON_SAME_NO'; +exports[1511] = 'ER_REORG_NO_PARAM_ERROR'; +exports[1512] = 'ER_ONLY_ON_RANGE_LIST_PARTITION'; +exports[1513] = 'ER_ADD_PARTITION_SUBPART_ERROR'; +exports[1514] = 'ER_ADD_PARTITION_NO_NEW_PARTITION'; +exports[1515] = 'ER_COALESCE_PARTITION_NO_PARTITION'; +exports[1516] = 'ER_REORG_PARTITION_NOT_EXIST'; +exports[1517] = 'ER_SAME_NAME_PARTITION'; +exports[1518] = 'ER_NO_BINLOG_ERROR'; +exports[1519] = 'ER_CONSECUTIVE_REORG_PARTITIONS'; +exports[1520] = 'ER_REORG_OUTSIDE_RANGE'; +exports[1521] = 'ER_PARTITION_FUNCTION_FAILURE'; +exports[1522] = 'ER_PART_STATE_ERROR'; +exports[1523] = 'ER_LIMITED_PART_RANGE'; +exports[1524] = 'ER_PLUGIN_IS_NOT_LOADED'; +exports[1525] = 'ER_WRONG_VALUE'; +exports[1526] = 'ER_NO_PARTITION_FOR_GIVEN_VALUE'; +exports[1527] = 'ER_FILEGROUP_OPTION_ONLY_ONCE'; +exports[1528] = 'ER_CREATE_FILEGROUP_FAILED'; +exports[1529] = 'ER_DROP_FILEGROUP_FAILED'; +exports[1530] = 'ER_TABLESPACE_AUTO_EXTEND_ERROR'; +exports[1531] = 'ER_WRONG_SIZE_NUMBER'; +exports[1532] = 'ER_SIZE_OVERFLOW_ERROR'; +exports[1533] = 'ER_ALTER_FILEGROUP_FAILED'; +exports[1534] = 'ER_BINLOG_ROW_LOGGING_FAILED'; +exports[1535] = 'ER_BINLOG_ROW_WRONG_TABLE_DEF'; +exports[1536] = 'ER_BINLOG_ROW_RBR_TO_SBR'; +exports[1537] = 'ER_EVENT_ALREADY_EXISTS'; +exports[1538] = 'ER_EVENT_STORE_FAILED'; +exports[1539] = 'ER_EVENT_DOES_NOT_EXIST'; +exports[1540] = 'ER_EVENT_CANT_ALTER'; +exports[1541] = 'ER_EVENT_DROP_FAILED'; +exports[1542] = 'ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG'; +exports[1543] = 'ER_EVENT_ENDS_BEFORE_STARTS'; +exports[1544] = 'ER_EVENT_EXEC_TIME_IN_THE_PAST'; +exports[1545] = 'ER_EVENT_OPEN_TABLE_FAILED'; +exports[1546] = 'ER_EVENT_NEITHER_M_EXPR_NOR_M_AT'; +exports[1547] = 'ER_COL_COUNT_DOESNT_MATCH_CORRUPTED'; +exports[1548] = 'ER_CANNOT_LOAD_FROM_TABLE'; +exports[1549] = 'ER_EVENT_CANNOT_DELETE'; +exports[1550] = 'ER_EVENT_COMPILE_ERROR'; +exports[1551] = 'ER_EVENT_SAME_NAME'; +exports[1552] = 'ER_EVENT_DATA_TOO_LONG'; +exports[1553] = 'ER_DROP_INDEX_FK'; +exports[1554] = 'ER_WARN_DEPRECATED_SYNTAX_WITH_VER'; +exports[1555] = 'ER_CANT_WRITE_LOCK_LOG_TABLE'; +exports[1556] = 'ER_CANT_LOCK_LOG_TABLE'; +exports[1557] = 'ER_FOREIGN_DUPLICATE_KEY'; +exports[1558] = 'ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE'; +exports[1559] = 'ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR'; +exports[1560] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT'; +exports[1561] = 'ER_NDB_CANT_SWITCH_BINLOG_FORMAT'; +exports[1562] = 'ER_PARTITION_NO_TEMPORARY'; +exports[1563] = 'ER_PARTITION_CONST_DOMAIN_ERROR'; +exports[1564] = 'ER_PARTITION_FUNCTION_IS_NOT_ALLOWED'; +exports[1565] = 'ER_DDL_LOG_ERROR'; +exports[1566] = 'ER_NULL_IN_VALUES_LESS_THAN'; +exports[1567] = 'ER_WRONG_PARTITION_NAME'; +exports[1568] = 'ER_CANT_CHANGE_TX_CHARACTERISTICS'; +exports[1569] = 'ER_DUP_ENTRY_AUTOINCREMENT_CASE'; +exports[1570] = 'ER_EVENT_MODIFY_QUEUE_ERROR'; +exports[1571] = 'ER_EVENT_SET_VAR_ERROR'; +exports[1572] = 'ER_PARTITION_MERGE_ERROR'; +exports[1573] = 'ER_CANT_ACTIVATE_LOG'; +exports[1574] = 'ER_RBR_NOT_AVAILABLE'; +exports[1575] = 'ER_BASE64_DECODE_ERROR'; +exports[1576] = 'ER_EVENT_RECURSION_FORBIDDEN'; +exports[1577] = 'ER_EVENTS_DB_ERROR'; +exports[1578] = 'ER_ONLY_INTEGERS_ALLOWED'; +exports[1579] = 'ER_UNSUPORTED_LOG_ENGINE'; +exports[1580] = 'ER_BAD_LOG_STATEMENT'; +exports[1581] = 'ER_CANT_RENAME_LOG_TABLE'; +exports[1582] = 'ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT'; +exports[1583] = 'ER_WRONG_PARAMETERS_TO_NATIVE_FCT'; +exports[1584] = 'ER_WRONG_PARAMETERS_TO_STORED_FCT'; +exports[1585] = 'ER_NATIVE_FCT_NAME_COLLISION'; +exports[1586] = 'ER_DUP_ENTRY_WITH_KEY_NAME'; +exports[1587] = 'ER_BINLOG_PURGE_EMFILE'; +exports[1588] = 'ER_EVENT_CANNOT_CREATE_IN_THE_PAST'; +exports[1589] = 'ER_EVENT_CANNOT_ALTER_IN_THE_PAST'; +exports[1590] = 'ER_SLAVE_INCIDENT'; +exports[1591] = 'ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT'; +exports[1592] = 'ER_BINLOG_UNSAFE_STATEMENT'; +exports[1593] = 'ER_SLAVE_FATAL_ERROR'; +exports[1594] = 'ER_SLAVE_RELAY_LOG_READ_FAILURE'; +exports[1595] = 'ER_SLAVE_RELAY_LOG_WRITE_FAILURE'; +exports[1596] = 'ER_SLAVE_CREATE_EVENT_FAILURE'; +exports[1597] = 'ER_SLAVE_MASTER_COM_FAILURE'; +exports[1598] = 'ER_BINLOG_LOGGING_IMPOSSIBLE'; +exports[1599] = 'ER_VIEW_NO_CREATION_CTX'; +exports[1600] = 'ER_VIEW_INVALID_CREATION_CTX'; +exports[1601] = 'ER_SR_INVALID_CREATION_CTX'; +exports[1602] = 'ER_TRG_CORRUPTED_FILE'; +exports[1603] = 'ER_TRG_NO_CREATION_CTX'; +exports[1604] = 'ER_TRG_INVALID_CREATION_CTX'; +exports[1605] = 'ER_EVENT_INVALID_CREATION_CTX'; +exports[1606] = 'ER_TRG_CANT_OPEN_TABLE'; +exports[1607] = 'ER_CANT_CREATE_SROUTINE'; +exports[1608] = 'ER_NEVER_USED'; +exports[1609] = 'ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT'; +exports[1610] = 'ER_SLAVE_CORRUPT_EVENT'; +exports[1611] = 'ER_LOAD_DATA_INVALID_COLUMN'; +exports[1612] = 'ER_LOG_PURGE_NO_FILE'; +exports[1613] = 'ER_XA_RBTIMEOUT'; +exports[1614] = 'ER_XA_RBDEADLOCK'; +exports[1615] = 'ER_NEED_REPREPARE'; +exports[1616] = 'ER_DELAYED_NOT_SUPPORTED'; +exports[1617] = 'WARN_NO_MASTER_INFO'; +exports[1618] = 'WARN_OPTION_IGNORED'; +exports[1619] = 'ER_PLUGIN_DELETE_BUILTIN'; +exports[1620] = 'WARN_PLUGIN_BUSY'; +exports[1621] = 'ER_VARIABLE_IS_READONLY'; +exports[1622] = 'ER_WARN_ENGINE_TRANSACTION_ROLLBACK'; +exports[1623] = 'ER_SLAVE_HEARTBEAT_FAILURE'; +exports[1624] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE'; +exports[1625] = 'ER_NDB_REPLICATION_SCHEMA_ERROR'; +exports[1626] = 'ER_CONFLICT_FN_PARSE_ERROR'; +exports[1627] = 'ER_EXCEPTIONS_WRITE_ERROR'; +exports[1628] = 'ER_TOO_LONG_TABLE_COMMENT'; +exports[1629] = 'ER_TOO_LONG_FIELD_COMMENT'; +exports[1630] = 'ER_FUNC_INEXISTENT_NAME_COLLISION'; +exports[1631] = 'ER_DATABASE_NAME'; +exports[1632] = 'ER_TABLE_NAME'; +exports[1633] = 'ER_PARTITION_NAME'; +exports[1634] = 'ER_SUBPARTITION_NAME'; +exports[1635] = 'ER_TEMPORARY_NAME'; +exports[1636] = 'ER_RENAMED_NAME'; +exports[1637] = 'ER_TOO_MANY_CONCURRENT_TRXS'; +exports[1638] = 'WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED'; +exports[1639] = 'ER_DEBUG_SYNC_TIMEOUT'; +exports[1640] = 'ER_DEBUG_SYNC_HIT_LIMIT'; +exports[1641] = 'ER_DUP_SIGNAL_SET'; +exports[1642] = 'ER_SIGNAL_WARN'; +exports[1643] = 'ER_SIGNAL_NOT_FOUND'; +exports[1644] = 'ER_SIGNAL_EXCEPTION'; +exports[1645] = 'ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER'; +exports[1646] = 'ER_SIGNAL_BAD_CONDITION_TYPE'; +exports[1647] = 'WARN_COND_ITEM_TRUNCATED'; +exports[1648] = 'ER_COND_ITEM_TOO_LONG'; +exports[1649] = 'ER_UNKNOWN_LOCALE'; +exports[1650] = 'ER_SLAVE_IGNORE_SERVER_IDS'; +exports[1651] = 'ER_QUERY_CACHE_DISABLED'; +exports[1652] = 'ER_SAME_NAME_PARTITION_FIELD'; +exports[1653] = 'ER_PARTITION_COLUMN_LIST_ERROR'; +exports[1654] = 'ER_WRONG_TYPE_COLUMN_VALUE_ERROR'; +exports[1655] = 'ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR'; +exports[1656] = 'ER_MAXVALUE_IN_VALUES_IN'; +exports[1657] = 'ER_TOO_MANY_VALUES_ERROR'; +exports[1658] = 'ER_ROW_SINGLE_PARTITION_FIELD_ERROR'; +exports[1659] = 'ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD'; +exports[1660] = 'ER_PARTITION_FIELDS_TOO_LONG'; +exports[1661] = 'ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE'; +exports[1662] = 'ER_BINLOG_ROW_MODE_AND_STMT_ENGINE'; +exports[1663] = 'ER_BINLOG_UNSAFE_AND_STMT_ENGINE'; +exports[1664] = 'ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE'; +exports[1665] = 'ER_BINLOG_STMT_MODE_AND_ROW_ENGINE'; +exports[1666] = 'ER_BINLOG_ROW_INJECTION_AND_STMT_MODE'; +exports[1667] = 'ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE'; +exports[1668] = 'ER_BINLOG_UNSAFE_LIMIT'; +exports[1669] = 'ER_BINLOG_UNSAFE_INSERT_DELAYED'; +exports[1670] = 'ER_BINLOG_UNSAFE_SYSTEM_TABLE'; +exports[1671] = 'ER_BINLOG_UNSAFE_AUTOINC_COLUMNS'; +exports[1672] = 'ER_BINLOG_UNSAFE_UDF'; +exports[1673] = 'ER_BINLOG_UNSAFE_SYSTEM_VARIABLE'; +exports[1674] = 'ER_BINLOG_UNSAFE_SYSTEM_FUNCTION'; +exports[1675] = 'ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS'; +exports[1676] = 'ER_MESSAGE_AND_STATEMENT'; +exports[1677] = 'ER_SLAVE_CONVERSION_FAILED'; +exports[1678] = 'ER_SLAVE_CANT_CREATE_CONVERSION'; +exports[1679] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT'; +exports[1680] = 'ER_PATH_LENGTH'; +exports[1681] = 'ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT'; +exports[1682] = 'ER_WRONG_NATIVE_TABLE_STRUCTURE'; +exports[1683] = 'ER_WRONG_PERFSCHEMA_USAGE'; +exports[1684] = 'ER_WARN_I_S_SKIPPED_TABLE'; +exports[1685] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT'; +exports[1686] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT'; +exports[1687] = 'ER_SPATIAL_MUST_HAVE_GEOM_COL'; +exports[1688] = 'ER_TOO_LONG_INDEX_COMMENT'; +exports[1689] = 'ER_LOCK_ABORTED'; +exports[1690] = 'ER_DATA_OUT_OF_RANGE'; +exports[1691] = 'ER_WRONG_SPVAR_TYPE_IN_LIMIT'; +exports[1692] = 'ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE'; +exports[1693] = 'ER_BINLOG_UNSAFE_MIXED_STATEMENT'; +exports[1694] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN'; +exports[1695] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN'; +exports[1696] = 'ER_FAILED_READ_FROM_PAR_FILE'; +exports[1697] = 'ER_VALUES_IS_NOT_INT_TYPE_ERROR'; +exports[1698] = 'ER_ACCESS_DENIED_NO_PASSWORD_ERROR'; +exports[1699] = 'ER_SET_PASSWORD_AUTH_PLUGIN'; +exports[1700] = 'ER_GRANT_PLUGIN_USER_EXISTS'; +exports[1701] = 'ER_TRUNCATE_ILLEGAL_FK'; +exports[1702] = 'ER_PLUGIN_IS_PERMANENT'; +exports[1703] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN'; +exports[1704] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX'; +exports[1705] = 'ER_STMT_CACHE_FULL'; +exports[1706] = 'ER_MULTI_UPDATE_KEY_CONFLICT'; +exports[1707] = 'ER_TABLE_NEEDS_REBUILD'; +exports[1708] = 'WARN_OPTION_BELOW_LIMIT'; +exports[1709] = 'ER_INDEX_COLUMN_TOO_LONG'; +exports[1710] = 'ER_ERROR_IN_TRIGGER_BODY'; +exports[1711] = 'ER_ERROR_IN_UNKNOWN_TRIGGER_BODY'; +exports[1712] = 'ER_INDEX_CORRUPT'; +exports[1713] = 'ER_UNDO_RECORD_TOO_BIG'; +exports[1714] = 'ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT'; +exports[1715] = 'ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE'; +exports[1716] = 'ER_BINLOG_UNSAFE_REPLACE_SELECT'; +exports[1717] = 'ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT'; +exports[1718] = 'ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT'; +exports[1719] = 'ER_BINLOG_UNSAFE_UPDATE_IGNORE'; +exports[1720] = 'ER_PLUGIN_NO_UNINSTALL'; +exports[1721] = 'ER_PLUGIN_NO_INSTALL'; +exports[1722] = 'ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT'; +exports[1723] = 'ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC'; +exports[1724] = 'ER_BINLOG_UNSAFE_INSERT_TWO_KEYS'; +exports[1725] = 'ER_TABLE_IN_FK_CHECK'; +exports[1726] = 'ER_UNSUPPORTED_ENGINE'; +exports[1727] = 'ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST'; +exports[1728] = 'ER_CANNOT_LOAD_FROM_TABLE_V2'; +exports[1729] = 'ER_MASTER_DELAY_VALUE_OUT_OF_RANGE'; +exports[1730] = 'ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT'; +exports[1731] = 'ER_PARTITION_EXCHANGE_DIFFERENT_OPTION'; +exports[1732] = 'ER_PARTITION_EXCHANGE_PART_TABLE'; +exports[1733] = 'ER_PARTITION_EXCHANGE_TEMP_TABLE'; +exports[1734] = 'ER_PARTITION_INSTEAD_OF_SUBPARTITION'; +exports[1735] = 'ER_UNKNOWN_PARTITION'; +exports[1736] = 'ER_TABLES_DIFFERENT_METADATA'; +exports[1737] = 'ER_ROW_DOES_NOT_MATCH_PARTITION'; +exports[1738] = 'ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX'; +exports[1739] = 'ER_WARN_INDEX_NOT_APPLICABLE'; +exports[1740] = 'ER_PARTITION_EXCHANGE_FOREIGN_KEY'; +exports[1741] = 'ER_NO_SUCH_KEY_VALUE'; +exports[1742] = 'ER_RPL_INFO_DATA_TOO_LONG'; +exports[1743] = 'ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE'; +exports[1744] = 'ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE'; +exports[1745] = 'ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX'; +exports[1746] = 'ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT'; +exports[1747] = 'ER_PARTITION_CLAUSE_ON_NONPARTITIONED'; +exports[1748] = 'ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET'; +exports[1749] = 'ER_NO_SUCH_PARTITION'; +exports[1750] = 'ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE'; +exports[1751] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE'; +exports[1752] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE'; +exports[1753] = 'ER_MTS_FEATURE_IS_NOT_SUPPORTED'; +exports[1754] = 'ER_MTS_UPDATED_DBS_GREATER_MAX'; +exports[1755] = 'ER_MTS_CANT_PARALLEL'; +exports[1756] = 'ER_MTS_INCONSISTENT_DATA'; +exports[1757] = 'ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING'; +exports[1758] = 'ER_DA_INVALID_CONDITION_NUMBER'; +exports[1759] = 'ER_INSECURE_PLAIN_TEXT'; +exports[1760] = 'ER_INSECURE_CHANGE_MASTER'; +exports[1761] = 'ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO'; +exports[1762] = 'ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO'; +exports[1763] = 'ER_SQLTHREAD_WITH_SECURE_SLAVE'; +exports[1764] = 'ER_TABLE_HAS_NO_FT'; +exports[1765] = 'ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER'; +exports[1766] = 'ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION'; +exports[1767] = 'ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST'; +exports[1768] = 'ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION'; +exports[1769] = 'ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION'; +exports[1770] = 'ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL'; +exports[1771] = 'ER_SKIPPING_LOGGED_TRANSACTION'; +exports[1772] = 'ER_MALFORMED_GTID_SET_SPECIFICATION'; +exports[1773] = 'ER_MALFORMED_GTID_SET_ENCODING'; +exports[1774] = 'ER_MALFORMED_GTID_SPECIFICATION'; +exports[1775] = 'ER_GNO_EXHAUSTED'; +exports[1776] = 'ER_BAD_SLAVE_AUTO_POSITION'; +exports[1777] = 'ER_AUTO_POSITION_REQUIRES_GTID_MODE_NOT_OFF'; +exports[1778] = 'ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET'; +exports[1779] = 'ER_GTID_MODE_ON_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON'; +exports[1780] = 'ER_GTID_MODE_REQUIRES_BINLOG'; +exports[1781] = 'ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF'; +exports[1782] = 'ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON'; +exports[1783] = 'ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF'; +exports[1784] = 'ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF'; +exports[1785] = 'ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE'; +exports[1786] = 'ER_GTID_UNSAFE_CREATE_SELECT'; +exports[1787] = 'ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION'; +exports[1788] = 'ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME'; +exports[1789] = 'ER_MASTER_HAS_PURGED_REQUIRED_GTIDS'; +exports[1790] = 'ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID'; +exports[1791] = 'ER_UNKNOWN_EXPLAIN_FORMAT'; +exports[1792] = 'ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION'; +exports[1793] = 'ER_TOO_LONG_TABLE_PARTITION_COMMENT'; +exports[1794] = 'ER_SLAVE_CONFIGURATION'; +exports[1795] = 'ER_INNODB_FT_LIMIT'; +exports[1796] = 'ER_INNODB_NO_FT_TEMP_TABLE'; +exports[1797] = 'ER_INNODB_FT_WRONG_DOCID_COLUMN'; +exports[1798] = 'ER_INNODB_FT_WRONG_DOCID_INDEX'; +exports[1799] = 'ER_INNODB_ONLINE_LOG_TOO_BIG'; +exports[1800] = 'ER_UNKNOWN_ALTER_ALGORITHM'; +exports[1801] = 'ER_UNKNOWN_ALTER_LOCK'; +exports[1802] = 'ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS'; +exports[1803] = 'ER_MTS_RECOVERY_FAILURE'; +exports[1804] = 'ER_MTS_RESET_WORKERS'; +exports[1805] = 'ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2'; +exports[1806] = 'ER_SLAVE_SILENT_RETRY_TRANSACTION'; +exports[1807] = 'ER_DISCARD_FK_CHECKS_RUNNING'; +exports[1808] = 'ER_TABLE_SCHEMA_MISMATCH'; +exports[1809] = 'ER_TABLE_IN_SYSTEM_TABLESPACE'; +exports[1810] = 'ER_IO_READ_ERROR'; +exports[1811] = 'ER_IO_WRITE_ERROR'; +exports[1812] = 'ER_TABLESPACE_MISSING'; +exports[1813] = 'ER_TABLESPACE_EXISTS'; +exports[1814] = 'ER_TABLESPACE_DISCARDED'; +exports[1815] = 'ER_INTERNAL_ERROR'; +exports[1816] = 'ER_INNODB_IMPORT_ERROR'; +exports[1817] = 'ER_INNODB_INDEX_CORRUPT'; +exports[1818] = 'ER_INVALID_YEAR_COLUMN_LENGTH'; +exports[1819] = 'ER_NOT_VALID_PASSWORD'; +exports[1820] = 'ER_MUST_CHANGE_PASSWORD'; +exports[1821] = 'ER_FK_NO_INDEX_CHILD'; +exports[1822] = 'ER_FK_NO_INDEX_PARENT'; +exports[1823] = 'ER_FK_FAIL_ADD_SYSTEM'; +exports[1824] = 'ER_FK_CANNOT_OPEN_PARENT'; +exports[1825] = 'ER_FK_INCORRECT_OPTION'; +exports[1826] = 'ER_FK_DUP_NAME'; +exports[1827] = 'ER_PASSWORD_FORMAT'; +exports[1828] = 'ER_FK_COLUMN_CANNOT_DROP'; +exports[1829] = 'ER_FK_COLUMN_CANNOT_DROP_CHILD'; +exports[1830] = 'ER_FK_COLUMN_NOT_NULL'; +exports[1831] = 'ER_DUP_INDEX'; +exports[1832] = 'ER_FK_COLUMN_CANNOT_CHANGE'; +exports[1833] = 'ER_FK_COLUMN_CANNOT_CHANGE_CHILD'; +exports[1834] = 'ER_FK_CANNOT_DELETE_PARENT'; +exports[1835] = 'ER_MALFORMED_PACKET'; +exports[1836] = 'ER_READ_ONLY_MODE'; +exports[1837] = 'ER_GTID_NEXT_TYPE_UNDEFINED_GROUP'; +exports[1838] = 'ER_VARIABLE_NOT_SETTABLE_IN_SP'; +exports[1839] = 'ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF'; +exports[1840] = 'ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY'; +exports[1841] = 'ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY'; +exports[1842] = 'ER_GTID_PURGED_WAS_CHANGED'; +exports[1843] = 'ER_GTID_EXECUTED_WAS_CHANGED'; +exports[1844] = 'ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES'; +exports[1845] = 'ER_ALTER_OPERATION_NOT_SUPPORTED'; +exports[1846] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON'; +exports[1847] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY'; +exports[1848] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION'; +exports[1849] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME'; +exports[1850] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE'; +exports[1851] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK'; +exports[1852] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE'; +exports[1853] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK'; +exports[1854] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC'; +exports[1855] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS'; +exports[1856] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS'; +exports[1857] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS'; +exports[1858] = 'ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE'; +exports[1859] = 'ER_DUP_UNKNOWN_IN_INDEX'; +exports[1860] = 'ER_IDENT_CAUSES_TOO_LONG_PATH'; +exports[1861] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL'; +exports[1862] = 'ER_MUST_CHANGE_PASSWORD_LOGIN'; +exports[1863] = 'ER_ROW_IN_WRONG_PARTITION'; +exports[1864] = 'ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX'; +exports[1865] = 'ER_INNODB_NO_FT_USES_PARSER'; +exports[1866] = 'ER_BINLOG_LOGICAL_CORRUPTION'; +exports[1867] = 'ER_WARN_PURGE_LOG_IN_USE'; +exports[1868] = 'ER_WARN_PURGE_LOG_IS_ACTIVE'; +exports[1869] = 'ER_AUTO_INCREMENT_CONFLICT'; +exports[1870] = 'WARN_ON_BLOCKHOLE_IN_RBR'; +exports[1871] = 'ER_SLAVE_MI_INIT_REPOSITORY'; +exports[1872] = 'ER_SLAVE_RLI_INIT_REPOSITORY'; +exports[1873] = 'ER_ACCESS_DENIED_CHANGE_USER_ERROR'; +exports[1874] = 'ER_INNODB_READ_ONLY'; +exports[1875] = 'ER_STOP_SLAVE_SQL_THREAD_TIMEOUT'; +exports[1876] = 'ER_STOP_SLAVE_IO_THREAD_TIMEOUT'; +exports[1877] = 'ER_TABLE_CORRUPT'; +exports[1878] = 'ER_TEMP_FILE_WRITE_FAILURE'; +exports[1879] = 'ER_INNODB_FT_AUX_NOT_HEX_ID'; +exports[1880] = 'ER_OLD_TEMPORALS_UPGRADED'; +exports[1881] = 'ER_INNODB_FORCED_RECOVERY'; +exports[1882] = 'ER_AES_INVALID_IV'; +exports[1883] = 'ER_PLUGIN_CANNOT_BE_UNINSTALLED'; +exports[1884] = 'ER_GTID_UNSAFE_BINLOG_SPLITTABLE_STATEMENT_AND_GTID_GROUP'; +exports[1885] = 'ER_SLAVE_HAS_MORE_GTIDS_THAN_MASTER'; +exports[3000] = 'ER_FILE_CORRUPT'; +exports[3001] = 'ER_ERROR_ON_MASTER'; +exports[3002] = 'ER_INCONSISTENT_ERROR'; +exports[3003] = 'ER_STORAGE_ENGINE_NOT_LOADED'; +exports[3004] = 'ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER'; +exports[3005] = 'ER_WARN_LEGACY_SYNTAX_CONVERTED'; +exports[3006] = 'ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN'; +exports[3007] = 'ER_CANNOT_DISCARD_TEMPORARY_TABLE'; +exports[3008] = 'ER_FK_DEPTH_EXCEEDED'; +exports[3009] = 'ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2'; +exports[3010] = 'ER_WARN_TRIGGER_DOESNT_HAVE_CREATED'; +exports[3011] = 'ER_REFERENCED_TRG_DOES_NOT_EXIST'; +exports[3012] = 'ER_EXPLAIN_NOT_SUPPORTED'; +exports[3013] = 'ER_INVALID_FIELD_SIZE'; +exports[3014] = 'ER_MISSING_HA_CREATE_OPTION'; +exports[3015] = 'ER_ENGINE_OUT_OF_MEMORY'; +exports[3016] = 'ER_PASSWORD_EXPIRE_ANONYMOUS_USER'; +exports[3017] = 'ER_SLAVE_SQL_THREAD_MUST_STOP'; +exports[3018] = 'ER_NO_FT_MATERIALIZED_SUBQUERY'; +exports[3019] = 'ER_INNODB_UNDO_LOG_FULL'; +exports[3020] = 'ER_INVALID_ARGUMENT_FOR_LOGARITHM'; +exports[3021] = 'ER_SLAVE_CHANNEL_IO_THREAD_MUST_STOP'; +exports[3022] = 'ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO'; +exports[3023] = 'ER_WARN_ONLY_MASTER_LOG_FILE_NO_POS'; +exports[3024] = 'ER_QUERY_TIMEOUT'; +exports[3025] = 'ER_NON_RO_SELECT_DISABLE_TIMER'; +exports[3026] = 'ER_DUP_LIST_ENTRY'; +exports[3027] = 'ER_SQL_MODE_NO_EFFECT'; +exports[3028] = 'ER_AGGREGATE_ORDER_FOR_UNION'; +exports[3029] = 'ER_AGGREGATE_ORDER_NON_AGG_QUERY'; +exports[3030] = 'ER_SLAVE_WORKER_STOPPED_PREVIOUS_THD_ERROR'; +exports[3031] = 'ER_DONT_SUPPORT_SLAVE_PRESERVE_COMMIT_ORDER'; +exports[3032] = 'ER_SERVER_OFFLINE_MODE'; +exports[3033] = 'ER_GIS_DIFFERENT_SRIDS'; +exports[3034] = 'ER_GIS_UNSUPPORTED_ARGUMENT'; +exports[3035] = 'ER_GIS_UNKNOWN_ERROR'; +exports[3036] = 'ER_GIS_UNKNOWN_EXCEPTION'; +exports[3037] = 'ER_GIS_INVALID_DATA'; +exports[3038] = 'ER_BOOST_GEOMETRY_EMPTY_INPUT_EXCEPTION'; +exports[3039] = 'ER_BOOST_GEOMETRY_CENTROID_EXCEPTION'; +exports[3040] = 'ER_BOOST_GEOMETRY_OVERLAY_INVALID_INPUT_EXCEPTION'; +exports[3041] = 'ER_BOOST_GEOMETRY_TURN_INFO_EXCEPTION'; +exports[3042] = 'ER_BOOST_GEOMETRY_SELF_INTERSECTION_POINT_EXCEPTION'; +exports[3043] = 'ER_BOOST_GEOMETRY_UNKNOWN_EXCEPTION'; +exports[3044] = 'ER_STD_BAD_ALLOC_ERROR'; +exports[3045] = 'ER_STD_DOMAIN_ERROR'; +exports[3046] = 'ER_STD_LENGTH_ERROR'; +exports[3047] = 'ER_STD_INVALID_ARGUMENT'; +exports[3048] = 'ER_STD_OUT_OF_RANGE_ERROR'; +exports[3049] = 'ER_STD_OVERFLOW_ERROR'; +exports[3050] = 'ER_STD_RANGE_ERROR'; +exports[3051] = 'ER_STD_UNDERFLOW_ERROR'; +exports[3052] = 'ER_STD_LOGIC_ERROR'; +exports[3053] = 'ER_STD_RUNTIME_ERROR'; +exports[3054] = 'ER_STD_UNKNOWN_EXCEPTION'; +exports[3055] = 'ER_GIS_DATA_WRONG_ENDIANESS'; +exports[3056] = 'ER_CHANGE_MASTER_PASSWORD_LENGTH'; +exports[3057] = 'ER_USER_LOCK_WRONG_NAME'; +exports[3058] = 'ER_USER_LOCK_DEADLOCK'; +exports[3059] = 'ER_REPLACE_INACCESSIBLE_ROWS'; +exports[3060] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS'; +exports[3061] = 'ER_ILLEGAL_USER_VAR'; +exports[3062] = 'ER_GTID_MODE_OFF'; +exports[3063] = 'ER_UNSUPPORTED_BY_REPLICATION_THREAD'; +exports[3064] = 'ER_INCORRECT_TYPE'; +exports[3065] = 'ER_FIELD_IN_ORDER_NOT_SELECT'; +exports[3066] = 'ER_AGGREGATE_IN_ORDER_NOT_SELECT'; +exports[3067] = 'ER_INVALID_RPL_WILD_TABLE_FILTER_PATTERN'; +exports[3068] = 'ER_NET_OK_PACKET_TOO_LARGE'; +exports[3069] = 'ER_INVALID_JSON_DATA'; +exports[3070] = 'ER_INVALID_GEOJSON_MISSING_MEMBER'; +exports[3071] = 'ER_INVALID_GEOJSON_WRONG_TYPE'; +exports[3072] = 'ER_INVALID_GEOJSON_UNSPECIFIED'; +exports[3073] = 'ER_DIMENSION_UNSUPPORTED'; +exports[3074] = 'ER_SLAVE_CHANNEL_DOES_NOT_EXIST'; +exports[3075] = 'ER_SLAVE_MULTIPLE_CHANNELS_HOST_PORT'; +exports[3076] = 'ER_SLAVE_CHANNEL_NAME_INVALID_OR_TOO_LONG'; +exports[3077] = 'ER_SLAVE_NEW_CHANNEL_WRONG_REPOSITORY'; +exports[3078] = 'ER_SLAVE_CHANNEL_DELETE'; +exports[3079] = 'ER_SLAVE_MULTIPLE_CHANNELS_CMD'; +exports[3080] = 'ER_SLAVE_MAX_CHANNELS_EXCEEDED'; +exports[3081] = 'ER_SLAVE_CHANNEL_MUST_STOP'; +exports[3082] = 'ER_SLAVE_CHANNEL_NOT_RUNNING'; +exports[3083] = 'ER_SLAVE_CHANNEL_WAS_RUNNING'; +exports[3084] = 'ER_SLAVE_CHANNEL_WAS_NOT_RUNNING'; +exports[3085] = 'ER_SLAVE_CHANNEL_SQL_THREAD_MUST_STOP'; +exports[3086] = 'ER_SLAVE_CHANNEL_SQL_SKIP_COUNTER'; +exports[3087] = 'ER_WRONG_FIELD_WITH_GROUP_V2'; +exports[3088] = 'ER_MIX_OF_GROUP_FUNC_AND_FIELDS_V2'; +exports[3089] = 'ER_WARN_DEPRECATED_SYSVAR_UPDATE'; +exports[3090] = 'ER_WARN_DEPRECATED_SQLMODE'; +exports[3091] = 'ER_CANNOT_LOG_PARTIAL_DROP_DATABASE_WITH_GTID'; +exports[3092] = 'ER_GROUP_REPLICATION_CONFIGURATION'; +exports[3093] = 'ER_GROUP_REPLICATION_RUNNING'; +exports[3094] = 'ER_GROUP_REPLICATION_APPLIER_INIT_ERROR'; +exports[3095] = 'ER_GROUP_REPLICATION_STOP_APPLIER_THREAD_TIMEOUT'; +exports[3096] = 'ER_GROUP_REPLICATION_COMMUNICATION_LAYER_SESSION_ERROR'; +exports[3097] = 'ER_GROUP_REPLICATION_COMMUNICATION_LAYER_JOIN_ERROR'; +exports[3098] = 'ER_BEFORE_DML_VALIDATION_ERROR'; +exports[3099] = 'ER_PREVENTS_VARIABLE_WITHOUT_RBR'; +exports[3100] = 'ER_RUN_HOOK_ERROR'; +exports[3101] = 'ER_TRANSACTION_ROLLBACK_DURING_COMMIT'; +exports[3102] = 'ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED'; +exports[3103] = 'ER_UNSUPPORTED_ALTER_INPLACE_ON_VIRTUAL_COLUMN'; +exports[3104] = 'ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN'; +exports[3105] = 'ER_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN'; +exports[3106] = 'ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN'; +exports[3107] = 'ER_GENERATED_COLUMN_NON_PRIOR'; +exports[3108] = 'ER_DEPENDENT_BY_GENERATED_COLUMN'; +exports[3109] = 'ER_GENERATED_COLUMN_REF_AUTO_INC'; +exports[3110] = 'ER_FEATURE_NOT_AVAILABLE'; +exports[3111] = 'ER_CANT_SET_GTID_MODE'; +exports[3112] = 'ER_CANT_USE_AUTO_POSITION_WITH_GTID_MODE_OFF'; +exports[3113] = 'ER_CANT_REPLICATE_ANONYMOUS_WITH_AUTO_POSITION'; +exports[3114] = 'ER_CANT_REPLICATE_ANONYMOUS_WITH_GTID_MODE_ON'; +exports[3115] = 'ER_CANT_REPLICATE_GTID_WITH_GTID_MODE_OFF'; +exports[3116] = 'ER_CANT_SET_ENFORCE_GTID_CONSISTENCY_ON_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS'; +exports[3117] = 'ER_SET_ENFORCE_GTID_CONSISTENCY_WARN_WITH_ONGOING_GTID_VIOLATING_TRANSACTIONS'; +exports[3118] = 'ER_ACCOUNT_HAS_BEEN_LOCKED'; +exports[3119] = 'ER_WRONG_TABLESPACE_NAME'; +exports[3120] = 'ER_TABLESPACE_IS_NOT_EMPTY'; +exports[3121] = 'ER_WRONG_FILE_NAME'; +exports[3122] = 'ER_BOOST_GEOMETRY_INCONSISTENT_TURNS_EXCEPTION'; +exports[3123] = 'ER_WARN_OPTIMIZER_HINT_SYNTAX_ERROR'; +exports[3124] = 'ER_WARN_BAD_MAX_EXECUTION_TIME'; +exports[3125] = 'ER_WARN_UNSUPPORTED_MAX_EXECUTION_TIME'; +exports[3126] = 'ER_WARN_CONFLICTING_HINT'; +exports[3127] = 'ER_WARN_UNKNOWN_QB_NAME'; +exports[3128] = 'ER_UNRESOLVED_HINT_NAME'; +exports[3129] = 'ER_WARN_ON_MODIFYING_GTID_EXECUTED_TABLE'; +exports[3130] = 'ER_PLUGGABLE_PROTOCOL_COMMAND_NOT_SUPPORTED'; +exports[3131] = 'ER_LOCKING_SERVICE_WRONG_NAME'; +exports[3132] = 'ER_LOCKING_SERVICE_DEADLOCK'; +exports[3133] = 'ER_LOCKING_SERVICE_TIMEOUT'; +exports[3134] = 'ER_GIS_MAX_POINTS_IN_GEOMETRY_OVERFLOWED'; +exports[3135] = 'ER_SQL_MODE_MERGED'; +exports[3136] = 'ER_VTOKEN_PLUGIN_TOKEN_MISMATCH'; +exports[3137] = 'ER_VTOKEN_PLUGIN_TOKEN_NOT_FOUND'; +exports[3138] = 'ER_CANT_SET_VARIABLE_WHEN_OWNING_GTID'; +exports[3139] = 'ER_SLAVE_CHANNEL_OPERATION_NOT_ALLOWED'; +exports[3140] = 'ER_INVALID_JSON_TEXT'; +exports[3141] = 'ER_INVALID_JSON_TEXT_IN_PARAM'; +exports[3142] = 'ER_INVALID_JSON_BINARY_DATA'; +exports[3143] = 'ER_INVALID_JSON_PATH'; +exports[3144] = 'ER_INVALID_JSON_CHARSET'; +exports[3145] = 'ER_INVALID_JSON_CHARSET_IN_FUNCTION'; +exports[3146] = 'ER_INVALID_TYPE_FOR_JSON'; +exports[3147] = 'ER_INVALID_CAST_TO_JSON'; +exports[3148] = 'ER_INVALID_JSON_PATH_CHARSET'; +exports[3149] = 'ER_INVALID_JSON_PATH_WILDCARD'; +exports[3150] = 'ER_JSON_VALUE_TOO_BIG'; +exports[3151] = 'ER_JSON_KEY_TOO_BIG'; +exports[3152] = 'ER_JSON_USED_AS_KEY'; +exports[3153] = 'ER_JSON_VACUOUS_PATH'; +exports[3154] = 'ER_JSON_BAD_ONE_OR_ALL_ARG'; +exports[3155] = 'ER_NUMERIC_JSON_VALUE_OUT_OF_RANGE'; +exports[3156] = 'ER_INVALID_JSON_VALUE_FOR_CAST'; +exports[3157] = 'ER_JSON_DOCUMENT_TOO_DEEP'; +exports[3158] = 'ER_JSON_DOCUMENT_NULL_KEY'; +exports[3159] = 'ER_SECURE_TRANSPORT_REQUIRED'; +exports[3160] = 'ER_NO_SECURE_TRANSPORTS_CONFIGURED'; +exports[3161] = 'ER_DISABLED_STORAGE_ENGINE'; +exports[3162] = 'ER_USER_DOES_NOT_EXIST'; +exports[3163] = 'ER_USER_ALREADY_EXISTS'; +exports[3164] = 'ER_AUDIT_API_ABORT'; +exports[3165] = 'ER_INVALID_JSON_PATH_ARRAY_CELL'; +exports[3166] = 'ER_BUFPOOL_RESIZE_INPROGRESS'; +exports[3167] = 'ER_FEATURE_DISABLED_SEE_DOC'; +exports[3168] = 'ER_SERVER_ISNT_AVAILABLE'; +exports[3169] = 'ER_SESSION_WAS_KILLED'; +exports[3170] = 'ER_CAPACITY_EXCEEDED'; +exports[3171] = 'ER_CAPACITY_EXCEEDED_IN_RANGE_OPTIMIZER'; +exports[3172] = 'ER_TABLE_NEEDS_UPG_PART'; +exports[3173] = 'ER_CANT_WAIT_FOR_EXECUTED_GTID_SET_WHILE_OWNING_A_GTID'; +exports[3174] = 'ER_CANNOT_ADD_FOREIGN_BASE_COL_VIRTUAL'; +exports[3175] = 'ER_CANNOT_CREATE_VIRTUAL_INDEX_CONSTRAINT'; +exports[3176] = 'ER_ERROR_ON_MODIFYING_GTID_EXECUTED_TABLE'; +exports[3177] = 'ER_LOCK_REFUSED_BY_ENGINE'; +exports[3178] = 'ER_UNSUPPORTED_ALTER_ONLINE_ON_VIRTUAL_COLUMN'; +exports[3179] = 'ER_MASTER_KEY_ROTATION_NOT_SUPPORTED_BY_SE'; +exports[3180] = 'ER_MASTER_KEY_ROTATION_ERROR_BY_SE'; +exports[3181] = 'ER_MASTER_KEY_ROTATION_BINLOG_FAILED'; +exports[3182] = 'ER_MASTER_KEY_ROTATION_SE_UNAVAILABLE'; +exports[3183] = 'ER_TABLESPACE_CANNOT_ENCRYPT'; +exports[3184] = 'ER_INVALID_ENCRYPTION_OPTION'; +exports[3185] = 'ER_CANNOT_FIND_KEY_IN_KEYRING'; +exports[3186] = 'ER_CAPACITY_EXCEEDED_IN_PARSER'; +exports[3187] = 'ER_UNSUPPORTED_ALTER_ENCRYPTION_INPLACE'; +exports[3188] = 'ER_KEYRING_UDF_KEYRING_SERVICE_ERROR'; +exports[3189] = 'ER_USER_COLUMN_OLD_LENGTH'; +exports[3190] = 'ER_CANT_RESET_MASTER'; +exports[3191] = 'ER_GROUP_REPLICATION_MAX_GROUP_SIZE'; +exports[3192] = 'ER_CANNOT_ADD_FOREIGN_BASE_COL_STORED'; +exports[3193] = 'ER_TABLE_REFERENCED'; +exports[3194] = 'ER_PARTITION_ENGINE_DEPRECATED_FOR_TABLE'; +exports[3195] = 'ER_WARN_USING_GEOMFROMWKB_TO_SET_SRID_ZERO'; +exports[3196] = 'ER_WARN_USING_GEOMFROMWKB_TO_SET_SRID'; +exports[3197] = 'ER_XA_RETRY'; +exports[3198] = 'ER_KEYRING_AWS_UDF_AWS_KMS_ERROR'; +exports[3199] = 'ER_BINLOG_UNSAFE_XA'; +exports[3200] = 'ER_UDF_ERROR'; +exports[3201] = 'ER_KEYRING_MIGRATION_FAILURE'; +exports[3202] = 'ER_KEYRING_ACCESS_DENIED_ERROR'; +exports[3203] = 'ER_KEYRING_MIGRATION_STATUS'; diff --git a/node_modules/mysql/lib/protocol/constants/field_flags.js b/node_modules/mysql/lib/protocol/constants/field_flags.js new file mode 100644 index 0000000000000000000000000000000000000000..c698da51bd99ee4d6e65d9111087660b5a53e317 --- /dev/null +++ b/node_modules/mysql/lib/protocol/constants/field_flags.js @@ -0,0 +1,18 @@ +// Manually extracted from mysql-5.5.23/include/mysql_com.h +exports.NOT_NULL_FLAG = 1; /* Field can't be NULL */ +exports.PRI_KEY_FLAG = 2; /* Field is part of a primary key */ +exports.UNIQUE_KEY_FLAG = 4; /* Field is part of a unique key */ +exports.MULTIPLE_KEY_FLAG = 8; /* Field is part of a key */ +exports.BLOB_FLAG = 16; /* Field is a blob */ +exports.UNSIGNED_FLAG = 32; /* Field is unsigned */ +exports.ZEROFILL_FLAG = 64; /* Field is zerofill */ +exports.BINARY_FLAG = 128; /* Field is binary */ + +/* The following are only sent to new clients */ +exports.ENUM_FLAG = 256; /* field is an enum */ +exports.AUTO_INCREMENT_FLAG = 512; /* field is a autoincrement field */ +exports.TIMESTAMP_FLAG = 1024; /* Field is a timestamp */ +exports.SET_FLAG = 2048; /* field is a set */ +exports.NO_DEFAULT_VALUE_FLAG = 4096; /* Field doesn't have default value */ +exports.ON_UPDATE_NOW_FLAG = 8192; /* Field is set to NOW on UPDATE */ +exports.NUM_FLAG = 32768; /* Field is num (for clients) */ diff --git a/node_modules/mysql/lib/protocol/constants/server_status.js b/node_modules/mysql/lib/protocol/constants/server_status.js new file mode 100644 index 0000000000000000000000000000000000000000..48880c3709cf58149a448f3e4821e85097d95f20 --- /dev/null +++ b/node_modules/mysql/lib/protocol/constants/server_status.js @@ -0,0 +1,39 @@ +// Manually extracted from mysql-5.5.23/include/mysql_com.h + +/** + Is raised when a multi-statement transaction + has been started, either explicitly, by means + of BEGIN or COMMIT AND CHAIN, or + implicitly, by the first transactional + statement, when autocommit=off. +*/ +exports.SERVER_STATUS_IN_TRANS = 1; +exports.SERVER_STATUS_AUTOCOMMIT = 2; /* Server in auto_commit mode */ +exports.SERVER_MORE_RESULTS_EXISTS = 8; /* Multi query - next query exists */ +exports.SERVER_QUERY_NO_GOOD_INDEX_USED = 16; +exports.SERVER_QUERY_NO_INDEX_USED = 32; +/** + The server was able to fulfill the clients request and opened a + read-only non-scrollable cursor for a query. This flag comes + in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands. +*/ +exports.SERVER_STATUS_CURSOR_EXISTS = 64; +/** + This flag is sent when a read-only cursor is exhausted, in reply to + COM_STMT_FETCH command. +*/ +exports.SERVER_STATUS_LAST_ROW_SENT = 128; +exports.SERVER_STATUS_DB_DROPPED = 256; /* A database was dropped */ +exports.SERVER_STATUS_NO_BACKSLASH_ESCAPES = 512; +/** + Sent to the client if after a prepared statement reprepare + we discovered that the new statement returns a different + number of result set columns. +*/ +exports.SERVER_STATUS_METADATA_CHANGED = 1024; +exports.SERVER_QUERY_WAS_SLOW = 2048; + +/** + To mark ResultSet containing output parameter values. +*/ +exports.SERVER_PS_OUT_PARAMS = 4096; diff --git a/node_modules/mysql/lib/protocol/constants/ssl_profiles.js b/node_modules/mysql/lib/protocol/constants/ssl_profiles.js new file mode 100644 index 0000000000000000000000000000000000000000..e76b954e1b47631565c9b13bba2d49ad8c8fbfcc --- /dev/null +++ b/node_modules/mysql/lib/protocol/constants/ssl_profiles.js @@ -0,0 +1,740 @@ +// Certificates for Amazon RDS +exports['Amazon RDS'] = { + ca: [ + /** + * Amazon RDS global certificate 2010 to 2015 + * + * CN = aws.amazon.com/rds/ + * OU = RDS + * O = Amazon.com + * L = Seattle + * ST = Washington + * C = US + * P = 2010-04-05T22:44:31Z/2015-04-04T22:41:31Z + * F = 7F:09:8D:A5:7D:BB:A6:EF:7C:70:D8:CA:4E:49:11:55:7E:89:A7:D3 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIDQzCCAqygAwIBAgIJAOd1tlfiGoEoMA0GCSqGSIb3DQEBBQUAMHUxCzAJBgNV\n' + + 'BAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdTZWF0dGxlMRMw\n' + + 'EQYDVQQKEwpBbWF6b24uY29tMQwwCgYDVQQLEwNSRFMxHDAaBgNVBAMTE2F3cy5h\n' + + 'bWF6b24uY29tL3Jkcy8wHhcNMTAwNDA1MjI0NDMxWhcNMTUwNDA0MjI0NDMxWjB1\n' + + 'MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHU2Vh\n' + + 'dHRsZTETMBEGA1UEChMKQW1hem9uLmNvbTEMMAoGA1UECxMDUkRTMRwwGgYDVQQD\n' + + 'ExNhd3MuYW1hem9uLmNvbS9yZHMvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n' + + 'gQDKhXGU7tizxUR5WaFoMTFcxNxa05PEjZaIOEN5ctkWrqYSRov0/nOMoZjqk8bC\n' + + 'med9vPFoQGD0OTakPs0jVe3wwmR735hyVwmKIPPsGlaBYj1O6llIpZeQVyupNx56\n' + + 'UzqtiLaDzh1KcmfqP3qP2dInzBfJQKjiRudo1FWnpPt33QIDAQABo4HaMIHXMB0G\n' + + 'A1UdDgQWBBT/H3x+cqSkR/ePSIinPtc4yWKe3DCBpwYDVR0jBIGfMIGcgBT/H3x+\n' + + 'cqSkR/ePSIinPtc4yWKe3KF5pHcwdTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldh\n' + + 'c2hpbmd0b24xEDAOBgNVBAcTB1NlYXR0bGUxEzARBgNVBAoTCkFtYXpvbi5jb20x\n' + + 'DDAKBgNVBAsTA1JEUzEcMBoGA1UEAxMTYXdzLmFtYXpvbi5jb20vcmRzL4IJAOd1\n' + + 'tlfiGoEoMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAvguZy/BDT66x\n' + + 'GfgnJlyQwnFSeVLQm9u/FIvz4huGjbq9dqnD6h/Gm56QPFdyMEyDiZWaqY6V08lY\n' + + 'LTBNb4kcIc9/6pc0/ojKciP5QJRm6OiZ4vgG05nF4fYjhU7WClUx7cxq1fKjNc2J\n' + + 'UCmmYqgiVkAGWRETVo+byOSDZ4swb10=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS global root CA 2015 to 2020 + * + * CN = Amazon RDS Root CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T09:11:31Z/2020-03-05T09:11:31Z + * F = E8:11:88:56:E7:A7:CE:3E:5E:DC:9A:31:25:1B:93:AC:DC:43:CE:B0 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID9DCCAtygAwIBAgIBQjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUwOTExMzFaFw0y\n' + + 'MDAzMDUwOTExMzFaMIGKMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEbMBkGA1UEAwwSQW1hem9uIFJE\n' + + 'UyBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuD8nrZ8V\n' + + 'u+VA8yVlUipCZIKPTDcOILYpUe8Tct0YeQQr0uyl018StdBsa3CjBgvwpDRq1HgF\n' + + 'Ji2N3+39+shCNspQeE6aYU+BHXhKhIIStt3r7gl/4NqYiDDMWKHxHq0nsGDFfArf\n' + + 'AOcjZdJagOMqb3fF46flc8k2E7THTm9Sz4L7RY1WdABMuurpICLFE3oHcGdapOb9\n' + + 'T53pQR+xpHW9atkcf3pf7gbO0rlKVSIoUenBlZipUlp1VZl/OD/E+TtRhDDNdI2J\n' + + 'P/DSMM3aEsq6ZQkfbz/Ilml+Lx3tJYXUDmp+ZjzMPLk/+3beT8EhrwtcG3VPpvwp\n' + + 'BIOqsqVVTvw/CwIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw\n' + + 'AwEB/zAdBgNVHQ4EFgQUTgLurD72FchM7Sz1BcGPnIQISYMwHwYDVR0jBBgwFoAU\n' + + 'TgLurD72FchM7Sz1BcGPnIQISYMwDQYJKoZIhvcNAQEFBQADggEBAHZcgIio8pAm\n' + + 'MjHD5cl6wKjXxScXKtXygWH2BoDMYBJF9yfyKO2jEFxYKbHePpnXB1R04zJSWAw5\n' + + '2EUuDI1pSBh9BA82/5PkuNlNeSTB3dXDD2PEPdzVWbSKvUB8ZdooV+2vngL0Zm4r\n' + + '47QPyd18yPHrRIbtBtHR/6CwKevLZ394zgExqhnekYKIqqEX41xsUV0Gm6x4vpjf\n' + + '2u6O/+YE2U+qyyxHE5Wd5oqde0oo9UUpFETJPVb6Q2cEeQib8PBAyi0i6KnF+kIV\n' + + 'A9dY7IHSubtCK/i8wxMVqfd5GtbA8mmpeJFwnDvm9rBEsHybl08qlax9syEwsUYr\n' + + '/40NawZfTUU=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-northeast-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS ap-northeast-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:06Z/2020-03-05T22:03:06Z + * F = 4B:2D:8A:E0:C1:A3:A9:AF:A7:BB:65:0C:5A:16:8A:39:3C:03:F2:C5 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEATCCAumgAwIBAgIBRDANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMDZaFw0y\n' + + 'MDAzMDUyMjAzMDZaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n' + + 'UyBhcC1ub3J0aGVhc3QtMSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n' + + 'ggEBAMmM2B4PfTXCZjbZMWiDPyxvk/eeNwIRJAhfzesiGUiLozX6CRy3rwC1ZOPV\n' + + 'AcQf0LB+O8wY88C/cV+d4Q2nBDmnk+Vx7o2MyMh343r5rR3Na+4izd89tkQVt0WW\n' + + 'vO21KRH5i8EuBjinboOwAwu6IJ+HyiQiM0VjgjrmEr/YzFPL8MgHD/YUHehqjACn\n' + + 'C0+B7/gu7W4qJzBL2DOf7ub2qszGtwPE+qQzkCRDwE1A4AJmVE++/FLH2Zx78Egg\n' + + 'fV1sUxPtYgjGH76VyyO6GNKM6rAUMD/q5mnPASQVIXgKbupr618bnH+SWHFjBqZq\n' + + 'HvDGPMtiiWII41EmGUypyt5AbysCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n' + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFIiKM0Q6n1K4EmLxs3ZXxINbwEwR\n' + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n' + + 'A4IBAQBezGbE9Rw/k2e25iGjj5n8r+M3dlye8ORfCE/dijHtxqAKasXHgKX8I9Tw\n' + + 'JkBiGWiuzqn7gO5MJ0nMMro1+gq29qjZnYX1pDHPgsRjUX8R+juRhgJ3JSHijRbf\n' + + '4qNJrnwga7pj94MhcLq9u0f6dxH6dXbyMv21T4TZMTmcFduf1KgaiVx1PEyJjC6r\n' + + 'M+Ru+A0eM+jJ7uCjUoZKcpX8xkj4nmSnz9NMPog3wdOSB9cAW7XIc5mHa656wr7I\n' + + 'WJxVcYNHTXIjCcng2zMKd1aCcl2KSFfy56sRfT7J5Wp69QSr+jq8KM55gw8uqAwi\n' + + 'VPrXn2899T1rcTtFYFP16WXjGuc0\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-northeast-2 certificate CA 2015 to 2020 + * + * CN = Amazon RDS ap-northeast-2 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-11-06T00:05:46Z/2020-03-05T00:05:46Z + * F = 77:D9:33:4E:CE:56:FC:42:7B:29:57:8D:67:59:ED:29:4E:18:CB:6B + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEATCCAumgAwIBAgIBTDANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTExMDYwMDA1NDZaFw0y\n' + + 'MDAzMDUwMDA1NDZaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n' + + 'UyBhcC1ub3J0aGVhc3QtMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n' + + 'ggEBAKSwd+RVUzTRH0FgnbwoTK8TMm/zMT4+2BvALpAUe6YXbkisg2goycWuuWLg\n' + + 'jOpFBB3GtyvXZnkqi7MkDWUmj1a2kf8l2oLyoaZ+Hm9x/sV+IJzOqPvj1XVUGjP6\n' + + 'yYYnPJmUYqvZeI7fEkIGdFkP2m4/sgsSGsFvpD9FK1bL1Kx2UDpYX0kHTtr18Zm/\n' + + '1oN6irqWALSmXMDydb8hE0FB2A1VFyeKE6PnoDj/Y5cPHwPPdEi6/3gkDkSaOG30\n' + + 'rWeQfL3pOcKqzbHaWTxMphd0DSL/quZ64Nr+Ly65Q5PRcTrtr55ekOUziuqXwk+o\n' + + '9QpACMwcJ7ROqOznZTqTzSFVXFECAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n' + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFM6Nox/QWbhzWVvzoJ/y0kGpNPK+\n' + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n' + + 'A4IBAQCTkWBqNvyRf3Y/W21DwFx3oT/AIWrHt0BdGZO34tavummXemTH9LZ/mqv9\n' + + 'aljt6ZuDtf5DEQjdsAwXMsyo03ffnP7doWm8iaF1+Mui77ot0TmTsP/deyGwukvJ\n' + + 'tkxX8bZjDh+EaNauWKr+CYnniNxCQLfFtXYJsfOdVBzK3xNL+Z3ucOQRhr2helWc\n' + + 'CDQgwfhP1+3pRVKqHvWCPC4R3fT7RZHuRmZ38kndv476GxRntejh+ePffif78bFI\n' + + '3rIZCPBGobrrUMycafSbyXteoGca/kA+/IqrAPlk0pWQ4aEL0yTWN2h2dnjoD7oX\n' + + 'byIuL/g9AGRh97+ssn7D6bDRPTbW\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-southeast-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS ap-southeast-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:19Z/2020-03-05T22:03:19Z + * F = 0E:EC:5D:BD:F9:80:EE:A9:A0:8D:81:AC:37:D9:8D:34:1C:CD:27:D1 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEATCCAumgAwIBAgIBRTANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMTlaFw0y\n' + + 'MDAzMDUyMjAzMTlaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n' + + 'UyBhcC1zb3V0aGVhc3QtMSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n' + + 'ggEBANaXElmSEYt/UtxHFsARFhSUahTf1KNJzR0Dmay6hqOXQuRVbKRwPd19u5vx\n' + + 'DdF1sLT7D69IK3VDnUiQScaCv2Dpu9foZt+rLx+cpx1qiQd1UHrvqq8xPzQOqCdC\n' + + 'RFStq6yVYZ69yfpfoI67AjclMOjl2Vph3ftVnqP0IgVKZdzeC7fd+umGgR9xY0Qr\n' + + 'Ubhd/lWdsbNvzK3f1TPWcfIKQnpvSt85PIEDJir6/nuJUKMtmJRwTymJf0i+JZ4x\n' + + '7dJa341p2kHKcHMgOPW7nJQklGBA70ytjUV6/qebS3yIugr/28mwReflg3TJzVDl\n' + + 'EOvi6pqbqNbkMuEwGDCmEQIVqgkCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n' + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFAu93/4k5xbWOsgdCdn+/KdiRuit\n' + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n' + + 'A4IBAQBlcjSyscpPjf5+MgzMuAsCxByqUt+WFspwcMCpwdaBeHOPSQrXNqX2Sk6P\n' + + 'kth6oCivA64trWo8tFMvPYlUA1FYVD5WpN0kCK+P5pD4KHlaDsXhuhClJzp/OP8t\n' + + 'pOyUr5109RHLxqoKB5J5m1XA7rgcFjnMxwBSWFe3/4uMk/+4T53YfCVXuc6QV3i7\n' + + 'I/2LAJwFf//pTtt6fZenYfCsahnr2nvrNRNyAxcfvGZ/4Opn/mJtR6R/AjvQZHiR\n' + + 'bkRNKF2GW0ueK5W4FkZVZVhhX9xh1Aj2Ollb+lbOqADaVj+AT3PoJPZ3MPQHKCXm\n' + + 'xwG0LOLlRr/TfD6li1AfOVTAJXv9\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-southeast-2 certificate CA 2015 to 2020 + * + * CN = Amazon RDS ap-southeast-2 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:24Z/2020-03-05T22:03:24Z + * F = 20:D9:A8:82:23:AB:B9:E5:C5:24:10:D3:4D:0F:3D:B1:31:DF:E5:14 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEATCCAumgAwIBAgIBRjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMjRaFw0y\n' + + 'MDAzMDUyMjAzMjRaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n' + + 'UyBhcC1zb3V0aGVhc3QtMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n' + + 'ggEBAJqBAJutz69hFOh3BtLHZTbwE8eejGGKayn9hu98YMDPzWzGXWCmW+ZYWELA\n' + + 'cY3cNWNF8K4FqKXFr2ssorBYim1UtYFX8yhydT2hMD5zgQ2sCGUpuidijuPA6zaq\n' + + 'Z3tdhVR94f0q8mpwpv2zqR9PcqaGDx2VR1x773FupRPRo7mEW1vC3IptHCQlP/zE\n' + + '7jQiLl28bDIH2567xg7e7E9WnZToRnhlYdTaDaJsHTzi5mwILi4cihSok7Shv/ME\n' + + 'hnukvxeSPUpaVtFaBhfBqq055ePq9I+Ns4KGreTKMhU0O9fkkaBaBmPaFgmeX/XO\n' + + 'n2AX7gMouo3mtv34iDTZ0h6YCGkCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n' + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFIlQnY0KHYWn1jYumSdJYfwj/Nfw\n' + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n' + + 'A4IBAQA0wVU6/l41cTzHc4azc4CDYY2Wd90DFWiH9C/mw0SgToYfCJ/5Cfi0NT/Y\n' + + 'PRnk3GchychCJgoPA/k9d0//IhYEAIiIDjyFVgjbTkKV3sh4RbdldKVOUB9kumz/\n' + + 'ZpShplsGt3z4QQiVnKfrAgqxWDjR0I0pQKkxXa6Sjkicos9LQxVtJ0XA4ieG1E7z\n' + + 'zJr+6t80wmzxvkInSaWP3xNJK9azVRTrgQZQlvkbpDbExl4mNTG66VD3bAp6t3Wa\n' + + 'B49//uDdfZmPkqqbX+hsxp160OH0rxJppwO3Bh869PkDnaPEd/Pxw7PawC+li0gi\n' + + 'NRV8iCEx85aFxcyOhqn0WZOasxee\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-central-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS eu-central-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:31Z/2020-03-05T22:03:31Z + * F = 94:B4:DF:B9:6D:7E:F7:C3:B7:BF:51:E9:A6:B7:44:A0:D0:82:11:84 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/zCCAuegAwIBAgIBRzANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMzFaFw0y\n' + + 'MDAzMDUyMjAzMzFaMIGSMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEjMCEGA1UEAwwaQW1hem9uIFJE\n' + + 'UyBldS1jZW50cmFsLTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n' + + 'AQDFtP2dhSLuaPOI4ZrrPWsK4OY9ocQBp3yApH1KJYmI9wpQKZG/KCH2E6Oo7JAw\n' + + 'QORU519r033T+FO2Z7pFPlmz1yrxGXyHpJs8ySx3Yo5S8ncDCdZJCLmtPiq/hahg\n' + + '5/0ffexMFUCQaYicFZsrJ/cStdxUV+tSw2JQLD7UxS9J97LQWUPyyG+ZrjYVTVq+\n' + + 'zudnFmNSe4QoecXMhAFTGJFQXxP7nhSL9Ao5FGgdXy7/JWeWdQIAj8ku6cBDKPa6\n' + + 'Y6kP+ak+In+Lye8z9qsCD/afUozfWjPR2aA4JoIZVF8dNRShIMo8l0XfgfM2q0+n\n' + + 'ApZWZ+BjhIO5XuoUgHS3D2YFAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNV\n' + + 'HRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBRm4GsWIA/M6q+tK8WGHWDGh2gcyTAf\n' + + 'BgNVHSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOC\n' + + 'AQEAHpMmeVQNqcxgfQdbDIi5UIy+E7zZykmtAygN1XQrvga9nXTis4kOTN6g5/+g\n' + + 'HCx7jIXeNJzAbvg8XFqBN84Quqgpl/tQkbpco9Jh1HDs558D5NnZQxNqH5qXQ3Mm\n' + + 'uPgCw0pYcPOa7bhs07i+MdVwPBsX27CFDtsgAIru8HvKxY1oTZrWnyIRo93tt/pk\n' + + 'WuItVMVHjaQZVfTCow0aDUbte6Vlw82KjUFq+n2NMSCJDiDKsDDHT6BJc4AJHIq3\n' + + '/4Z52MSC9KMr0yAaaoWfW/yMEj9LliQauAgwVjArF4q78rxpfKTG9Rfd8U1BZANP\n' + + '7FrFMN0ThjfA1IvmOYcgskY5bQ==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-west-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS eu-west-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:35Z/2020-03-05T22:03:35Z + * F = 1A:95:F0:43:82:D2:5D:A6:AD:F5:13:27:0B:40:8A:72:D9:92:F3:E0 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBSDANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMzVaFw0y\n' + + 'MDAzMDUyMjAzMzVaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n' + + 'UyBldS13ZXN0LTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCx\n' + + 'PdbqQ0HKRj79Pmocxvjc+P6i4Ux24kgFIl+ckiir1vzkmesc3a58gjrMlCksEObt\n' + + 'Yihs5IhzEq1ePT0gbfS9GYFp34Uj/MtPwlrfCBWG4d2TcrsKRHr1/EXUYhWqmdrb\n' + + 'RhX8XqoRhVkbF/auzFSBhTzcGGvZpQ2KIaxRcQfcXlMVhj/pxxAjh8U4F350Fb0h\n' + + 'nX1jw4/KvEreBL0Xb2lnlGTkwVxaKGSgXEnOgIyOFdOQc61vdome0+eeZsP4jqeR\n' + + 'TGYJA9izJsRbe2YJxHuazD+548hsPlM3vFzKKEVURCha466rAaYAHy3rKur3HYQx\n' + + 'Yt+SoKcEz9PXuSGj96ejAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBTebg//h2oeXbZjQ4uuoiuLYzuiPDAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n' + + 'TikPaGeZasTPw+4RBemlsyPAjtFFQLo7ddaFdORLgdEysVf8aBqndvbA6MT/v4lj\n' + + 'GtEtUdF59ZcbWOrVm+fBZ2h/jYJ59dYF/xzb09nyRbdMSzB9+mkSsnOMqluq5y8o\n' + + 'DY/PfP2vGhEg/2ZncRC7nlQU1Dm8F4lFWEiQ2fi7O1cW852Vmbq61RIfcYsH/9Ma\n' + + 'kpgk10VZ75b8m3UhmpZ/2uRY+JEHImH5WpcTJ7wNiPNJsciZMznGtrgOnPzYco8L\n' + + 'cDleOASIZifNMQi9PKOJKvi0ITz0B/imr8KBsW0YjZVJ54HMa7W1lwugSM7aMAs+\n' + + 'E3Sd5lS+SHwWaOCHwhOEVA==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS sa-east-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS sa-east-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:40Z/2020-03-05T22:03:40Z + * F = 32:10:3D:FA:6D:42:F5:35:98:40:15:F4:4C:74:74:27:CB:CE:D4:B5 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBSTANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzNDBaFw0y\n' + + 'MDAzMDUyMjAzNDBaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n' + + 'UyBzYS1lYXN0LTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCU\n' + + 'X4OBnQ5xA6TLJAiFEI6l7bUWjoVJBa/VbMdCCSs2i2dOKmqUaXu2ix2zcPILj3lZ\n' + + 'GMk3d/2zvTK/cKhcFrewHUBamTeVHdEmynhMQamqNmkM4ptYzFcvEUw1TGxHT4pV\n' + + 'Q6gSN7+/AJewQvyHexHo8D0+LDN0/Wa9mRm4ixCYH2CyYYJNKaZt9+EZfNu+PPS4\n' + + '8iB0TWH0DgQkbWMBfCRgolLLitAZklZ4dvdlEBS7evN1/7ttBxUK6SvkeeSx3zBl\n' + + 'ww3BlXqc3bvTQL0A+RRysaVyFbvtp9domFaDKZCpMmDFAN/ntx215xmQdrSt+K3F\n' + + 'cXdGQYHx5q410CAclGnbAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBT6iVWnm/uakS+tEX2mzIfw+8JL0zAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n' + + 'FmDD+QuDklXn2EgShwQxV13+txPRuVdOSrutHhoCgMwFWCMtPPtBAKs6KPY7Guvw\n' + + 'DpJoZSehDiOfsgMirjOWjvfkeWSNvKfjWTVneX7pZD9W5WPnsDBvTbCGezm+v87z\n' + + 'b+ZM2ZMo98m/wkMcIEAgdSKilR2fuw8rLkAjhYFfs0A7tDgZ9noKwgHvoE4dsrI0\n' + + 'KZYco6DlP/brASfHTPa2puBLN9McK3v+h0JaSqqm5Ro2Bh56tZkQh8AWy/miuDuK\n' + + '3+hNEVdxosxlkM1TPa1DGj0EzzK0yoeerXuH2HX7LlCrrxf6/wdKnjR12PMrLQ4A\n' + + 'pCqkcWw894z6bV9MAvKe6A==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-east-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS us-east-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T21:54:04Z/2020-03-05T21:54:04Z + * F = 34:47:8A:90:8A:83:AE:45:DC:B6:16:76:D2:35:EC:E9:75:C6:2C:63 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBQzANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMTU0MDRaFw0y\n' + + 'MDAzMDUyMTU0MDRaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n' + + 'UyB1cy1lYXN0LTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDI\n' + + 'UIuwh8NusKHk1SqPXcP7OqxY3S/M2ZyQWD3w7Bfihpyyy/fc1w0/suIpX3kbMhAV\n' + + '2ESwged2/2zSx4pVnjp/493r4luhSqQYzru78TuPt9bhJIJ51WXunZW2SWkisSaf\n' + + 'USYUzVN9ezR/bjXTumSUQaLIouJt3OHLX49s+3NAbUyOI8EdvgBQWD68H1epsC0n\n' + + 'CI5s+pIktyOZ59c4DCDLQcXErQ+tNbDC++oct1ANd/q8p9URonYwGCGOBy7sbCYq\n' + + '9eVHh1Iy2M+SNXddVOGw5EuruvHoCIQyOz5Lz4zSuZA9dRbrfztNOpezCNYu6NKM\n' + + 'n+hzcvdiyxv77uNm8EaxAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBQSQG3TmMe6Sa3KufaPBa72v4QFDzAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n' + + 'L/mOZfB3187xTmjOHMqN2G2oSKHBKiQLM9uv8+97qT+XR+TVsBT6b3yoPpMAGhHA\n' + + 'Pc7nxAF5gPpuzatx0OTLPcmYucFmfqT/1qA5WlgCnMNtczyNMH97lKFTNV7Njtek\n' + + 'jWEzAEQSyEWrkNpNlC4j6kMYyPzVXQeXUeZTgJ9FNnVZqmvfjip2N22tawMjrCn5\n' + + '7KN/zN65EwY2oO9XsaTwwWmBu3NrDdMbzJnbxoWcFWj4RBwanR1XjQOVNhDwmCOl\n' + + '/1Et13b8CPyj69PC8BOVU6cfTSx8WUVy0qvYOKHNY9Bqa5BDnIL3IVmUkeTlM1mt\n' + + 'enRpyBj+Bk9rh/ICdiRKmA==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-west-1 certificate CA 2015 to 2020 + * + * CN = Amazon RDS us-west-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:45Z/2020-03-05T22:03:45Z + * F = EF:94:2F:E3:58:0E:09:D6:79:C2:16:97:91:FB:37:EA:D7:70:A8:4B + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBSjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzNDVaFw0y\n' + + 'MDAzMDUyMjAzNDVaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n' + + 'UyB1cy13ZXN0LTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDE\n' + + 'Dhw+uw/ycaiIhhyu2pXFRimq0DlB8cNtIe8hdqndH8TV/TFrljNgR8QdzOgZtZ9C\n' + + 'zzQ2GRpInN/qJF6slEd6wO+6TaDBQkPY+07TXNt52POFUhdVkhJXHpE2BS7Xn6J7\n' + + '7RFAOeG1IZmc2DDt+sR1BgXzUqHslQGfFYNS0/MBO4P+ya6W7IhruB1qfa4HiYQS\n' + + 'dbe4MvGWnv0UzwAqdR7OF8+8/5c58YXZIXCO9riYF2ql6KNSL5cyDPcYK5VK0+Q9\n' + + 'VI6vuJHSMYcF7wLePw8jtBktqAFE/wbdZiIHhZvNyiNWPPNTGUmQbaJ+TzQEHDs5\n' + + '8en+/W7JKnPyBOkxxENbAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBS0nw/tFR9bCjgqWTPJkyy4oOD8bzAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n' + + 'CXGAY3feAak6lHdqj6+YWjy6yyUnLK37bRxZDsyDVXrPRQaXRzPTzx79jvDwEb/H\n' + + 'Q/bdQ7zQRWqJcbivQlwhuPJ4kWPUZgSt3JUUuqkMsDzsvj/bwIjlrEFDOdHGh0mi\n' + + 'eVIngFEjUXjMh+5aHPEF9BlQnB8LfVtKj18e15UDTXFa+xJPFxUR7wDzCfo4WI1m\n' + + 'sUMG4q1FkGAZgsoyFPZfF8IVvgCuGdR8z30VWKklFxttlK0eGLlPAyIO0CQxPQlo\n' + + 'saNJrHf4tLOgZIWk+LpDhNd9Et5EzvJ3aURUsKY4pISPPF5WdvM9OE59bERwUErd\n' + + 'nuOuQWQeeadMceZnauRzJQ==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-west-2 certificate CA 2015 to 2020 + * + * CN = Amazon RDS us-west-2 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2015-02-05T22:03:50Z/2020-03-05T22:03:50Z + * F = 94:2C:A8:B0:23:48:17:F0:CD:2F:19:7F:C1:E0:21:7C:65:79:13:3A + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBSzANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzNTBaFw0y\n' + + 'MDAzMDUyMjAzNTBaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n' + + 'UyB1cy13ZXN0LTIgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDM\n' + + 'H58SR48U6jyERC1vYTnub34smf5EQVXyzaTmspWGWGzT31NLNZGSDFaa7yef9kdO\n' + + 'mzJsgebR5tXq6LdwlIoWkKYQ7ycUaadtVKVYdI40QcI3cHn0qLFlg2iBXmWp/B+i\n' + + 'Z34VuVlCh31Uj5WmhaBoz8t/GRqh1V/aCsf3Wc6jCezH3QfuCjBpzxdOOHN6Ie2v\n' + + 'xX09O5qmZTvMoRBAvPkxdaPg/Mi7fxueWTbEVk78kuFbF1jHYw8U1BLILIAhcqlq\n' + + 'x4u8nl73t3O3l/soNUcIwUDK0/S+Kfqhwn9yQyPlhb4Wy3pfnZLJdkyHldktnQav\n' + + '9TB9u7KH5Lk0aAYslMLxAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBT8roM4lRnlFHWMPWRz0zkwFZog1jAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n' + + 'JwrxwgwmPtcdaU7O7WDdYa4hprpOMamI49NDzmE0s10oGrqmLwZygcWU0jT+fJ+Y\n' + + 'pJe1w0CVfKaeLYNsOBVW3X4ZPmffYfWBheZiaiEflq/P6t7/Eg81gaKYnZ/x1Dfa\n' + + 'sUYkzPvCkXe9wEz5zdUTOCptDt89rBR9CstL9vE7WYUgiVVmBJffWbHQLtfjv6OF\n' + + 'NMb0QME981kGRzc2WhgP71YS2hHd1kXtsoYP1yTu4vThSKsoN4bkiHsaC1cRkLoy\n' + + '0fFA4wpB3WloMEvCDaUvvH1LZlBXTNlwi9KtcwD4tDxkkBt4tQczKLGpQ/nF/W9n\n' + + '8YDWk3IIc1sd0bkZqoau2Q==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-south-1 certificate CA 2016 to 2020 + * + * CN = Amazon RDS ap-south-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2016-05-03T21:29:22Z/2020-03-05T21:29:22Z + * F = F3:A3:C2:52:D9:82:20:AC:8C:62:31:2A:8C:AD:5D:7B:1C:31:F1:DD + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/TCCAuWgAwIBAgIBTTANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjA1MDMyMTI5MjJaFw0y\n' + + 'MDAzMDUyMTI5MjJaMIGQMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEhMB8GA1UEAwwYQW1hem9uIFJE\n' + + 'UyBhcC1zb3V0aC0xIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\n' + + '06eWGLE0TeqL9kyWOLkS8q0fXO97z+xyBV3DKSB2lg2GkgBz3B98MkmkeB0SZy3G\n' + + 'Ce4uCpCPbFKiFEdiUclOlhZsrBuCeaimxLM3Ig2wuenElO/7TqgaYHYUbT3d+VQW\n' + + 'GUbLn5GRZJZe1OAClYdOWm7A1CKpuo+cVV1vxbY2nGUQSJPpVn2sT9gnwvjdE60U\n' + + 'JGYU/RLCTm8zmZBvlWaNIeKDnreIc4rKn6gUnJ2cQn1ryCVleEeyc3xjYDSrjgdn\n' + + 'FLYGcp9mphqVT0byeQMOk0c7RHpxrCSA0V5V6/CreFV2LteK50qcDQzDSM18vWP/\n' + + 'p09FoN8O7QrtOeZJzH/lmwIDAQABo2YwZDAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0T\n' + + 'AQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU2i83QHuEl/d0keXF+69HNJph7cMwHwYD\n' + + 'VR0jBBgwFoAUTgLurD72FchM7Sz1BcGPnIQISYMwDQYJKoZIhvcNAQELBQADggEB\n' + + 'ACqnH2VjApoDqoSQOky52QBwsGaj+xWYHW5Gm7EvCqvQuhWMkeBuD6YJmMvNyA9G\n' + + 'I2lh6/o+sUk/RIsbYbxPRdhNPTOgDR9zsNRw6qxaHztq/CEC+mxDCLa3O1hHBaDV\n' + + 'BmB3nCZb93BvO0EQSEk7aytKq/f+sjyxqOcs385gintdHGU9uM7gTZHnU9vByJsm\n' + + '/TL07Miq67X0NlhIoo3jAk+xHaeKJdxdKATQp0448P5cY20q4b8aMk1twcNaMvCP\n' + + 'dG4M5doaoUA8OQ/0ukLLae/LBxLeTw04q1/a2SyFaVUX2Twbb1S3xVWwLA8vsyGr\n' + + 'igXx7B5GgP+IHb6DTjPJAi0=\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-east-2 certificate CA 2016 to 2020 + * + * CN = Amazon RDS us-east-2 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2016-08-11T19:58:45Z/2020-03-05T19:58:45Z + * F = 9B:78:E3:64:7F:74:BC:B2:52:18:CF:13:C3:62:B8:35:9D:3D:5F:B6 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBTjANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjA4MTExOTU4NDVaFw0y\n' + + 'MDAzMDUxOTU4NDVaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n' + + 'UyB1cy1lYXN0LTIgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCp\n' + + 'WnnUX7wM0zzstccX+4iXKJa9GR0a2PpvB1paEX4QRCgfhEdQWDaSqyrWNgdVCKkt\n' + + '1aQkWu5j6VAC2XIG7kKoonm1ZdBVyBLqW5lXNywlaiU9yhJkwo8BR+/OqgE+PLt/\n' + + 'EO1mlN0PQudja/XkExCXTO29TG2j7F/O7hox6vTyHNHc0H88zS21uPuBE+jivViS\n' + + 'yzj/BkyoQ85hnkues3f9R6gCGdc+J51JbZnmgzUkvXjAEuKhAm9JksVOxcOKUYe5\n' + + 'ERhn0U9zjzpfbAITIkul97VVa5IxskFFTHIPJbvRKHJkiF6wTJww/tc9wm+fSCJ1\n' + + '+DbQTGZgkQ3bJrqRN29/AgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBSAHQzUYYZbepwKEMvGdHp8wzHnfDAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQsFAAOCAQEA\n' + + 'MbaEzSYZ+aZeTBxf8yi0ta8K4RdwEJsEmP6IhFFQHYUtva2Cynl4Q9tZg3RMsybT\n' + + '9mlnSQQlbN/wqIIXbkrcgFcHoXG9Odm/bDtUwwwDaiEhXVfeQom3G77QHOWMTCGK\n' + + 'qadwuh5msrb17JdXZoXr4PYHDKP7j0ONfAyFNER2+uecblHfRSpVq5UeF3L6ZJb8\n' + + 'fSw/GtAV6an+/0r+Qm+PiI2H5XuZ4GmRJYnGMhqWhBYrY7p3jtVnKcsh39wgfUnW\n' + + 'AvZEZG/yhFyAZW0Essa39LiL5VSq14Y1DOj0wgnhSY/9WHxaAo1HB1T9OeZknYbD\n' + + 'fl/EGSZ0TEvZkENrXcPlVA==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ca-central-1 certificate CA 2016 to 2020 + * + * CN = Amazon RDS ca-central-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2016-09-15T00:10:11Z/2020-03-05T00:10:11Z + * F = D7:E0:16:AB:8A:0B:63:9F:67:1F:16:87:42:F4:0A:EE:73:A6:FC:04 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/zCCAuegAwIBAgIBTzANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjA5MTUwMDEwMTFaFw0y\n' + + 'MDAzMDUwMDEwMTFaMIGSMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEjMCEGA1UEAwwaQW1hem9uIFJE\n' + + 'UyBjYS1jZW50cmFsLTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n' + + 'AQCZYI/iQ6DrS3ny3t1EwX1wAD+3LMgh7Fd01EW5LIuaK2kYIIQpsVKhxLCit/V5\n' + + 'AGc/1qiJS1Qz9ODLTh0Na6bZW6EakRzuHJLe32KJtoFYPC7Z09UqzXrpA/XL+1hM\n' + + 'P0ZmCWsU7Nn/EmvfBp9zX3dZp6P6ATrvDuYaVFr+SA7aT3FXpBroqBS1fyzUPs+W\n' + + 'c6zTR6+yc4zkHX0XQxC5RH6xjgpeRkoOajA/sNo7AQF7KlWmKHbdVF44cvvAhRKZ\n' + + 'XaoVs/C4GjkaAEPTCbopYdhzg+KLx9eB2BQnYLRrIOQZtRfbQI2Nbj7p3VsRuOW1\n' + + 'tlcks2w1Gb0YC6w6SuIMFkl1AgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNV\n' + + 'HRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBToYWxE1lawl6Ks6NsvpbHQ3GKEtzAf\n' + + 'BgNVHSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQsFAAOC\n' + + 'AQEAG/8tQ0ooi3hoQpa5EJz0/E5VYBsAz3YxA2HoIonn0jJyG16bzB4yZt4vNQMA\n' + + 'KsNlQ1uwDWYL1nz63axieUUFIxqxl1KmwfhsmLgZ0Hd2mnTPIl2Hw3uj5+wdgGBg\n' + + 'agnAZ0bajsBYgD2VGQbqjdk2Qn7Fjy3LEWIvGZx4KyZ99OJ2QxB7JOPdauURAtWA\n' + + 'DKYkP4LLJxtj07DSzG8kuRWb9B47uqUD+eKDIyjfjbnzGtd9HqqzYFau7EX3HVD9\n' + + '9Qhnjl7bTZ6YfAEZ3nH2t3Vc0z76XfGh47rd0pNRhMV+xpok75asKf/lNh5mcUrr\n' + + 'VKwflyMkQpSbDCmcdJ90N2xEXQ==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-west-2 certificate CA 2016 to 2020 + * + * CN = Amazon RDS eu-west-2 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2016-10-10T17:44:42Z/2020-03-05T17:44:42Z + * F = 47:79:51:9F:FF:07:D3:F4:27:D3:AB:64:56:7F:00:45:BB:84:C1:71 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBUDANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjEwMTAxNzQ0NDJaFw0y\n' + + 'MDAzMDUxNzQ0NDJaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n' + + 'UyBldS13ZXN0LTIgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDO\n' + + 'cttLJfubB4XMMIGWNfJISkIdCMGJyOzLiMJaiWB5GYoXKhEl7YGotpy0qklwW3BQ\n' + + 'a0fmVdcCLX+dIuVQ9iFK+ZcK7zwm7HtdDTCHOCKeOh2IcnU4c/VIokFi6Gn8udM6\n' + + 'N/Zi5M5OGpVwLVALQU7Yctsn3c95el6MdVx6mJiIPVu7tCVZn88Z2koBQ2gq9P4O\n' + + 'Sb249SHFqOb03lYDsaqy1NDsznEOhaRBw7DPJFpvmw1lA3/Y6qrExRI06H2VYR2i\n' + + '7qxwDV50N58fs10n7Ye1IOxTVJsgEA7X6EkRRXqYaM39Z76R894548WHfwXWjUsi\n' + + 'MEX0RS0/t1GmnUQjvevDAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBQBxmcuRSxERYCtNnSr5xNfySokHjAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQsFAAOCAQEA\n' + + 'UyCUQjsF3nUAABjfEZmpksTuUo07aT3KGYt+EMMFdejnBQ0+2lJJFGtT+CDAk1SD\n' + + 'RSgfEBon5vvKEtlnTf9a3pv8WXOAkhfxnryr9FH6NiB8obISHNQNPHn0ljT2/T+I\n' + + 'Y6ytfRvKHa0cu3V0NXbJm2B4KEOt4QCDiFxUIX9z6eB4Kditwu05OgQh6KcogOiP\n' + + 'JesWxBMXXGoDC1rIYTFO7szwDyOHlCcVXJDNsTJhc32oDWYdeIbW7o/5I+aQsrXZ\n' + + 'C96HykZcgWzz6sElrQxUaT3IoMw/5nmw4uWKKnZnxgI9bY4fpQwMeBZ96iHfFxvH\n' + + 'mqfEEuC7uUoPofXdBp2ObQ==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS us-gov-west-1 CA 2017 to 2022 + * + * CN = Amazon RDS us-gov-west-1 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2017-05-19T22:31:19Z/2022-05-18T12:00:00Z + * F = 77:55:8C:C4:5E:71:1F:1B:57:E3:DA:6E:5B:74:27:12:4E:E8:69:E8 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIECjCCAvKgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwgZMxCzAJBgNVBAYTAlVT\n' + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n' + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n' + + 'MSQwIgYDVQQDDBtBbWF6b24gUkRTIEdvdkNsb3VkIFJvb3QgQ0EwHhcNMTcwNTE5\n' + + 'MjIzMTE5WhcNMjIwNTE4MTIwMDAwWjCBkzELMAkGA1UEBhMCVVMxEzARBgNVBAgM\n' + + 'Cldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoMGUFtYXpvbiBX\n' + + 'ZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMxJDAiBgNVBAMM\n' + + 'G0FtYXpvbiBSRFMgdXMtZ292LXdlc3QtMSBDQTCCASIwDQYJKoZIhvcNAQEBBQAD\n' + + 'ggEPADCCAQoCggEBAM8YZLKAzzOdNnoi7Klih26Zkj+OCpDfwx4ZYB6f8L8UoQi5\n' + + '8z9ZtIwMjiJ/kO08P1yl4gfc7YZcNFvhGruQZNat3YNpxwUpQcr4mszjuffbL4uz\n' + + '+/8FBxALdqCVOJ5Q0EVSfz3d9Bd1pUPL7ARtSpy7bn/tUPyQeI+lODYO906C0TQ3\n' + + 'b9bjOsgAdBKkHfjLdsknsOZYYIzYWOJyFJJa0B11XjDUNBy/3IuC0KvDl6At0V5b\n' + + '8M6cWcKhte2hgjwTYepV+/GTadeube1z5z6mWsN5arOAQUtYDLH6Aztq9mCJzLHm\n' + + 'RccBugnGl3fRLJ2VjioN8PoGoN9l9hFBy5fnFgsCAwEAAaNmMGQwDgYDVR0PAQH/\n' + + 'BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFEG7+br8KkvwPd5g\n' + + '71Rvh2stclJbMB8GA1UdIwQYMBaAFEkQz6S4NS5lOYKcDjBSuCcVpdzjMA0GCSqG\n' + + 'SIb3DQEBCwUAA4IBAQBMA327u5ABmhX+aPxljoIbxnydmAFWxW6wNp5+rZrvPig8\n' + + 'zDRqGQWWr7wWOIjfcWugSElYtf/m9KZHG/Z6+NG7nAoUrdcd1h/IQhb+lFQ2b5g9\n' + + 'sVzQv/H2JNkfZA8fL/Ko/Tm/f9tcqe0zrGCtT+5u0Nvz35Wl8CEUKLloS5xEb3k5\n' + + '7D9IhG3fsE3vHWlWrGCk1cKry3j12wdPG5cUsug0vt34u6rdhP+FsM0tHI15Kjch\n' + + 'RuUCvyQecy2ZFNAa3jmd5ycNdL63RWe8oayRBpQBxPPCbHfILxGZEdJbCH9aJ2D/\n' + + 'l8oHIDnvOLdv7/cBjyYuvmprgPtu3QEkbre5Hln/\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS eu-west-3 certificate CA 2017 to 2020 + * + * CN = Amazon RDS eu-west-3 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2017-08-25T21:39:26Z/2020-03-05T21:39:26Z + * F = FD:35:A7:84:60:68:98:00:12:54:ED:34:26:8C:66:0F:72:DD:B2:F4 + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIID/DCCAuSgAwIBAgIBUTANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNzA4MjUyMTM5MjZaFw0y\n' + + 'MDAzMDUyMTM5MjZaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n' + + 'UyBldS13ZXN0LTMgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC+\n' + + 'xmlEC/3a4cJH+UPwXCE02lC7Zq5NHd0dn6peMeLN8agb6jW4VfSY0NydjRj2DJZ8\n' + + 'K7wV6sub5NUGT1NuFmvSmdbNR2T59KX0p2dVvxmXHHtIpQ9Y8Aq3ZfhmC5q5Bqgw\n' + + 'tMA1xayDi7HmoPX3R8kk9ktAZQf6lDeksCvok8idjTu9tiSpDiMwds5BjMsWfyjZ\n' + + 'd13PTGGNHYVdP692BSyXzSP1Vj84nJKnciW8tAqwIiadreJt5oXyrCXi8ekUMs80\n' + + 'cUTuGm3aA3Q7PB5ljJMPqz0eVddaiIvmTJ9O3Ez3Du/HpImyMzXjkFaf+oNXf/Hx\n' + + '/EW5jCRR6vEiXJcDRDS7AgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n' + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBRZ9mRtS5fHk3ZKhG20Oack4cAqMTAfBgNV\n' + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQsFAAOCAQEA\n' + + 'F/u/9L6ExQwD73F/bhCw7PWcwwqsK1mypIdrjdIsu0JSgwWwGCXmrIspA3n3Dqxq\n' + + 'sMhAJD88s9Em7337t+naar2VyLO63MGwjj+vA4mtvQRKq8ScIpiEc7xN6g8HUMsd\n' + + 'gPG9lBGfNjuAZsrGJflrko4HyuSM7zHExMjXLH+CXcv/m3lWOZwnIvlVMa4x0Tz0\n' + + 'A4fklaawryngzeEjuW6zOiYCzjZtPlP8Fw0SpzppJ8VpQfrZ751RDo4yudmPqoPK\n' + + '5EUe36L8U+oYBXnC5TlYs9bpVv9o5wJQI5qA9oQE2eFWxF1E0AyZ4V5sgGUBStaX\n' + + 'BjDDWul0wSo7rt1Tq7XpnA==\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS ap-northeast-3 certificate CA 2017 to 2020 + * + * CN = Amazon RDS ap-northeast-3 CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2017-12-01T00:55:42Z/2020-03-05T00:55:42Z + * F = C0:C7:D4:B3:91:40:A0:77:43:28:BF:AF:77:57:DF:FD:98:FB:10:3F + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEATCCAumgAwIBAgIBTjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n' + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n' + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n' + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNzEyMDEwMDU1NDJaFw0y\n' + + 'MDAzMDUwMDU1NDJaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n' + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n' + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n' + + 'UyBhcC1ub3J0aGVhc3QtMyBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n' + + 'ggEBAMZtQNnm/XT19mTa10ftHLzg5UhajoI65JHv4TQNdGXdsv+CQdGYU49BJ9Eu\n' + + '3bYgiEtTzR2lQe9zGMvtuJobLhOWuavzp7IixoIQcHkFHN6wJ1CvqrxgvJfBq6Hy\n' + + 'EuCDCiU+PPDLUNA6XM6Qx3IpHd1wrJkjRB80dhmMSpxmRmx849uFafhN+P1QybsM\n' + + 'TI0o48VON2+vj+mNuQTyLMMP8D4odSQHjaoG+zyJfJGZeAyqQyoOUOFEyQaHC3TT\n' + + '3IDSNCQlpxb9LerbCoKu79WFBBq3CS5cYpg8/fsnV2CniRBFFUumBt5z4dhw9RJU\n' + + 'qlUXXO1ZyzpGd+c5v6FtrfXtnIUCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n' + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFETv7ELNplYy/xTeIOInl6nzeiHg\n' + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n' + + 'A4IBAQCpKxOQcd0tEKb3OtsOY8q/MPwTyustGk2Rt7t9G68idADp8IytB7M0SDRo\n' + + 'wWZqynEq7orQVKdVOanhEWksNDzGp0+FPAf/KpVvdYCd7ru3+iI+V4ZEp2JFdjuZ\n' + + 'Zz0PIjS6AgsZqE5Ri1J+NmfmjGZCPhsHnGZiBaenX6K5VRwwwmLN6xtoqrrfR5zL\n' + + 'QfBeeZNJG6KiM3R/DxJ5rAa6Fz+acrhJ60L7HprhB7SFtj1RCijau3+ZwiGmUOMr\n' + + 'yKlMv+VgmzSw7o4Hbxy1WVrA6zQsTHHSGf+vkQn2PHvnFMUEu/ZLbTDYFNmTLK91\n' + + 'K6o4nMsEvhBKgo4z7H1EqqxXhvN2\n' + + '-----END CERTIFICATE-----\n', + + /** + * Amazon RDS GovCloud Root CA 2017 to 2022 + * + * CN = Amazon RDS GovCloud Root CA + * OU = Amazon RDS + * O = Amazon Web Services, Inc. + * L = Seattle + * ST = Washington + * C = US + * P = 2017-05-19T22:29:11Z/2022-05-18T22:29:11Z + * F = A3:61:F9:C9:A2:5B:91:FE:73:A6:52:E3:59:14:8E:CE:35:12:0F:FD + */ + '-----BEGIN CERTIFICATE-----\n' + + 'MIIEDjCCAvagAwIBAgIJAMM61RQn3/kdMA0GCSqGSIb3DQEBCwUAMIGTMQswCQYD\n' + + 'VQQGEwJVUzEQMA4GA1UEBwwHU2VhdHRsZTETMBEGA1UECAwKV2FzaGluZ3RvbjEi\n' + + 'MCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1h\n' + + 'em9uIFJEUzEkMCIGA1UEAwwbQW1hem9uIFJEUyBHb3ZDbG91ZCBSb290IENBMB4X\n' + + 'DTE3MDUxOTIyMjkxMVoXDTIyMDUxODIyMjkxMVowgZMxCzAJBgNVBAYTAlVTMRAw\n' + + 'DgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQKDBlB\n' + + 'bWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRTMSQw\n' + + 'IgYDVQQDDBtBbWF6b24gUkRTIEdvdkNsb3VkIFJvb3QgQ0EwggEiMA0GCSqGSIb3\n' + + 'DQEBAQUAA4IBDwAwggEKAoIBAQDGS9bh1FGiJPT+GRb3C5aKypJVDC1H2gbh6n3u\n' + + 'j8cUiyMXfmm+ak402zdLpSYMaxiQ7oL/B3wEmumIpRDAsQrSp3B/qEeY7ipQGOfh\n' + + 'q2TXjXGIUjiJ/FaoGqkymHRLG+XkNNBtb7MRItsjlMVNELXECwSiMa3nJL2/YyHW\n' + + 'nTr1+11/weeZEKgVbCUrOugFkMXnfZIBSn40j6EnRlO2u/NFU5ksK5ak2+j8raZ7\n' + + 'xW7VXp9S1Tgf1IsWHjGZZZguwCkkh1tHOlHC9gVA3p63WecjrIzcrR/V27atul4m\n' + + 'tn56s5NwFvYPUIx1dbC8IajLUrepVm6XOwdQCfd02DmOyjWJAgMBAAGjYzBhMA4G\n' + + 'A1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRJEM+kuDUu\n' + + 'ZTmCnA4wUrgnFaXc4zAfBgNVHSMEGDAWgBRJEM+kuDUuZTmCnA4wUrgnFaXc4zAN\n' + + 'BgkqhkiG9w0BAQsFAAOCAQEAcfA7uirXsNZyI2j4AJFVtOTKOZlQwqbyNducnmlg\n' + + '/5nug9fAkwM4AgvF5bBOD1Hw6khdsccMwIj+1S7wpL+EYb/nSc8G0qe1p/9lZ/mZ\n' + + 'ff5g4JOa26lLuCrZDqAk4TzYnt6sQKfa5ZXVUUn0BK3okhiXS0i+NloMyaBCL7vk\n' + + 'kDwkHwEqflRKfZ9/oFTcCfoiHPA7AdBtaPVr0/Kj9L7k+ouz122huqG5KqX0Zpo8\n' + + 'S0IGvcd2FZjNSNPttNAK7YuBVsZ0m2nIH1SLp//00v7yAHIgytQwwB17PBcp4NXD\n' + + 'pCfTa27ng9mMMC2YLqWQpW4TkqjDin2ZC+5X/mbrjzTvVg==\n' + + '-----END CERTIFICATE-----\n' + ] +}; diff --git a/node_modules/mysql/lib/protocol/constants/types.js b/node_modules/mysql/lib/protocol/constants/types.js new file mode 100644 index 0000000000000000000000000000000000000000..19943e8e589e5b05285d34d5b08cfb22924e6ac2 --- /dev/null +++ b/node_modules/mysql/lib/protocol/constants/types.js @@ -0,0 +1,33 @@ +// Manually extracted from mysql-5.7.9/include/mysql.h.pp +// some more info here: http://dev.mysql.com/doc/refman/5.5/en/c-api-prepared-statement-type-codes.html +exports.DECIMAL = 0x00; // aka DECIMAL (http://dev.mysql.com/doc/refman/5.0/en/precision-math-decimal-changes.html) +exports.TINY = 0x01; // aka TINYINT, 1 byte +exports.SHORT = 0x02; // aka SMALLINT, 2 bytes +exports.LONG = 0x03; // aka INT, 4 bytes +exports.FLOAT = 0x04; // aka FLOAT, 4-8 bytes +exports.DOUBLE = 0x05; // aka DOUBLE, 8 bytes +exports.NULL = 0x06; // NULL (used for prepared statements, I think) +exports.TIMESTAMP = 0x07; // aka TIMESTAMP +exports.LONGLONG = 0x08; // aka BIGINT, 8 bytes +exports.INT24 = 0x09; // aka MEDIUMINT, 3 bytes +exports.DATE = 0x0a; // aka DATE +exports.TIME = 0x0b; // aka TIME +exports.DATETIME = 0x0c; // aka DATETIME +exports.YEAR = 0x0d; // aka YEAR, 1 byte (don't ask) +exports.NEWDATE = 0x0e; // aka ? +exports.VARCHAR = 0x0f; // aka VARCHAR (?) +exports.BIT = 0x10; // aka BIT, 1-8 byte +exports.TIMESTAMP2 = 0x11; // aka TIMESTAMP with fractional seconds +exports.DATETIME2 = 0x12; // aka DATETIME with fractional seconds +exports.TIME2 = 0x13; // aka TIME with fractional seconds +exports.JSON = 0xf5; // aka JSON +exports.NEWDECIMAL = 0xf6; // aka DECIMAL +exports.ENUM = 0xf7; // aka ENUM +exports.SET = 0xf8; // aka SET +exports.TINY_BLOB = 0xf9; // aka TINYBLOB, TINYTEXT +exports.MEDIUM_BLOB = 0xfa; // aka MEDIUMBLOB, MEDIUMTEXT +exports.LONG_BLOB = 0xfb; // aka LONGBLOG, LONGTEXT +exports.BLOB = 0xfc; // aka BLOB, TEXT +exports.VAR_STRING = 0xfd; // aka VARCHAR, VARBINARY +exports.STRING = 0xfe; // aka CHAR, BINARY +exports.GEOMETRY = 0xff; // aka GEOMETRY diff --git a/node_modules/mysql/lib/protocol/packets/AuthSwitchRequestPacket.js b/node_modules/mysql/lib/protocol/packets/AuthSwitchRequestPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..c74e6ec23680991261e2184ee3c69bbd338daa52 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/AuthSwitchRequestPacket.js @@ -0,0 +1,20 @@ +module.exports = AuthSwitchRequestPacket; +function AuthSwitchRequestPacket(options) { + options = options || {}; + + this.status = 0xfe; + this.authMethodName = options.authMethodName; + this.authMethodData = options.authMethodData; +} + +AuthSwitchRequestPacket.prototype.parse = function parse(parser) { + this.status = parser.parseUnsignedNumber(1); + this.authMethodName = parser.parseNullTerminatedString(); + this.authMethodData = parser.parsePacketTerminatedBuffer(); +}; + +AuthSwitchRequestPacket.prototype.write = function write(writer) { + writer.writeUnsignedNumber(1, this.status); + writer.writeNullTerminatedString(this.authMethodName); + writer.writeBuffer(this.authMethodData); +}; diff --git a/node_modules/mysql/lib/protocol/packets/AuthSwitchResponsePacket.js b/node_modules/mysql/lib/protocol/packets/AuthSwitchResponsePacket.js new file mode 100644 index 0000000000000000000000000000000000000000..488abbd03b26f3bf9b5952f53ec7b48096d74e68 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/AuthSwitchResponsePacket.js @@ -0,0 +1,14 @@ +module.exports = AuthSwitchResponsePacket; +function AuthSwitchResponsePacket(options) { + options = options || {}; + + this.data = options.data; +} + +AuthSwitchResponsePacket.prototype.parse = function parse(parser) { + this.data = parser.parsePacketTerminatedBuffer(); +}; + +AuthSwitchResponsePacket.prototype.write = function write(writer) { + writer.writeBuffer(this.data); +}; diff --git a/node_modules/mysql/lib/protocol/packets/ClientAuthenticationPacket.js b/node_modules/mysql/lib/protocol/packets/ClientAuthenticationPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..595db77a002f236f10e78e9c5b816ba0afc57f5d --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/ClientAuthenticationPacket.js @@ -0,0 +1,54 @@ +var Buffer = require('safe-buffer').Buffer; + +module.exports = ClientAuthenticationPacket; +function ClientAuthenticationPacket(options) { + options = options || {}; + + this.clientFlags = options.clientFlags; + this.maxPacketSize = options.maxPacketSize; + this.charsetNumber = options.charsetNumber; + this.filler = undefined; + this.user = options.user; + this.scrambleBuff = options.scrambleBuff; + this.database = options.database; + this.protocol41 = options.protocol41; +} + +ClientAuthenticationPacket.prototype.parse = function(parser) { + if (this.protocol41) { + this.clientFlags = parser.parseUnsignedNumber(4); + this.maxPacketSize = parser.parseUnsignedNumber(4); + this.charsetNumber = parser.parseUnsignedNumber(1); + this.filler = parser.parseFiller(23); + this.user = parser.parseNullTerminatedString(); + this.scrambleBuff = parser.parseLengthCodedBuffer(); + this.database = parser.parseNullTerminatedString(); + } else { + this.clientFlags = parser.parseUnsignedNumber(2); + this.maxPacketSize = parser.parseUnsignedNumber(3); + this.user = parser.parseNullTerminatedString(); + this.scrambleBuff = parser.parseBuffer(8); + this.database = parser.parseLengthCodedBuffer(); + } +}; + +ClientAuthenticationPacket.prototype.write = function(writer) { + if (this.protocol41) { + writer.writeUnsignedNumber(4, this.clientFlags); + writer.writeUnsignedNumber(4, this.maxPacketSize); + writer.writeUnsignedNumber(1, this.charsetNumber); + writer.writeFiller(23); + writer.writeNullTerminatedString(this.user); + writer.writeLengthCodedBuffer(this.scrambleBuff); + writer.writeNullTerminatedString(this.database); + } else { + writer.writeUnsignedNumber(2, this.clientFlags); + writer.writeUnsignedNumber(3, this.maxPacketSize); + writer.writeNullTerminatedString(this.user); + writer.writeBuffer(this.scrambleBuff); + if (this.database && this.database.length) { + writer.writeFiller(1); + writer.writeBuffer(Buffer.from(this.database)); + } + } +}; diff --git a/node_modules/mysql/lib/protocol/packets/ComChangeUserPacket.js b/node_modules/mysql/lib/protocol/packets/ComChangeUserPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..3278842358f1e083729481d68b37e5ffbb9bae49 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/ComChangeUserPacket.js @@ -0,0 +1,26 @@ +module.exports = ComChangeUserPacket; +function ComChangeUserPacket(options) { + options = options || {}; + + this.command = 0x11; + this.user = options.user; + this.scrambleBuff = options.scrambleBuff; + this.database = options.database; + this.charsetNumber = options.charsetNumber; +} + +ComChangeUserPacket.prototype.parse = function(parser) { + this.command = parser.parseUnsignedNumber(1); + this.user = parser.parseNullTerminatedString(); + this.scrambleBuff = parser.parseLengthCodedBuffer(); + this.database = parser.parseNullTerminatedString(); + this.charsetNumber = parser.parseUnsignedNumber(1); +}; + +ComChangeUserPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.command); + writer.writeNullTerminatedString(this.user); + writer.writeLengthCodedBuffer(this.scrambleBuff); + writer.writeNullTerminatedString(this.database); + writer.writeUnsignedNumber(2, this.charsetNumber); +}; diff --git a/node_modules/mysql/lib/protocol/packets/ComPingPacket.js b/node_modules/mysql/lib/protocol/packets/ComPingPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..dd332c93cb42201f5a3311e21a393117fd3b9ffa --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/ComPingPacket.js @@ -0,0 +1,12 @@ +module.exports = ComPingPacket; +function ComPingPacket() { + this.command = 0x0e; +} + +ComPingPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.command); +}; + +ComPingPacket.prototype.parse = function(parser) { + this.command = parser.parseUnsignedNumber(1); +}; diff --git a/node_modules/mysql/lib/protocol/packets/ComQueryPacket.js b/node_modules/mysql/lib/protocol/packets/ComQueryPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..7ac191fd0a1abd5ddd1ceaf4c70959e6731c1bce --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/ComQueryPacket.js @@ -0,0 +1,15 @@ +module.exports = ComQueryPacket; +function ComQueryPacket(sql) { + this.command = 0x03; + this.sql = sql; +} + +ComQueryPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.command); + writer.writeString(this.sql); +}; + +ComQueryPacket.prototype.parse = function(parser) { + this.command = parser.parseUnsignedNumber(1); + this.sql = parser.parsePacketTerminatedString(); +}; diff --git a/node_modules/mysql/lib/protocol/packets/ComQuitPacket.js b/node_modules/mysql/lib/protocol/packets/ComQuitPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..1104061cb29cee10858660db16e493c06efc46e7 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/ComQuitPacket.js @@ -0,0 +1,12 @@ +module.exports = ComQuitPacket; +function ComQuitPacket() { + this.command = 0x01; +} + +ComQuitPacket.prototype.parse = function parse(parser) { + this.command = parser.parseUnsignedNumber(1); +}; + +ComQuitPacket.prototype.write = function write(writer) { + writer.writeUnsignedNumber(1, this.command); +}; diff --git a/node_modules/mysql/lib/protocol/packets/ComStatisticsPacket.js b/node_modules/mysql/lib/protocol/packets/ComStatisticsPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..5e3913e15e09f9272461b8e0dfbb2434262921e7 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/ComStatisticsPacket.js @@ -0,0 +1,12 @@ +module.exports = ComStatisticsPacket; +function ComStatisticsPacket() { + this.command = 0x09; +} + +ComStatisticsPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.command); +}; + +ComStatisticsPacket.prototype.parse = function(parser) { + this.command = parser.parseUnsignedNumber(1); +}; diff --git a/node_modules/mysql/lib/protocol/packets/EmptyPacket.js b/node_modules/mysql/lib/protocol/packets/EmptyPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..3d3410659971b21b0d83c3e3c0ed9acee770fb8d --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/EmptyPacket.js @@ -0,0 +1,6 @@ +module.exports = EmptyPacket; +function EmptyPacket() { +} + +EmptyPacket.prototype.write = function write() { +}; diff --git a/node_modules/mysql/lib/protocol/packets/EofPacket.js b/node_modules/mysql/lib/protocol/packets/EofPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..b80ca5ef22f0036e31add667da8d5f9567728c6d --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/EofPacket.js @@ -0,0 +1,25 @@ +module.exports = EofPacket; +function EofPacket(options) { + options = options || {}; + + this.fieldCount = undefined; + this.warningCount = options.warningCount; + this.serverStatus = options.serverStatus; + this.protocol41 = options.protocol41; +} + +EofPacket.prototype.parse = function(parser) { + this.fieldCount = parser.parseUnsignedNumber(1); + if (this.protocol41) { + this.warningCount = parser.parseUnsignedNumber(2); + this.serverStatus = parser.parseUnsignedNumber(2); + } +}; + +EofPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, 0xfe); + if (this.protocol41) { + writer.writeUnsignedNumber(2, this.warningCount); + writer.writeUnsignedNumber(2, this.serverStatus); + } +}; diff --git a/node_modules/mysql/lib/protocol/packets/ErrorPacket.js b/node_modules/mysql/lib/protocol/packets/ErrorPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..e03de00ce2b5ebb3fab5057f4b08058e6904499c --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/ErrorPacket.js @@ -0,0 +1,35 @@ +module.exports = ErrorPacket; +function ErrorPacket(options) { + options = options || {}; + + this.fieldCount = options.fieldCount; + this.errno = options.errno; + this.sqlStateMarker = options.sqlStateMarker; + this.sqlState = options.sqlState; + this.message = options.message; +} + +ErrorPacket.prototype.parse = function(parser) { + this.fieldCount = parser.parseUnsignedNumber(1); + this.errno = parser.parseUnsignedNumber(2); + + // sqlStateMarker ('#' = 0x23) indicates error packet format + if (parser.peak() === 0x23) { + this.sqlStateMarker = parser.parseString(1); + this.sqlState = parser.parseString(5); + } + + this.message = parser.parsePacketTerminatedString(); +}; + +ErrorPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, 0xff); + writer.writeUnsignedNumber(2, this.errno); + + if (this.sqlStateMarker) { + writer.writeString(this.sqlStateMarker); + writer.writeString(this.sqlState); + } + + writer.writeString(this.message); +}; diff --git a/node_modules/mysql/lib/protocol/packets/Field.js b/node_modules/mysql/lib/protocol/packets/Field.js new file mode 100644 index 0000000000000000000000000000000000000000..bb6336c1a4d96eac96bf4b97bbfa1e11969e64e2 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/Field.js @@ -0,0 +1,34 @@ +var Types = require('../constants/types'); + +module.exports = Field; +function Field(options) { + options = options || {}; + + this.parser = options.parser; + this.packet = options.packet; + this.db = options.packet.db; + this.table = options.packet.table; + this.name = options.packet.name; + this.type = typeToString(options.packet.type); + this.length = options.packet.length; +} + +Field.prototype.string = function () { + return this.parser.parseLengthCodedString(); +}; + +Field.prototype.buffer = function () { + return this.parser.parseLengthCodedBuffer(); +}; + +Field.prototype.geometry = function () { + return this.parser.parseGeometryValue(); +}; + +function typeToString(t) { + for (var k in Types) { + if (Types[k] === t) return k; + } + + return undefined; +} diff --git a/node_modules/mysql/lib/protocol/packets/FieldPacket.js b/node_modules/mysql/lib/protocol/packets/FieldPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..12cfed10c174f705ec8c8364782e9f54f1573b03 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/FieldPacket.js @@ -0,0 +1,93 @@ +module.exports = FieldPacket; +function FieldPacket(options) { + options = options || {}; + + this.catalog = options.catalog; + this.db = options.db; + this.table = options.table; + this.orgTable = options.orgTable; + this.name = options.name; + this.orgName = options.orgName; + this.charsetNr = options.charsetNr; + this.length = options.length; + this.type = options.type; + this.flags = options.flags; + this.decimals = options.decimals; + this.default = options.default; + this.zeroFill = options.zeroFill; + this.protocol41 = options.protocol41; +} + +FieldPacket.prototype.parse = function(parser) { + if (this.protocol41) { + this.catalog = parser.parseLengthCodedString(); + this.db = parser.parseLengthCodedString(); + this.table = parser.parseLengthCodedString(); + this.orgTable = parser.parseLengthCodedString(); + this.name = parser.parseLengthCodedString(); + this.orgName = parser.parseLengthCodedString(); + + if (parser.parseLengthCodedNumber() !== 0x0c) { + var err = new TypeError('Received invalid field length'); + err.code = 'PARSER_INVALID_FIELD_LENGTH'; + throw err; + } + + this.charsetNr = parser.parseUnsignedNumber(2); + this.length = parser.parseUnsignedNumber(4); + this.type = parser.parseUnsignedNumber(1); + this.flags = parser.parseUnsignedNumber(2); + this.decimals = parser.parseUnsignedNumber(1); + + var filler = parser.parseBuffer(2); + if (filler[0] !== 0x0 || filler[1] !== 0x0) { + var err = new TypeError('Received invalid filler'); + err.code = 'PARSER_INVALID_FILLER'; + throw err; + } + + // parsed flags + this.zeroFill = (this.flags & 0x0040 ? true : false); + + if (parser.reachedPacketEnd()) { + return; + } + + this.default = parser.parseLengthCodedString(); + } else { + this.table = parser.parseLengthCodedString(); + this.name = parser.parseLengthCodedString(); + this.length = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1)); + this.type = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1)); + } +}; + +FieldPacket.prototype.write = function(writer) { + if (this.protocol41) { + writer.writeLengthCodedString(this.catalog); + writer.writeLengthCodedString(this.db); + writer.writeLengthCodedString(this.table); + writer.writeLengthCodedString(this.orgTable); + writer.writeLengthCodedString(this.name); + writer.writeLengthCodedString(this.orgName); + + writer.writeLengthCodedNumber(0x0c); + writer.writeUnsignedNumber(2, this.charsetNr || 0); + writer.writeUnsignedNumber(4, this.length || 0); + writer.writeUnsignedNumber(1, this.type || 0); + writer.writeUnsignedNumber(2, this.flags || 0); + writer.writeUnsignedNumber(1, this.decimals || 0); + writer.writeFiller(2); + + if (this.default !== undefined) { + writer.writeLengthCodedString(this.default); + } + } else { + writer.writeLengthCodedString(this.table); + writer.writeLengthCodedString(this.name); + writer.writeUnsignedNumber(1, 0x01); + writer.writeUnsignedNumber(1, this.length); + writer.writeUnsignedNumber(1, 0x01); + writer.writeUnsignedNumber(1, this.type); + } +}; diff --git a/node_modules/mysql/lib/protocol/packets/HandshakeInitializationPacket.js b/node_modules/mysql/lib/protocol/packets/HandshakeInitializationPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..b2510633b807b91e3b9698f9778acde3b64069ef --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/HandshakeInitializationPacket.js @@ -0,0 +1,103 @@ +var Buffer = require('safe-buffer').Buffer; +var Client = require('../constants/client'); + +module.exports = HandshakeInitializationPacket; +function HandshakeInitializationPacket(options) { + options = options || {}; + + this.protocolVersion = options.protocolVersion; + this.serverVersion = options.serverVersion; + this.threadId = options.threadId; + this.scrambleBuff1 = options.scrambleBuff1; + this.filler1 = options.filler1; + this.serverCapabilities1 = options.serverCapabilities1; + this.serverLanguage = options.serverLanguage; + this.serverStatus = options.serverStatus; + this.serverCapabilities2 = options.serverCapabilities2; + this.scrambleLength = options.scrambleLength; + this.filler2 = options.filler2; + this.scrambleBuff2 = options.scrambleBuff2; + this.filler3 = options.filler3; + this.pluginData = options.pluginData; + this.protocol41 = options.protocol41; + + if (this.protocol41) { + // force set the bit in serverCapabilities1 + this.serverCapabilities1 |= Client.CLIENT_PROTOCOL_41; + } +} + +HandshakeInitializationPacket.prototype.parse = function(parser) { + this.protocolVersion = parser.parseUnsignedNumber(1); + this.serverVersion = parser.parseNullTerminatedString(); + this.threadId = parser.parseUnsignedNumber(4); + this.scrambleBuff1 = parser.parseBuffer(8); + this.filler1 = parser.parseFiller(1); + this.serverCapabilities1 = parser.parseUnsignedNumber(2); + this.serverLanguage = parser.parseUnsignedNumber(1); + this.serverStatus = parser.parseUnsignedNumber(2); + + this.protocol41 = (this.serverCapabilities1 & (1 << 9)) > 0; + + if (this.protocol41) { + this.serverCapabilities2 = parser.parseUnsignedNumber(2); + this.scrambleLength = parser.parseUnsignedNumber(1); + this.filler2 = parser.parseFiller(10); + // scrambleBuff2 should be 0x00 terminated, but sphinx does not do this + // so we assume scrambleBuff2 to be 12 byte and treat the next byte as a + // filler byte. + this.scrambleBuff2 = parser.parseBuffer(12); + this.filler3 = parser.parseFiller(1); + } else { + this.filler2 = parser.parseFiller(13); + } + + if (parser.reachedPacketEnd()) { + return; + } + + // According to the docs this should be 0x00 terminated, but MariaDB does + // not do this, so we assume this string to be packet terminated. + this.pluginData = parser.parsePacketTerminatedString(); + + // However, if there is a trailing '\0', strip it + var lastChar = this.pluginData.length - 1; + if (this.pluginData[lastChar] === '\0') { + this.pluginData = this.pluginData.substr(0, lastChar); + } +}; + +HandshakeInitializationPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.protocolVersion); + writer.writeNullTerminatedString(this.serverVersion); + writer.writeUnsignedNumber(4, this.threadId); + writer.writeBuffer(this.scrambleBuff1); + writer.writeFiller(1); + writer.writeUnsignedNumber(2, this.serverCapabilities1); + writer.writeUnsignedNumber(1, this.serverLanguage); + writer.writeUnsignedNumber(2, this.serverStatus); + if (this.protocol41) { + writer.writeUnsignedNumber(2, this.serverCapabilities2); + writer.writeUnsignedNumber(1, this.scrambleLength); + writer.writeFiller(10); + } + writer.writeNullTerminatedBuffer(this.scrambleBuff2); + + if (this.pluginData !== undefined) { + writer.writeNullTerminatedString(this.pluginData); + } +}; + +HandshakeInitializationPacket.prototype.scrambleBuff = function() { + var buffer = null; + + if (typeof this.scrambleBuff2 === 'undefined') { + buffer = Buffer.from(this.scrambleBuff1); + } else { + buffer = Buffer.allocUnsafe(this.scrambleBuff1.length + this.scrambleBuff2.length); + this.scrambleBuff1.copy(buffer, 0); + this.scrambleBuff2.copy(buffer, this.scrambleBuff1.length); + } + + return buffer; +}; diff --git a/node_modules/mysql/lib/protocol/packets/LocalDataFilePacket.js b/node_modules/mysql/lib/protocol/packets/LocalDataFilePacket.js new file mode 100644 index 0000000000000000000000000000000000000000..af7aaa045bb200c1f7e220eab8ecbfc82578b30b --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/LocalDataFilePacket.js @@ -0,0 +1,15 @@ +module.exports = LocalDataFilePacket; + +/** + * Create a new LocalDataFilePacket + * @constructor + * @param {Buffer} data The data contents of the packet + * @public + */ +function LocalDataFilePacket(data) { + this.data = data; +} + +LocalDataFilePacket.prototype.write = function(writer) { + writer.writeBuffer(this.data); +}; diff --git a/node_modules/mysql/lib/protocol/packets/OkPacket.js b/node_modules/mysql/lib/protocol/packets/OkPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..7caf3b0e7cbe1e2b1814aec8fceb62aa0e79be36 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/OkPacket.js @@ -0,0 +1,44 @@ + +// Language-neutral expression to match ER_UPDATE_INFO +var ER_UPDATE_INFO_REGEXP = /^[^:0-9]+: [0-9]+[^:0-9]+: ([0-9]+)[^:0-9]+: [0-9]+[^:0-9]*$/; + +module.exports = OkPacket; +function OkPacket(options) { + options = options || {}; + + this.fieldCount = undefined; + this.affectedRows = undefined; + this.insertId = undefined; + this.serverStatus = undefined; + this.warningCount = undefined; + this.message = undefined; + this.protocol41 = options.protocol41; +} + +OkPacket.prototype.parse = function(parser) { + this.fieldCount = parser.parseUnsignedNumber(1); + this.affectedRows = parser.parseLengthCodedNumber(); + this.insertId = parser.parseLengthCodedNumber(); + if (this.protocol41) { + this.serverStatus = parser.parseUnsignedNumber(2); + this.warningCount = parser.parseUnsignedNumber(2); + } + this.message = parser.parsePacketTerminatedString(); + this.changedRows = 0; + + var m = ER_UPDATE_INFO_REGEXP.exec(this.message); + if (m !== null) { + this.changedRows = parseInt(m[1], 10); + } +}; + +OkPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, 0x00); + writer.writeLengthCodedNumber(this.affectedRows || 0); + writer.writeLengthCodedNumber(this.insertId || 0); + if (this.protocol41) { + writer.writeUnsignedNumber(2, this.serverStatus || 0); + writer.writeUnsignedNumber(2, this.warningCount || 0); + } + writer.writeString(this.message); +}; diff --git a/node_modules/mysql/lib/protocol/packets/OldPasswordPacket.js b/node_modules/mysql/lib/protocol/packets/OldPasswordPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..1ff78ec1e09443ce4c0915a0af082ba771e8f84d --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/OldPasswordPacket.js @@ -0,0 +1,15 @@ +module.exports = OldPasswordPacket; +function OldPasswordPacket(options) { + options = options || {}; + + this.scrambleBuff = options.scrambleBuff; +} + +OldPasswordPacket.prototype.parse = function(parser) { + this.scrambleBuff = parser.parseNullTerminatedBuffer(); +}; + +OldPasswordPacket.prototype.write = function(writer) { + writer.writeBuffer(this.scrambleBuff); + writer.writeFiller(1); +}; diff --git a/node_modules/mysql/lib/protocol/packets/ResultSetHeaderPacket.js b/node_modules/mysql/lib/protocol/packets/ResultSetHeaderPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..25b8002226921a5c3e3762dae83b38015edc5f3d --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/ResultSetHeaderPacket.js @@ -0,0 +1,25 @@ +module.exports = ResultSetHeaderPacket; +function ResultSetHeaderPacket(options) { + options = options || {}; + + this.fieldCount = options.fieldCount; + this.extra = options.extra; +} + +ResultSetHeaderPacket.prototype.parse = function(parser) { + this.fieldCount = parser.parseLengthCodedNumber(); + + if (parser.reachedPacketEnd()) return; + + this.extra = (this.fieldCount === null) + ? parser.parsePacketTerminatedString() + : parser.parseLengthCodedNumber(); +}; + +ResultSetHeaderPacket.prototype.write = function(writer) { + writer.writeLengthCodedNumber(this.fieldCount); + + if (this.extra !== undefined) { + writer.writeLengthCodedNumber(this.extra); + } +}; diff --git a/node_modules/mysql/lib/protocol/packets/RowDataPacket.js b/node_modules/mysql/lib/protocol/packets/RowDataPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..8313f87fbcbdd29217992b771de5354094949c00 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/RowDataPacket.js @@ -0,0 +1,133 @@ +var Types = require('../constants/types'); +var Charsets = require('../constants/charsets'); +var Field = require('./Field'); +var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53); + +module.exports = RowDataPacket; +function RowDataPacket() { +} + +Object.defineProperty(RowDataPacket.prototype, 'parse', { + configurable : true, + enumerable : false, + value : parse +}); + +Object.defineProperty(RowDataPacket.prototype, '_typeCast', { + configurable : true, + enumerable : false, + value : typeCast +}); + +function parse(parser, fieldPackets, typeCast, nestTables, connection) { + var self = this; + var next = function () { + return self._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings, connection.config.dateStrings); + }; + + for (var i = 0; i < fieldPackets.length; i++) { + var fieldPacket = fieldPackets[i]; + var value; + + if (typeof typeCast === 'function') { + value = typeCast.apply(connection, [ new Field({ packet: fieldPacket, parser: parser }), next ]); + } else { + value = (typeCast) + ? this._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings, connection.config.dateStrings) + : ( (fieldPacket.charsetNr === Charsets.BINARY) + ? parser.parseLengthCodedBuffer() + : parser.parseLengthCodedString() ); + } + + if (typeof nestTables === 'string' && nestTables.length) { + this[fieldPacket.table + nestTables + fieldPacket.name] = value; + } else if (nestTables) { + this[fieldPacket.table] = this[fieldPacket.table] || {}; + this[fieldPacket.table][fieldPacket.name] = value; + } else { + this[fieldPacket.name] = value; + } + } +} + +function typeCast(field, parser, timeZone, supportBigNumbers, bigNumberStrings, dateStrings) { + var numberString; + + switch (field.type) { + case Types.TIMESTAMP: + case Types.TIMESTAMP2: + case Types.DATE: + case Types.DATETIME: + case Types.DATETIME2: + case Types.NEWDATE: + var dateString = parser.parseLengthCodedString(); + + if (typeMatch(field.type, dateStrings)) { + return dateString; + } + + if (dateString === null) { + return null; + } + + var originalString = dateString; + if (field.type === Types.DATE) { + dateString += ' 00:00:00'; + } + + if (timeZone !== 'local') { + dateString += ' ' + timeZone; + } + + var dt = new Date(dateString); + if (isNaN(dt.getTime())) { + return originalString; + } + + return dt; + case Types.TINY: + case Types.SHORT: + case Types.LONG: + case Types.INT24: + case Types.YEAR: + case Types.FLOAT: + case Types.DOUBLE: + numberString = parser.parseLengthCodedString(); + return (numberString === null || (field.zeroFill && numberString[0] === '0')) + ? numberString : Number(numberString); + case Types.NEWDECIMAL: + case Types.LONGLONG: + numberString = parser.parseLengthCodedString(); + return (numberString === null || (field.zeroFill && numberString[0] === '0')) + ? numberString + : ((supportBigNumbers && (bigNumberStrings || (Number(numberString) >= IEEE_754_BINARY_64_PRECISION) || Number(numberString) <= -IEEE_754_BINARY_64_PRECISION)) + ? numberString + : Number(numberString)); + case Types.BIT: + return parser.parseLengthCodedBuffer(); + case Types.STRING: + case Types.VAR_STRING: + case Types.TINY_BLOB: + case Types.MEDIUM_BLOB: + case Types.LONG_BLOB: + case Types.BLOB: + return (field.charsetNr === Charsets.BINARY) + ? parser.parseLengthCodedBuffer() + : parser.parseLengthCodedString(); + case Types.GEOMETRY: + return parser.parseGeometryValue(); + default: + return parser.parseLengthCodedString(); + } +} + +function typeMatch(type, list) { + if (Array.isArray(list)) { + for (var i = 0; i < list.length; i++) { + if (Types[list[i]] === type) return true; + } + return false; + } else { + return Boolean(list); + } +} diff --git a/node_modules/mysql/lib/protocol/packets/SSLRequestPacket.js b/node_modules/mysql/lib/protocol/packets/SSLRequestPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..a57cfc1a1f2ca9d79392727b2726d752ae49cc97 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/SSLRequestPacket.js @@ -0,0 +1,27 @@ +// http://dev.mysql.com/doc/internals/en/ssl.html +// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest + +var ClientConstants = require('../constants/client'); + +module.exports = SSLRequestPacket; + +function SSLRequestPacket(options) { + options = options || {}; + this.clientFlags = options.clientFlags | ClientConstants.CLIENT_SSL; + this.maxPacketSize = options.maxPacketSize; + this.charsetNumber = options.charsetNumber; +} + +SSLRequestPacket.prototype.parse = function(parser) { + // TODO: check SSLRequest packet v41 vs pre v41 + this.clientFlags = parser.parseUnsignedNumber(4); + this.maxPacketSize = parser.parseUnsignedNumber(4); + this.charsetNumber = parser.parseUnsignedNumber(1); +}; + +SSLRequestPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(4, this.clientFlags); + writer.writeUnsignedNumber(4, this.maxPacketSize); + writer.writeUnsignedNumber(1, this.charsetNumber); + writer.writeFiller(23); +}; diff --git a/node_modules/mysql/lib/protocol/packets/StatisticsPacket.js b/node_modules/mysql/lib/protocol/packets/StatisticsPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..5f70b3ba71608ff682f034db59707709eb1e558a --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/StatisticsPacket.js @@ -0,0 +1,20 @@ +module.exports = StatisticsPacket; +function StatisticsPacket() { + this.message = undefined; +} + +StatisticsPacket.prototype.parse = function(parser) { + this.message = parser.parsePacketTerminatedString(); + + var items = this.message.split(/\s\s/); + for (var i = 0; i < items.length; i++) { + var m = items[i].match(/^(.+)\:\s+(.+)$/); + if (m !== null) { + this[m[1].toLowerCase().replace(/\s/g, '_')] = Number(m[2]); + } + } +}; + +StatisticsPacket.prototype.write = function(writer) { + writer.writeString(this.message); +}; diff --git a/node_modules/mysql/lib/protocol/packets/UseOldPasswordPacket.js b/node_modules/mysql/lib/protocol/packets/UseOldPasswordPacket.js new file mode 100644 index 0000000000000000000000000000000000000000..d73bf44594d64dc665a3a07fc73832f5bef18bae --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/UseOldPasswordPacket.js @@ -0,0 +1,14 @@ +module.exports = UseOldPasswordPacket; +function UseOldPasswordPacket(options) { + options = options || {}; + + this.firstByte = options.firstByte || 0xfe; +} + +UseOldPasswordPacket.prototype.parse = function(parser) { + this.firstByte = parser.parseUnsignedNumber(1); +}; + +UseOldPasswordPacket.prototype.write = function(writer) { + writer.writeUnsignedNumber(1, this.firstByte); +}; diff --git a/node_modules/mysql/lib/protocol/packets/index.js b/node_modules/mysql/lib/protocol/packets/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f36b87bfbe7018e17560d81a7586b834ca8f64c4 --- /dev/null +++ b/node_modules/mysql/lib/protocol/packets/index.js @@ -0,0 +1,22 @@ +exports.AuthSwitchRequestPacket = require('./AuthSwitchRequestPacket'); +exports.AuthSwitchResponsePacket = require('./AuthSwitchResponsePacket'); +exports.ClientAuthenticationPacket = require('./ClientAuthenticationPacket'); +exports.ComChangeUserPacket = require('./ComChangeUserPacket'); +exports.ComPingPacket = require('./ComPingPacket'); +exports.ComQueryPacket = require('./ComQueryPacket'); +exports.ComQuitPacket = require('./ComQuitPacket'); +exports.ComStatisticsPacket = require('./ComStatisticsPacket'); +exports.EmptyPacket = require('./EmptyPacket'); +exports.EofPacket = require('./EofPacket'); +exports.ErrorPacket = require('./ErrorPacket'); +exports.Field = require('./Field'); +exports.FieldPacket = require('./FieldPacket'); +exports.HandshakeInitializationPacket = require('./HandshakeInitializationPacket'); +exports.LocalDataFilePacket = require('./LocalDataFilePacket'); +exports.OkPacket = require('./OkPacket'); +exports.OldPasswordPacket = require('./OldPasswordPacket'); +exports.ResultSetHeaderPacket = require('./ResultSetHeaderPacket'); +exports.RowDataPacket = require('./RowDataPacket'); +exports.SSLRequestPacket = require('./SSLRequestPacket'); +exports.StatisticsPacket = require('./StatisticsPacket'); +exports.UseOldPasswordPacket = require('./UseOldPasswordPacket'); diff --git a/node_modules/mysql/lib/protocol/sequences/ChangeUser.js b/node_modules/mysql/lib/protocol/sequences/ChangeUser.js new file mode 100644 index 0000000000000000000000000000000000000000..26be6dbbd353e8df8c42d32ce54cdf1776dd971e --- /dev/null +++ b/node_modules/mysql/lib/protocol/sequences/ChangeUser.js @@ -0,0 +1,41 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); +var Auth = require('../Auth'); + +module.exports = ChangeUser; +Util.inherits(ChangeUser, Sequence); +function ChangeUser(options, callback) { + Sequence.call(this, options, callback); + + this._user = options.user; + this._password = options.password; + this._database = options.database; + this._charsetNumber = options.charsetNumber; + this._currentConfig = options.currentConfig; +} + +ChangeUser.prototype.start = function(handshakeInitializationPacket) { + var scrambleBuff = handshakeInitializationPacket.scrambleBuff(); + scrambleBuff = Auth.token(this._password, scrambleBuff); + + var packet = new Packets.ComChangeUserPacket({ + user : this._user, + scrambleBuff : scrambleBuff, + database : this._database, + charsetNumber : this._charsetNumber + }); + + this._currentConfig.user = this._user; + this._currentConfig.password = this._password; + this._currentConfig.database = this._database; + this._currentConfig.charsetNumber = this._charsetNumber; + + this.emit('packet', packet); +}; + +ChangeUser.prototype['ErrorPacket'] = function(packet) { + var err = this._packetToError(packet); + err.fatal = true; + this.end(err); +}; diff --git a/node_modules/mysql/lib/protocol/sequences/Handshake.js b/node_modules/mysql/lib/protocol/sequences/Handshake.js new file mode 100644 index 0000000000000000000000000000000000000000..2881be8446999b7f1412f1d7bc652ea3bdbc39b7 --- /dev/null +++ b/node_modules/mysql/lib/protocol/sequences/Handshake.js @@ -0,0 +1,127 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); +var Auth = require('../Auth'); +var ClientConstants = require('../constants/client'); + +module.exports = Handshake; +Util.inherits(Handshake, Sequence); +function Handshake(options, callback) { + Sequence.call(this, options, callback); + + options = options || {}; + + this._config = options.config; + this._handshakeInitializationPacket = null; +} + +Handshake.prototype.determinePacket = function determinePacket(firstByte, parser) { + if (firstByte === 0xff) { + return Packets.ErrorPacket; + } + + if (!this._handshakeInitializationPacket) { + return Packets.HandshakeInitializationPacket; + } + + if (firstByte === 0xfe) { + return (parser.packetLength() === 1) + ? Packets.UseOldPasswordPacket + : Packets.AuthSwitchRequestPacket; + } + + return undefined; +}; + +Handshake.prototype['AuthSwitchRequestPacket'] = function (packet) { + if (packet.authMethodName === 'mysql_native_password') { + var challenge = packet.authMethodData.slice(0, 20); + + this.emit('packet', new Packets.AuthSwitchResponsePacket({ + data: Auth.token(this._config.password, challenge) + })); + } else { + var err = new Error( + 'MySQL is requesting the ' + packet.authMethodName + ' authentication method, which is not supported.' + ); + + err.code = 'UNSUPPORTED_AUTH_METHOD'; + err.fatal = true; + + this.end(err); + } +}; + +Handshake.prototype['HandshakeInitializationPacket'] = function(packet) { + this._handshakeInitializationPacket = packet; + + this._config.protocol41 = packet.protocol41; + + var serverSSLSupport = packet.serverCapabilities1 & ClientConstants.CLIENT_SSL; + + if (this._config.ssl) { + if (!serverSSLSupport) { + var err = new Error('Server does not support secure connection'); + + err.code = 'HANDSHAKE_NO_SSL_SUPPORT'; + err.fatal = true; + + this.end(err); + return; + } + + this._config.clientFlags |= ClientConstants.CLIENT_SSL; + this.emit('packet', new Packets.SSLRequestPacket({ + clientFlags : this._config.clientFlags, + maxPacketSize : this._config.maxPacketSize, + charsetNumber : this._config.charsetNumber + })); + this.emit('start-tls'); + } else { + this._sendCredentials(); + } +}; + +Handshake.prototype._tlsUpgradeCompleteHandler = function() { + this._sendCredentials(); +}; + +Handshake.prototype._sendCredentials = function() { + var packet = this._handshakeInitializationPacket; + this.emit('packet', new Packets.ClientAuthenticationPacket({ + clientFlags : this._config.clientFlags, + maxPacketSize : this._config.maxPacketSize, + charsetNumber : this._config.charsetNumber, + user : this._config.user, + database : this._config.database, + protocol41 : packet.protocol41, + scrambleBuff : (packet.protocol41) + ? Auth.token(this._config.password, packet.scrambleBuff()) + : Auth.scramble323(packet.scrambleBuff(), this._config.password) + })); +}; + +Handshake.prototype['UseOldPasswordPacket'] = function() { + if (!this._config.insecureAuth) { + var err = new Error( + 'MySQL server is requesting the old and insecure pre-4.1 auth mechanism. ' + + 'Upgrade the user password or use the {insecureAuth: true} option.' + ); + + err.code = 'HANDSHAKE_INSECURE_AUTH'; + err.fatal = true; + + this.end(err); + return; + } + + this.emit('packet', new Packets.OldPasswordPacket({ + scrambleBuff: Auth.scramble323(this._handshakeInitializationPacket.scrambleBuff(), this._config.password) + })); +}; + +Handshake.prototype['ErrorPacket'] = function(packet) { + var err = this._packetToError(packet, true); + err.fatal = true; + this.end(err); +}; diff --git a/node_modules/mysql/lib/protocol/sequences/Ping.js b/node_modules/mysql/lib/protocol/sequences/Ping.js new file mode 100644 index 0000000000000000000000000000000000000000..230f3c1aba8573ae01fd4416a0ec2a4996b7f591 --- /dev/null +++ b/node_modules/mysql/lib/protocol/sequences/Ping.js @@ -0,0 +1,19 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); + +module.exports = Ping; +Util.inherits(Ping, Sequence); + +function Ping(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + Sequence.call(this, options, callback); +} + +Ping.prototype.start = function() { + this.emit('packet', new Packets.ComPingPacket()); +}; diff --git a/node_modules/mysql/lib/protocol/sequences/Query.js b/node_modules/mysql/lib/protocol/sequences/Query.js new file mode 100644 index 0000000000000000000000000000000000000000..dd340abf73b130209e5078cae25baaed38608305 --- /dev/null +++ b/node_modules/mysql/lib/protocol/sequences/Query.js @@ -0,0 +1,218 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); +var ResultSet = require('../ResultSet'); +var ServerStatus = require('../constants/server_status'); +var fs = require('fs'); +var Readable = require('readable-stream'); + +module.exports = Query; +Util.inherits(Query, Sequence); +function Query(options, callback) { + Sequence.call(this, options, callback); + + this.sql = options.sql; + this.values = options.values; + this.typeCast = (options.typeCast === undefined) + ? true + : options.typeCast; + this.nestTables = options.nestTables || false; + + this._resultSet = null; + this._results = []; + this._fields = []; + this._index = 0; + this._loadError = null; +} + +Query.prototype.start = function() { + this.emit('packet', new Packets.ComQueryPacket(this.sql)); +}; + +Query.prototype.determinePacket = function determinePacket(byte, parser) { + var resultSet = this._resultSet; + + if (!resultSet) { + switch (byte) { + case 0x00: return Packets.OkPacket; + case 0xff: return Packets.ErrorPacket; + default: return Packets.ResultSetHeaderPacket; + } + } + + if (resultSet.eofPackets.length === 0) { + return (resultSet.fieldPackets.length < resultSet.resultSetHeaderPacket.fieldCount) + ? Packets.FieldPacket + : Packets.EofPacket; + } + + if (byte === 0xff) { + return Packets.ErrorPacket; + } + + if (byte === 0xfe && parser.packetLength() < 9) { + return Packets.EofPacket; + } + + return Packets.RowDataPacket; +}; + +Query.prototype['OkPacket'] = function(packet) { + // try...finally for exception safety + try { + if (!this._callback) { + this.emit('result', packet, this._index); + } else { + this._results.push(packet); + this._fields.push(undefined); + } + } finally { + this._index++; + this._resultSet = null; + this._handleFinalResultPacket(packet); + } +}; + +Query.prototype['ErrorPacket'] = function(packet) { + var err = this._packetToError(packet); + + var results = (this._results.length > 0) + ? this._results + : undefined; + + var fields = (this._fields.length > 0) + ? this._fields + : undefined; + + err.index = this._index; + err.sql = this.sql; + + this.end(err, results, fields); +}; + +Query.prototype['ResultSetHeaderPacket'] = function(packet) { + if (packet.fieldCount === null) { + this._sendLocalDataFile(packet.extra); + } else { + this._resultSet = new ResultSet(packet); + } +}; + +Query.prototype['FieldPacket'] = function(packet) { + this._resultSet.fieldPackets.push(packet); +}; + +Query.prototype['EofPacket'] = function(packet) { + this._resultSet.eofPackets.push(packet); + + if (this._resultSet.eofPackets.length === 1 && !this._callback) { + this.emit('fields', this._resultSet.fieldPackets, this._index); + } + + if (this._resultSet.eofPackets.length !== 2) { + return; + } + + if (this._callback) { + this._results.push(this._resultSet.rows); + this._fields.push(this._resultSet.fieldPackets); + } + + this._index++; + this._resultSet = null; + this._handleFinalResultPacket(packet); +}; + +Query.prototype._handleFinalResultPacket = function(packet) { + if (packet.serverStatus & ServerStatus.SERVER_MORE_RESULTS_EXISTS) { + return; + } + + var results = (this._results.length > 1) + ? this._results + : this._results[0]; + + var fields = (this._fields.length > 1) + ? this._fields + : this._fields[0]; + + this.end(this._loadError, results, fields); +}; + +Query.prototype['RowDataPacket'] = function(packet, parser, connection) { + packet.parse(parser, this._resultSet.fieldPackets, this.typeCast, this.nestTables, connection); + + if (this._callback) { + this._resultSet.rows.push(packet); + } else { + this.emit('result', packet, this._index); + } +}; + +Query.prototype._sendLocalDataFile = function(path) { + var self = this; + var localStream = fs.createReadStream(path, { + flag : 'r', + encoding : null, + autoClose : true + }); + + this.on('pause', function () { + localStream.pause(); + }); + + this.on('resume', function () { + localStream.resume(); + }); + + localStream.on('data', function (data) { + self.emit('packet', new Packets.LocalDataFilePacket(data)); + }); + + localStream.on('error', function (err) { + self._loadError = err; + localStream.emit('end'); + }); + + localStream.on('end', function () { + self.emit('packet', new Packets.EmptyPacket()); + }); +}; + +Query.prototype.stream = function(options) { + var self = this; + + options = options || {}; + options.objectMode = true; + + var stream = new Readable(options); + + stream._read = function() { + self._connection && self._connection.resume(); + }; + + stream.once('end', function() { + process.nextTick(function () { + stream.emit('close'); + }); + }); + + this.on('result', function(row, i) { + if (!stream.push(row)) self._connection.pause(); + stream.emit('result', row, i); // replicate old emitter + }); + + this.on('error', function(err) { + stream.emit('error', err); // Pass on any errors + }); + + this.on('end', function() { + stream.push(null); // pushing null, indicating EOF + }); + + this.on('fields', function(fields, i) { + stream.emit('fields', fields, i); // replicate old emitter + }); + + return stream; +}; diff --git a/node_modules/mysql/lib/protocol/sequences/Quit.js b/node_modules/mysql/lib/protocol/sequences/Quit.js new file mode 100644 index 0000000000000000000000000000000000000000..3c34c58205f0e1dfa818a3b4e5f36550416f9e00 --- /dev/null +++ b/node_modules/mysql/lib/protocol/sequences/Quit.js @@ -0,0 +1,40 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); + +module.exports = Quit; +Util.inherits(Quit, Sequence); +function Quit(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + Sequence.call(this, options, callback); + + this._started = false; +} + +Quit.prototype.end = function end(err) { + if (this._ended) { + return; + } + + if (!this._started) { + Sequence.prototype.end.call(this, err); + return; + } + + if (err && err.code === 'ECONNRESET' && err.syscall === 'read') { + // Ignore read errors after packet sent + Sequence.prototype.end.call(this); + return; + } + + Sequence.prototype.end.call(this, err); +}; + +Quit.prototype.start = function() { + this._started = true; + this.emit('packet', new Packets.ComQuitPacket()); +}; diff --git a/node_modules/mysql/lib/protocol/sequences/Sequence.js b/node_modules/mysql/lib/protocol/sequences/Sequence.js new file mode 100644 index 0000000000000000000000000000000000000000..de82dc270ceba918e83c6d8f6e5833d29283c171 --- /dev/null +++ b/node_modules/mysql/lib/protocol/sequences/Sequence.js @@ -0,0 +1,125 @@ +var Util = require('util'); +var EventEmitter = require('events').EventEmitter; +var Packets = require('../packets'); +var ErrorConstants = require('../constants/errors'); +var Timer = require('../Timer'); + +// istanbul ignore next: Node.js < 0.10 not covered +var listenerCount = EventEmitter.listenerCount + || function(emitter, type){ return emitter.listeners(type).length; }; + +var LONG_STACK_DELIMITER = '\n --------------------\n'; + +module.exports = Sequence; +Util.inherits(Sequence, EventEmitter); +function Sequence(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + EventEmitter.call(this); + + options = options || {}; + + this._callback = callback; + this._callSite = null; + this._ended = false; + this._timeout = options.timeout; + this._timer = new Timer(this); +} + +Sequence.determinePacket = function(byte) { + switch (byte) { + case 0x00: return Packets.OkPacket; + case 0xfe: return Packets.EofPacket; + case 0xff: return Packets.ErrorPacket; + default: return undefined; + } +}; + +Sequence.prototype.hasErrorHandler = function() { + return Boolean(this._callback) || listenerCount(this, 'error') > 1; +}; + +Sequence.prototype._packetToError = function(packet) { + var code = ErrorConstants[packet.errno] || 'UNKNOWN_CODE_PLEASE_REPORT'; + var err = new Error(code + ': ' + packet.message); + err.code = code; + err.errno = packet.errno; + + err.sqlMessage = packet.message; + err.sqlState = packet.sqlState; + + return err; +}; + +Sequence.prototype.end = function(err) { + if (this._ended) { + return; + } + + this._ended = true; + + if (err) { + this._addLongStackTrace(err); + } + + // Without this we are leaking memory. This problem was introduced in + // 8189925374e7ce3819bbe88b64c7b15abac96b16. I suspect that the error object + // causes a cyclic reference that the GC does not detect properly, but I was + // unable to produce a standalone version of this leak. This would be a great + // challenge for somebody interested in difficult problems : )! + this._callSite = null; + + // try...finally for exception safety + try { + if (err) { + this.emit('error', err); + } + } finally { + try { + if (this._callback) { + this._callback.apply(this, arguments); + } + } finally { + this.emit('end'); + } + } +}; + +Sequence.prototype['OkPacket'] = function(packet) { + this.end(null, packet); +}; + +Sequence.prototype['ErrorPacket'] = function(packet) { + this.end(this._packetToError(packet)); +}; + +// Implemented by child classes +Sequence.prototype.start = function() {}; + +Sequence.prototype._addLongStackTrace = function _addLongStackTrace(err) { + var callSiteStack = this._callSite && this._callSite.stack; + + if (!callSiteStack || typeof callSiteStack !== 'string') { + // No recorded call site + return; + } + + if (err.stack.indexOf(LONG_STACK_DELIMITER) !== -1) { + // Error stack already looks long + return; + } + + var index = callSiteStack.indexOf('\n'); + + if (index !== -1) { + // Append recorded call site + err.stack += LONG_STACK_DELIMITER + callSiteStack.substr(index + 1); + } +}; + +Sequence.prototype._onTimeout = function _onTimeout() { + this.emit('timeout'); +}; diff --git a/node_modules/mysql/lib/protocol/sequences/Statistics.js b/node_modules/mysql/lib/protocol/sequences/Statistics.js new file mode 100644 index 0000000000000000000000000000000000000000..c75b5d936a1adc3bf0ff2df5dd78caea2b038204 --- /dev/null +++ b/node_modules/mysql/lib/protocol/sequences/Statistics.js @@ -0,0 +1,30 @@ +var Sequence = require('./Sequence'); +var Util = require('util'); +var Packets = require('../packets'); + +module.exports = Statistics; +Util.inherits(Statistics, Sequence); +function Statistics(options, callback) { + if (!callback && typeof options === 'function') { + callback = options; + options = {}; + } + + Sequence.call(this, options, callback); +} + +Statistics.prototype.start = function() { + this.emit('packet', new Packets.ComStatisticsPacket()); +}; + +Statistics.prototype['StatisticsPacket'] = function (packet) { + this.end(null, packet); +}; + +Statistics.prototype.determinePacket = function determinePacket(firstByte) { + if (firstByte === 0x55) { + return Packets.StatisticsPacket; + } + + return undefined; +}; diff --git a/node_modules/mysql/lib/protocol/sequences/index.js b/node_modules/mysql/lib/protocol/sequences/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0eae5ce63bbdeb08ffe1b0fcfbf83448964b6236 --- /dev/null +++ b/node_modules/mysql/lib/protocol/sequences/index.js @@ -0,0 +1,7 @@ +exports.ChangeUser = require('./ChangeUser'); +exports.Handshake = require('./Handshake'); +exports.Ping = require('./Ping'); +exports.Query = require('./Query'); +exports.Quit = require('./Quit'); +exports.Sequence = require('./Sequence'); +exports.Statistics = require('./Statistics'); diff --git a/node_modules/mysql/package.json b/node_modules/mysql/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c69f6ecc8814293e3fe9797614f04727eae9edb6 --- /dev/null +++ b/node_modules/mysql/package.json @@ -0,0 +1,98 @@ +{ + "_from": "mysql@^2.14.1", + "_id": "mysql@2.16.0", + "_inBundle": false, + "_integrity": "sha512-dPbN2LHonQp7D5ja5DJXNbCLe/HRdu+f3v61aguzNRQIrmZLOeRoymBYyeThrR6ug+FqzDL95Gc9maqZUJS+Gw==", + "_location": "/mysql", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "mysql@^2.14.1", + "name": "mysql", + "escapedName": "mysql", + "rawSpec": "^2.14.1", + "saveSpec": null, + "fetchSpec": "^2.14.1" + }, + "_requiredBy": [ + "/promise-mysql" + ], + "_resolved": "https://registry.npmjs.org/mysql/-/mysql-2.16.0.tgz", + "_shasum": "b23b22ab5de44fc2d5d32bd4f5af6653fc45e2ba", + "_spec": "mysql@^2.14.1", + "_where": "/home/capsule_man/developpement/happy-botday/node_modules/promise-mysql", + "author": { + "name": "Felix Geisendörfer", + "email": "felix@debuggable.com", + "url": "http://debuggable.com/" + }, + "bugs": { + "url": "https://github.com/mysqljs/mysql/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Andrey Sidorov", + "email": "sidorares@yandex.ru" + }, + { + "name": "Bradley Grainger", + "email": "bgrainger@gmail.com" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Diogo Resende", + "email": "dresende@thinkdigital.pt" + }, + { + "name": "Nathan Woltman", + "email": "nwoltman@outlook.com" + } + ], + "dependencies": { + "bignumber.js": "4.1.0", + "readable-stream": "2.3.6", + "safe-buffer": "5.1.2", + "sqlstring": "2.3.1" + }, + "deprecated": false, + "description": "A node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.", + "devDependencies": { + "after": "0.8.2", + "eslint": "4.19.1", + "nyc": "10.3.2", + "seedrandom": "2.4.3", + "timezone-mock": "0.0.7", + "urun": "0.0.8", + "utest": "0.0.8" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "lib/", + "Changes.md", + "License", + "Readme.md", + "index.js" + ], + "homepage": "https://github.com/mysqljs/mysql#readme", + "license": "MIT", + "name": "mysql", + "repository": { + "type": "git", + "url": "git+https://github.com/mysqljs/mysql.git" + }, + "scripts": { + "lint": "eslint .", + "test": "node test/run.js", + "test-ci": "nyc --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node tool/version-changes.js && git add Changes.md" + }, + "version": "2.16.0" +} diff --git a/node_modules/mquery/node_modules/ms/license.md b/node_modules/promise-mysql/LICENSE similarity index 96% rename from node_modules/mquery/node_modules/ms/license.md rename to node_modules/promise-mysql/LICENSE index 69b61253a38926757b7de1d4df4880fc2105c2c9..b5d1ec33db562181b37c12fb1a849721bd3a0a05 100644 --- a/node_modules/mquery/node_modules/ms/license.md +++ b/node_modules/promise-mysql/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016 Zeit, Inc. +Copyright (c) 2014 Luke Bonaccorsi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -19,3 +19,4 @@ 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/promise-mysql/README.md b/node_modules/promise-mysql/README.md new file mode 100644 index 0000000000000000000000000000000000000000..97d7a916b2d8d64580bdb33058e9cfc56832452b --- /dev/null +++ b/node_modules/promise-mysql/README.md @@ -0,0 +1,211 @@ +Promise-mysql +================== +[](https://travis-ci.org/lukeb-uk/node-promise-mysql?branch=master) + +Promise-mysql is a wrapper for [mysqljs/mysql](https://github.com/mysqljs/mysql) that wraps function calls with [Bluebird](https://github.com/petkaantonov/bluebird/) promises. Usually this would be done with Bluebird's `.promisifyAll()` method, but mysqljs/mysql's footprint is different to that of what Bluebird expects. + +To install promise-mysql, use [npm](http://github.com/isaacs/npm): + +```bash +$ npm install promise-mysql +``` + +Please refer to [mysqljs/mysql](https://github.com/mysqljs/mysql) for documentation on how to use the mysql functions and refer to [Bluebird](https://github.com/petkaantonov/bluebird/) for documentation on Bluebird's promises + +At the minute only the standard connection (using `.createConnection()`) and the pool (using `.createPool()`) is supported. `createPoolCluster` is not implemented yet. + +## Examples + +### Connection + +**Important note: don't forget to call connection.end() when you're finished otherwise the Node process won't finish** + +To connect, you simply call `.createConnection()` like you would on mysqljs/mysql: +```javascript +var mysql = require('promise-mysql'); + +mysql.createConnection({ + host: 'localhost', + user: 'sauron', + password: 'theonetruering', + database: 'mordor' +}).then(function(conn){ + // do stuff with conn + conn.end(); +}); +``` + +To use the promise, you call the methods as you would if you were just using mysqljs/mysql, minus the callback. You then add a .then() with your function in: +```javascript +var mysql = require('promise-mysql'); + +mysql.createConnection({ + host: 'localhost', + user: 'sauron', + password: 'theonetruering', + database: 'mordor' +}).then(function(conn){ + var result = conn.query('select `name` from hobbits'); + conn.end(); + return result; +}).then(function(rows){ + // Logs out a list of hobbits + console.log(rows); +}); +``` + +You can even chain the promises, using a return within the .then(): +```javascript +var mysql = require('promise-mysql'); +var connection; + +mysql.createConnection({ + host: 'localhost', + user: 'sauron', + password: 'theonetruering', + database: 'mordor' +}).then(function(conn){ + connection = conn; + return connection.query('select `id` from hobbits where `name`="frodo"'); +}).then(function(rows){ + // Query the items for a ring that Frodo owns. + var result = connection.query('select * from items where `owner`="' + rows[0].id + '" and `name`="ring"'); + connection.end(); + return result; +}).then(function(rows){ + // Logs out a ring that Frodo owns + console.log(rows); +}); +``` + +You can catch errors using the .catch() method. You can still add .then() clauses, they'll just get skipped if there's an error +```javascript +var mysql = require('promise-mysql'); +var connection; + +mysql.createConnection({ + host: 'localhost', + user: 'sauron', + password: 'theonetruering', + database: 'mordor' +}).then(function(conn){ + connection = conn; + return connection.query('select * from tablethatdoesnotexist'); +}).then(function(){ + var result = connection.query('select * from hobbits'); + connection.end(); + return result; +}).catch(function(error){ + if (connection && connection.end) connection.end(); + //logs out the error + console.log(error); +}); + +``` + +### Pool + +Use pool directly: + +```javascript +pool = mysql.createPool({ + host: 'localhost', + user: 'sauron', + password: 'theonetruering', + database: 'mordor', + connectionLimit: 10 +}); + +pool.query('select `name` from hobbits').then(function(rows){ + // Logs out a list of hobbits + console.log(rows); +}); + +``` + +Get a connection from the pool: + +```javascript +pool.getConnection().then(function(connection) { + connection.query('select `name` from hobbits').then(...) +}).catch(function(err) { + done(err); +}); +``` + +#### Using/Disposer Pattern with Pool +Example implementing a using/disposer pattern using Bluebird's built-in `using` and `disposer` functions. + +databaseConnection.js: +```javascript +var mysql = require('promise-mysql'); + +pool = mysql.createPool({ + host: 'localhost', + user: 'sauron', + password: 'theonetruering', + database: 'mordor', + connectionLimit: 10 +}); + +function getSqlConnection() { + return pool.getConnection().disposer(function(connection) { + pool.releaseConnection(connection); + }); +} + +module.exports = getSqlConnection; +``` + +sqlQuery.js: +```javascript +var Promise = require("bluebird"); +var getSqlConnection = require('./databaseConnection'); +Promise.using(getSqlConnection(), function(connection) { + return connection.query('select `name` from hobbits').then(function(rows) { + return console.log(rows); + }).catch(function(error) { + console.log(error); + }); +}) +``` + + +## Tests + +At the moment only simple basics tests are implemented using Mocha. +To run the tests, you need to connect to a running MySQL server. A database or write permissions are not required. + +If you have docker, you can run a docker container bound to the mysql port with the command: +```bash +docker run -p 3306:3306 --name mysql_container -e MYSQL_ROOT_PASSWORD=password -d mysql +``` + +Start the test suite with + +```bash +DB_HOST=localhost DB_USER=user DB_PWD=pwd npm test +``` + +## License + +The MIT License (MIT) + +Copyright (c) 2014 Luke Bonaccorsi + +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/promise-mysql/index.d.ts b/node_modules/promise-mysql/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5b671c44ba55062539c4856f819746b8c5a72c4 --- /dev/null +++ b/node_modules/promise-mysql/index.d.ts @@ -0,0 +1,76 @@ +import * as mysql from 'mysql'; +import * as Bluebird from 'bluebird'; + +export function createConnection(connectionUri: string | mysql.ConnectionConfig): Bluebird<Connection>; + +export function createPool(config: mysql.PoolConfig | string): Pool; + +export { Types, escape, escapeId, format, ConnectionOptions, ConnectionConfig, PoolConfig } from 'mysql'; + +export interface QueryFunction { + (query: mysql.Query | string | mysql.QueryOptions): Bluebird<any>; + + (options: string, values: any): Bluebird<any>; +} + +export interface Connection { + query: QueryFunction; + + beginTransaction(options?: mysql.QueryOptions): Bluebird<void>; + + commit(options?: mysql.QueryOptions): Bluebird<void>; + + rollback(options?: mysql.QueryOptions): Bluebird<void>; + + changeUser(options?: mysql.ConnectionOptions): Bluebird<void>; + + ping(options?: mysql.QueryOptions): Bluebird<void>; + + queryStream(sql: string, values: any): mysql.Query; + + statistics(options?: mysql.QueryOptions): Bluebird<void>; + + end(options?: mysql.QueryOptions): Bluebird<void>; + + destroy(): void; + + pause(): void; + + resume(): void; + + escape(value: any, stringifyObjects?: boolean, timeZone?: string): string; + + escapeId(value: string, forbidQualified?: boolean): string; + + format(sql: string, values: any[], stringifyObjects?: boolean, timeZone?: string): string; +} + +export interface PoolConnection extends Connection { + release(): any; + + destroy(): any; +} + +export interface Pool { + getConnection(): Bluebird<PoolConnection>; + + releaseConnection(connection: PoolConnection): void; + + query: QueryFunction; + + end(options?: mysql.QueryOptions): Bluebird<void>; + + release(options?: mysql.QueryOptions): Bluebird<void>; + + escape(value: any, stringifyObjects?: boolean, timeZone?: string): string; + + escapeId(value: string, forbidQualified?: boolean): string; + + on(ev: 'connection' | 'acquire' | 'release', callback: (connection: mysql.PoolConnection) => void): mysql.Pool; + + on(ev: 'error', callback: (err: mysql.MysqlError) => void): mysql.Pool; + + on(ev: 'enqueue', callback: (err?: mysql.MysqlError) => void): mysql.Pool; + + on(ev: string, callback: (...args: any[]) => void): mysql.Pool; +} diff --git a/node_modules/promise-mysql/index.js b/node_modules/promise-mysql/index.js new file mode 100644 index 0000000000000000000000000000000000000000..12d5e07cc8c3558b5adb00ec63d52872a08ad1a6 --- /dev/null +++ b/node_modules/promise-mysql/index.js @@ -0,0 +1,16 @@ +var Connection = require('./lib/connection.js'); +var Pool = require('./lib/pool.js'); +var mysql = require('mysql'); + +exports.createConnection = function(config){ + return new Connection(config); +} + +exports.createPool = function(config){ + return new Pool(config); +} + +exports.Types = mysql.Types; +exports.escape = mysql.escape; +exports.escapeId = mysql.escapeId; +exports.format = mysql.format; diff --git a/node_modules/promise-mysql/lib/connection.js b/node_modules/promise-mysql/lib/connection.js new file mode 100644 index 0000000000000000000000000000000000000000..0d2e37bf1cd79fae9d1916a64f1a7f181b650820 --- /dev/null +++ b/node_modules/promise-mysql/lib/connection.js @@ -0,0 +1,123 @@ +var Promise = require('bluebird'), + mysql = require('mysql'), + promiseCallback = require('./helper').promiseCallback; + +/** +* Constructor +* @param {object} config - The configuration object +* @param {object} _connection - Mysql-Connection, only used internaly by the pool object +*/ +var connection = function(config, _connection){ + var self = this, + connect = function(resolve, reject) { + if (_connection) { + self.connection = _connection; + resolve(); + } else { + self.connection = mysql.createConnection(self.config); + self.connection.connect( + function(err){ + if (err) { + self.connection.err = err; + if (typeof reject === 'function') { + return reject(err); + } else { + setTimeout(function(){ + connect(); + }, 2000); + return; + } + } else { + delete self.connection.err; + if (typeof resolve === 'function') { + return resolve(); + } + } + } + ); + + self.connection.on('error', function(err) { + console.log('db error', err); + self.connection.err = err; + if(err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'ECONNRESET' || err.code === 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR') { + connect(); + } + }); + } + }; + + this.config = config; + + return new Promise(function(resolve, reject) { + connect( + function(){ + return resolve(self); + }, + function(err){ + return reject(err); + } + ); + }); +} + +connection.prototype.query = function(sql, values) { + return promiseCallback.apply(this.connection, ['query', arguments]); +}; + +connection.prototype.queryStream = function(sql, values) { + return this.connection.query(sql, values); +}; + +connection.prototype.beginTransaction = function() { + return promiseCallback.apply(this.connection, ['beginTransaction', arguments]); +}; + +connection.prototype.commit = function() { + return promiseCallback.apply(this.connection, ['commit', arguments]); +}; + +connection.prototype.rollback = function() { + return promiseCallback.apply(this.connection, ['rollback', arguments]); +}; + +connection.prototype.changeUser = function(data) { + return promiseCallback.apply(this.connection, ['changeUser', arguments]); +}; + +connection.prototype.ping = function(data) { + return promiseCallback.apply(this.connection, ['ping', arguments]); +}; + +connection.prototype.statistics = function(data) { + return promiseCallback.apply(this.connection, ['statistics', arguments]); +}; + +connection.prototype.end = function(data) { + return promiseCallback.apply(this.connection, ['end', arguments]); +}; + +connection.prototype.destroy = function() { + this.connection.destroy(); +}; + +connection.prototype.pause = function() { + this.connection.pause(); +}; + +connection.prototype.resume = function() { + this.connection.resume(); +}; + +connection.prototype.escape = function(value) { + return this.connection.escape(value); +}; + +connection.prototype.escapeId = function(value) { + return this.connection.escapeId(value); +}; + +connection.prototype.format = function(sql, values) { + return this.connection.format(sql, values); +}; + +module.exports = connection; diff --git a/node_modules/promise-mysql/lib/helper.js b/node_modules/promise-mysql/lib/helper.js new file mode 100644 index 0000000000000000000000000000000000000000..47d0db0e9eae45cd9f31ffaabdcc7bfe3351a828 --- /dev/null +++ b/node_modules/promise-mysql/lib/helper.js @@ -0,0 +1,22 @@ +var Promise = require('bluebird'); + +var promiseCallback = function(functionName, params) { + var self = this; + params = Array.prototype.slice.call(params, 0); + return new Promise(function(resolve, reject) { + params.push(function(err) { + var args = Array.prototype.slice.call(arguments, 1); + if (err) { + return reject(err); + } + + return resolve.apply(this, args); + }); + + self[functionName].apply(self, params); + }); +}; + +module.exports = { + promiseCallback: promiseCallback, +}; diff --git a/node_modules/promise-mysql/lib/pool.js b/node_modules/promise-mysql/lib/pool.js new file mode 100644 index 0000000000000000000000000000000000000000..764b43c9c89a78a7641da85c0fa701840e554545 --- /dev/null +++ b/node_modules/promise-mysql/lib/pool.js @@ -0,0 +1,45 @@ +var mysql = require('mysql'), + PoolConnection = require('./poolConnection.js'), + promiseCallback = require('./helper').promiseCallback; + +var pool = function(config) { + this.pool = mysql.createPool(config); +}; + +pool.prototype.getConnection = function getConnection() { + return promiseCallback.apply(this.pool, ['getConnection', arguments]) + .then(function(con) { + return new PoolConnection(con); + }); +}; + +pool.prototype.releaseConnection = function releaseConnection(connection) { + //Use the underlying connection from the mysql-module here: + return this.pool.releaseConnection(connection.connection); +}; + +pool.prototype.query = function(sql, values) { + return promiseCallback.apply(this.pool, ['query', arguments]); +}; + +pool.prototype.end = function(data) { + return promiseCallback.apply(this.pool, ['end', arguments]); +}; + +pool.prototype.release = function(data) { + return promiseCallback.apply(this.pool, ['release', arguments]); +}; + +pool.prototype.escape = function(value) { + return this.pool.escape(value); +}; + +pool.prototype.escapeId = function(value) { + return this.pool.escapeId(value); +}; + +pool.prototype.on = function(event, fn) { + this.pool.on(event, fn); +}; + +module.exports = pool; diff --git a/node_modules/promise-mysql/lib/poolConnection.js b/node_modules/promise-mysql/lib/poolConnection.js new file mode 100644 index 0000000000000000000000000000000000000000..447bf15951fc921b4f68fefe5de0a5b7d04f3b40 --- /dev/null +++ b/node_modules/promise-mysql/lib/poolConnection.js @@ -0,0 +1,21 @@ +var Connection = require('./connection.js'), + inherits = require('util').inherits, + promiseCallback = require('./helper').promiseCallback; + +var poolConnection = function(_connection) { + this.connection = _connection; + + Connection.call(this, null, _connection) +} + +inherits(poolConnection, Connection); + +poolConnection.prototype.release = function() { + this.connection.release(); +}; + +poolConnection.prototype.destroy = function() { + this.connection.destroy(); +}; + +module.exports = poolConnection; diff --git a/node_modules/promise-mysql/package.json b/node_modules/promise-mysql/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bab166398ec10d3008d19b961a5b30ebe5a7d4fa --- /dev/null +++ b/node_modules/promise-mysql/package.json @@ -0,0 +1,77 @@ +{ + "_from": "promise-mysql", + "_id": "promise-mysql@3.3.1", + "_inBundle": false, + "_integrity": "sha512-PE+J6TtAqMJpdREvSphKvd+pn0IgGiLgxaDBb12oZNBR1VSxYSzknveuiSBmkptZC1ZDRwU+zBxBJeBgGFkCRA==", + "_location": "/promise-mysql", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "promise-mysql", + "name": "promise-mysql", + "escapedName": "promise-mysql", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/promise-mysql/-/promise-mysql-3.3.1.tgz", + "_shasum": "31ad1bbff065a9f2abb2627294502c98045d3d16", + "_spec": "promise-mysql", + "_where": "/home/capsule_man/developpement/happy-botday", + "author": { + "name": "Luke Bonaccorsi" + }, + "bugs": { + "url": "https://github.com/lukeb-uk/node-promise-mysql/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@types/bluebird": "^3.5.19", + "@types/mysql": "^2.15.2", + "bluebird": "^3.5.0", + "mysql": "^2.14.1" + }, + "deprecated": false, + "description": "A bluebird wrapper for node-mysql", + "devDependencies": { + "chai": "^4.0.1", + "mocha": "^5.0.0" + }, + "homepage": "https://github.com/lukeb-uk/node-promise-mysql#readme", + "keywords": [ + "promise", + "performance", + "promises", + "promises-a", + "promises-aplus", + "async", + "await", + "deferred", + "deferreds", + "future", + "flow control", + "dsl", + "fluent interface", + "database", + "mysql", + "mysql-promise", + "bluebird", + "q" + ], + "license": "MIT", + "main": "index.js", + "name": "promise-mysql", + "repository": { + "type": "git", + "url": "git+https://github.com/lukeb-uk/node-promise-mysql.git" + }, + "scripts": { + "test": "mocha --exit" + }, + "version": "3.3.1" +} diff --git a/node_modules/regexp-clone/.npmignore b/node_modules/regexp-clone/.npmignore deleted file mode 100644 index be106cacde1aeeb93d8964b399961636df72e8fc..0000000000000000000000000000000000000000 --- a/node_modules/regexp-clone/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.sw* -node_modules/ diff --git a/node_modules/regexp-clone/.travis.yml b/node_modules/regexp-clone/.travis.yml deleted file mode 100644 index 58f23716aefb940d7d7ea44c1f3004416ac5f065..0000000000000000000000000000000000000000 --- a/node_modules/regexp-clone/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - 0.10 diff --git a/node_modules/regexp-clone/History.md b/node_modules/regexp-clone/History.md deleted file mode 100644 index 0beedfc354046212ee8de1b32e44a555289fffd6..0000000000000000000000000000000000000000 --- a/node_modules/regexp-clone/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.0.1 / 2013-04-17 -================== - - * initial commit diff --git a/node_modules/regexp-clone/LICENSE b/node_modules/regexp-clone/LICENSE deleted file mode 100644 index 98c7c8983953cd4121f84217622565a655a5fb1f..0000000000000000000000000000000000000000 --- a/node_modules/regexp-clone/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2013 [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/regexp-clone/Makefile b/node_modules/regexp-clone/Makefile deleted file mode 100644 index 6c8fb751677818fb46d2b4bcf70ce67c4b2c620f..0000000000000000000000000000000000000000 --- a/node_modules/regexp-clone/Makefile +++ /dev/null @@ -1,5 +0,0 @@ - -test: - @./node_modules/.bin/mocha $(T) --async-only $(TESTS) - -.PHONY: test diff --git a/node_modules/regexp-clone/README.md b/node_modules/regexp-clone/README.md deleted file mode 100644 index 2aabe5c6ffced608710a3643d20df6d2a3b5c13e..0000000000000000000000000000000000000000 --- a/node_modules/regexp-clone/README.md +++ /dev/null @@ -1,18 +0,0 @@ -#regexp-clone -============== - -Clones RegExps with flag preservation - -```js -var regexpClone = require('regexp-clone'); - -var a = /somethin/g; -console.log(a.global); // true - -var b = regexpClone(a); -console.log(b.global); // true -``` - -## License - -[MIT](https://github.com/aheckmann/regexp-clone/blob/master/LICENSE) diff --git a/node_modules/regexp-clone/index.js b/node_modules/regexp-clone/index.js deleted file mode 100644 index e5850ca5f4997aeca86d135f4c229754162d97fc..0000000000000000000000000000000000000000 --- a/node_modules/regexp-clone/index.js +++ /dev/null @@ -1,20 +0,0 @@ - -var toString = Object.prototype.toString; - -function isRegExp (o) { - return 'object' == typeof o - && '[object RegExp]' == toString.call(o); -} - -module.exports = exports = function (regexp) { - if (!isRegExp(regexp)) { - throw new TypeError('Not a RegExp'); - } - - var flags = []; - if (regexp.global) flags.push('g'); - if (regexp.multiline) flags.push('m'); - if (regexp.ignoreCase) flags.push('i'); - return new RegExp(regexp.source, flags.join('')); -} - diff --git a/node_modules/regexp-clone/package.json b/node_modules/regexp-clone/package.json deleted file mode 100644 index 51ae8945dc7080efa8dede98ba7f2500a8c00c34..0000000000000000000000000000000000000000 --- a/node_modules/regexp-clone/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "_from": "regexp-clone@0.0.1", - "_id": "regexp-clone@0.0.1", - "_inBundle": false, - "_integrity": "sha1-p8LgmJH9vzj7sQ03b7cwA+aKxYk=", - "_location": "/regexp-clone", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "regexp-clone@0.0.1", - "name": "regexp-clone", - "escapedName": "regexp-clone", - "rawSpec": "0.0.1", - "saveSpec": null, - "fetchSpec": "0.0.1" - }, - "_requiredBy": [ - "/mongoose", - "/mquery" - ], - "_resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz", - "_shasum": "a7c2e09891fdbf38fbb10d376fb73003e68ac589", - "_spec": "regexp-clone@0.0.1", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongoose", - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "bugs": { - "url": "https://github.com/aheckmann/regexp-clone/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Clone RegExps with options", - "devDependencies": { - "mocha": "1.8.1" - }, - "homepage": "https://github.com/aheckmann/regexp-clone#readme", - "keywords": [ - "RegExp", - "clone" - ], - "license": "MIT", - "main": "index.js", - "name": "regexp-clone", - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/regexp-clone.git" - }, - "scripts": { - "test": "make test" - }, - "version": "0.0.1" -} diff --git a/node_modules/regexp-clone/test/index.js b/node_modules/regexp-clone/test/index.js deleted file mode 100644 index 264a77629f3549c133f8dcc96a23ded77abe50bf..0000000000000000000000000000000000000000 --- a/node_modules/regexp-clone/test/index.js +++ /dev/null @@ -1,112 +0,0 @@ - -var assert = require('assert') -var clone = require('../'); - -describe('regexp-clone', function(){ - function hasEqualSource (a, b) { - assert.ok(a !== b); - assert.equal(a.source, b.source); - } - - function isInsensitive (a) { - assert.ok(a.ignoreCase); - } - - function isGlobal (a) { - assert.ok(a.global); - } - - function isMultiline (a) { - assert.ok(a.multiline); - } - - function insensitiveFlag (a) { - var b = clone(a); - hasEqualSource(a, b); - isInsensitive(a); - isInsensitive(b); - } - - function globalFlag (a) { - var b = clone(a); - hasEqualSource(a, b); - isGlobal(a); - isGlobal(b); - } - - function multilineFlag (a) { - var b = clone(a); - hasEqualSource(a, b); - isMultiline(a); - isMultiline(b); - } - - describe('literals', function(){ - it('insensitive flag', function(done){ - var a = /hello/i; - insensitiveFlag(a); - done(); - }) - it('global flag', function(done){ - var a = /hello/g; - globalFlag(a); - done(); - }) - it('multiline flag', function(done){ - var a = /hello/m; - multilineFlag(a); - done(); - }) - it('no flags', function(done){ - var a = /hello/; - var b = clone(a); - hasEqualSource(a, b); - assert.ok(!a.insensitive); - assert.ok(!a.global); - assert.ok(!a.global); - done(); - }) - it('all flags', function(done){ - var a = /hello/gim; - insensitiveFlag(a); - globalFlag(a); - multilineFlag(a); - done(); - }) - }) - - describe('instances', function(){ - it('insensitive flag', function(done){ - var a = new RegExp('hello', 'i'); - insensitiveFlag(a); - done(); - }) - it('global flag', function(done){ - var a = new RegExp('hello', 'g'); - globalFlag(a); - done(); - }) - it('multiline flag', function(done){ - var a = new RegExp('hello', 'm'); - multilineFlag(a); - done(); - }) - it('no flags', function(done){ - var a = new RegExp('hmm'); - var b = clone(a); - hasEqualSource(a, b); - assert.ok(!a.insensitive); - assert.ok(!a.global); - assert.ok(!a.global); - done(); - }) - it('all flags', function(done){ - var a = new RegExp('hello', 'gim'); - insensitiveFlag(a); - globalFlag(a); - multilineFlag(a); - done(); - }) - }) -}) - diff --git a/node_modules/require_optional/.npmignore b/node_modules/require_optional/.npmignore deleted file mode 100644 index e920c16718d133a2ef272e4b57b512739ecb002f..0000000000000000000000000000000000000000 --- a/node_modules/require_optional/.npmignore +++ /dev/null @@ -1,33 +0,0 @@ -# Logs -logs -*.log -npm-debug.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 - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directory -node_modules - -# Optional npm cache directory -.npm - -# Optional REPL history -.node_repl_history diff --git a/node_modules/require_optional/.travis.yml b/node_modules/require_optional/.travis.yml deleted file mode 100644 index 72903c34aff420b083b5ef4ccc2363291de9a2de..0000000000000000000000000000000000000000 --- a/node_modules/require_optional/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: node_js -node_js: - - "0.10" - - "0.12" - - "4" - - "6" - - "7" - - "8" -sudo: false diff --git a/node_modules/require_optional/HISTORY.md b/node_modules/require_optional/HISTORY.md deleted file mode 100644 index 7bee02fc0a7477e131956a56686054b8d55757f5..0000000000000000000000000000000000000000 --- a/node_modules/require_optional/HISTORY.md +++ /dev/null @@ -1,7 +0,0 @@ -1.0.1 03-02-2016 -================ -* Fix dependency resolution issue when a component in peerOptionalDependencies is installed at the level of the module declaring in peerOptionalDependencies. - -1.0.0 03-02-2016 -================ -* Initial release allowing us to optionally resolve dependencies in the package.json file under the peerOptionalDependencies tag. \ No newline at end of file diff --git a/node_modules/require_optional/LICENSE b/node_modules/require_optional/LICENSE deleted file mode 100644 index 8dada3edaf50dbc082c9a125058f25def75e625a..0000000000000000000000000000000000000000 --- a/node_modules/require_optional/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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/require_optional/README.md b/node_modules/require_optional/README.md deleted file mode 100644 index c0323f065db3b5412097d25e73093ad7f2811b17..0000000000000000000000000000000000000000 --- a/node_modules/require_optional/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# require_optional -Work around the problem that we do not have a optionalPeerDependencies concept in node.js making it a hassle to optionally include native modules diff --git a/node_modules/require_optional/index.js b/node_modules/require_optional/index.js deleted file mode 100644 index 3710319feb36beef46f85dbfb9efbb5f203d55d3..0000000000000000000000000000000000000000 --- a/node_modules/require_optional/index.js +++ /dev/null @@ -1,128 +0,0 @@ -var path = require('path'), - fs = require('fs'), - f = require('util').format, - resolveFrom = require('resolve-from'), - semver = require('semver'); - -var exists = fs.existsSync || path.existsSync; - -// Find the location of a package.json file near or above the given location -var find_package_json = function(location) { - var found = false; - - while(!found) { - if (exists(location + '/package.json')) { - found = location; - } else if (location !== '/') { - location = path.dirname(location); - } else { - return false; - } - } - - return location; -} - -// Find the package.json object of the module closest up the module call tree that contains name in that module's peerOptionalDependencies -var find_package_json_with_name = function(name) { - // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies - var currentModule = module; - var found = false; - while (currentModule) { - // Check currentModule has a package.json - location = currentModule.filename; - var location = find_package_json(location) - if (!location) { - currentModule = currentModule.parent; - continue; - } - - // Read the package.json file - var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); - // Is the name defined by interal file references - var parts = name.split(/\//); - - // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for - if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { - currentModule = currentModule.parent; - continue; - } - found = true; - break; - } - - // Check whether name has been found in currentModule's peerOptionalDependencies - if (!found) { - throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); - } - - return { - object: object, - parts: parts - } -} - -var require_optional = function(name, options) { - options = options || {}; - options.strict = typeof options.strict == 'boolean' ? options.strict : true; - - var res = find_package_json_with_name(name) - var object = res.object; - var parts = res.parts; - - // Unpack the expected version - var expectedVersions = object.peerOptionalDependencies[parts[0]]; - // The resolved package - var moduleEntry = undefined; - // Module file - var moduleEntryFile = name; - - try { - // Validate if it's possible to read the module - moduleEntry = require(moduleEntryFile); - } catch(err) { - // Attempt to resolve in top level package - try { - // Get the module entry file - moduleEntryFile = resolveFrom(process.cwd(), name); - if(moduleEntryFile == null) return undefined; - // Attempt to resolve the module - moduleEntry = require(moduleEntryFile); - } catch(err) { - if(err.code === 'MODULE_NOT_FOUND') return undefined; - } - } - - // Resolve the location of the module's package.json file - var location = find_package_json(require.resolve(moduleEntryFile)); - if(!location) { - throw new Error('package.json can not be located'); - } - - // Read the module file - var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); - // Get the version - var version = dependentOnModule.version; - // Validate if the found module satisfies the version id - if(semver.satisfies(version, expectedVersions) == false - && options.strict) { - var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); - error.code = 'OPTIONAL_MODULE_NOT_FOUND'; - throw error; - } - - // Satifies the module requirement - return moduleEntry; -} - -require_optional.exists = function(name) { - try { - var m = require_optional(name); - if(m === undefined) return false; - return true; - } catch(err) { - return false; - } -} - -module.exports = require_optional; diff --git a/node_modules/require_optional/package.json b/node_modules/require_optional/package.json deleted file mode 100644 index 1b49ef1dd7af4bbcb236547f971a3e4669607c35..0000000000000000000000000000000000000000 --- a/node_modules/require_optional/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "_from": "require_optional@^1.0.1", - "_id": "require_optional@1.0.1", - "_inBundle": false, - "_integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", - "_location": "/require_optional", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "require_optional@^1.0.1", - "name": "require_optional", - "escapedName": "require_optional", - "rawSpec": "^1.0.1", - "saveSpec": null, - "fetchSpec": "^1.0.1" - }, - "_requiredBy": [ - "/mongodb-core" - ], - "_resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", - "_shasum": "4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e", - "_spec": "require_optional@^1.0.1", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongodb-core", - "author": { - "name": "Christian Kvalheim Amor" - }, - "bugs": { - "url": "https://github.com/christkv/require_optional/issues" - }, - "bundleDependencies": false, - "dependencies": { - "resolve-from": "^2.0.0", - "semver": "^5.1.0" - }, - "deprecated": false, - "description": "Allows you declare optionalPeerDependencies that can be satisfied by the top level module but ignored if they are not.", - "devDependencies": { - "bson": "0.4.21", - "co": "4.6.0", - "es6-promise": "^3.0.2", - "mocha": "^2.4.5" - }, - "homepage": "https://github.com/christkv/require_optional", - "keywords": [ - "optional", - "require", - "optionalPeerDependencies" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "require_optional", - "peerOptionalDependencies": { - "co": ">=5.6.0", - "es6-promise": "^3.0.2", - "es6-promise2": "^4.0.2", - "bson": "0.4.21" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/christkv/require_optional.git" - }, - "scripts": { - "test": "mocha" - }, - "version": "1.0.1" -} diff --git a/node_modules/require_optional/test/nestedTest/index.js b/node_modules/require_optional/test/nestedTest/index.js deleted file mode 100644 index 76de2ab4cf30ca6653f38c249734d6baccf6da82..0000000000000000000000000000000000000000 --- a/node_modules/require_optional/test/nestedTest/index.js +++ /dev/null @@ -1,8 +0,0 @@ -var require_optional = require('../../') - -function findPackage(packageName) { - var pkg = require_optional(packageName); - return pkg; -} - -module.exports.findPackage = findPackage diff --git a/node_modules/require_optional/test/nestedTest/package.json b/node_modules/require_optional/test/nestedTest/package.json deleted file mode 100644 index 4c456a6bf04e3b724b2361f1d9d3ee98d8db526c..0000000000000000000000000000000000000000 --- a/node_modules/require_optional/test/nestedTest/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "nestedtest", - "version": "1.0.0", - "description": "A dummy package that facilitates testing that require_optional correctly walks up the module call stack", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "Sebastian Hallum Clarke", - "license": "ISC" -} diff --git a/node_modules/require_optional/test/require_optional_tests.js b/node_modules/require_optional/test/require_optional_tests.js deleted file mode 100644 index c9cc2a3612b50a6448ab7e2e3c5a70b424663b2e..0000000000000000000000000000000000000000 --- a/node_modules/require_optional/test/require_optional_tests.js +++ /dev/null @@ -1,59 +0,0 @@ -var assert = require('assert'), - require_optional = require('../'), - nestedTest = require('./nestedTest'); - -describe('Require Optional', function() { - describe('top level require', function() { - it('should correctly require co library', function() { - var promise = require_optional('es6-promise'); - assert.ok(promise); - }); - - it('should fail to require es6-promise library', function() { - try { - require_optional('co'); - } catch(e) { - assert.equal('OPTIONAL_MODULE_NOT_FOUND', e.code); - return; - } - - assert.ok(false); - }); - - it('should ignore optional library not defined', function() { - assert.equal(undefined, require_optional('es6-promise2')); - }); - }); - - describe('internal module file require', function() { - it('should correctly require co library', function() { - var Long = require_optional('bson/lib/bson/long.js'); - assert.ok(Long); - }); - }); - - describe('top level resolve', function() { - it('should correctly use exists method', function() { - assert.equal(false, require_optional.exists('co')); - assert.equal(true, require_optional.exists('es6-promise')); - assert.equal(true, require_optional.exists('bson/lib/bson/long.js')); - assert.equal(false, require_optional.exists('es6-promise2')); - }); - }); - - describe('require_optional inside dependencies', function() { - it('should correctly walk up module call stack searching for peerOptionalDependencies', function() { - assert.ok(nestedTest.findPackage('bson')) - }); - it('should return null when a package is defined in top-level package.json but not installed', function() { - assert.equal(null, nestedTest.findPackage('es6-promise2')) - }); - it('should error when searching for an optional dependency that is not defined in any ancestor package.json', function() { - try { - nestedTest.findPackage('bison') - } catch (err) { - assert.equal(err.message, 'no optional dependency [bison] defined in peerOptionalDependencies in any package.json') - } - }) - }); -}); diff --git a/node_modules/resolve-from/index.js b/node_modules/resolve-from/index.js deleted file mode 100644 index 434159f17ab8b4f4a0d1fd39b9b1c38d09243b28..0000000000000000000000000000000000000000 --- a/node_modules/resolve-from/index.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; -var path = require('path'); -var Module = require('module'); - -module.exports = function (fromDir, moduleId) { - if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { - throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); - } - - fromDir = path.resolve(fromDir); - - var fromFile = path.join(fromDir, 'noop.js'); - - try { - return Module._resolveFilename(moduleId, { - id: fromFile, - filename: fromFile, - paths: Module._nodeModulePaths(fromDir) - }); - } catch (err) { - return null; - } -}; diff --git a/node_modules/resolve-from/license b/node_modules/resolve-from/license deleted file mode 100644 index 654d0bfe943437d43242325b1fbcff5f400d84ee..0000000000000000000000000000000000000000 --- a/node_modules/resolve-from/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/resolve-from/package.json b/node_modules/resolve-from/package.json deleted file mode 100644 index 28123cc744d4122609afa35839b31820081b2cf8..0000000000000000000000000000000000000000 --- a/node_modules/resolve-from/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "_from": "resolve-from@^2.0.0", - "_id": "resolve-from@2.0.0", - "_inBundle": false, - "_integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=", - "_location": "/resolve-from", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "resolve-from@^2.0.0", - "name": "resolve-from", - "escapedName": "resolve-from", - "rawSpec": "^2.0.0", - "saveSpec": null, - "fetchSpec": "^2.0.0" - }, - "_requiredBy": [ - "/require_optional" - ], - "_resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", - "_shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", - "_spec": "resolve-from@^2.0.0", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/require_optional", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/resolve-from/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Resolve the path of a module like require.resolve() but from a given path", - "devDependencies": { - "ava": "*", - "xo": "*" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/sindresorhus/resolve-from#readme", - "keywords": [ - "require", - "resolve", - "path", - "module", - "from", - "like", - "path" - ], - "license": "MIT", - "name": "resolve-from", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/resolve-from.git" - }, - "scripts": { - "test": "xo && ava" - }, - "version": "2.0.0" -} diff --git a/node_modules/resolve-from/readme.md b/node_modules/resolve-from/readme.md deleted file mode 100644 index bb4ca91e8b78c69d92fdbfc00eea4202cf4a1115..0000000000000000000000000000000000000000 --- a/node_modules/resolve-from/readme.md +++ /dev/null @@ -1,58 +0,0 @@ -# resolve-from [](https://travis-ci.org/sindresorhus/resolve-from) - -> Resolve the path of a module like [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve) but from a given path - -Unlike `require.resolve()` it returns `null` instead of throwing when the module can't be found. - - -## Install - -``` -$ npm install --save resolve-from -``` - - -## Usage - -```js -const resolveFrom = require('resolve-from'); - -// there's a file at `./foo/bar.js` - -resolveFrom('foo', './bar'); -//=> '/Users/sindresorhus/dev/test/foo/bar.js' -``` - - -## API - -### resolveFrom(fromDir, moduleId) - -#### fromDir - -Type: `string` - -Directory to resolve from. - -#### moduleId - -Type: `string` - -What you would use in `require()`. - - -## Tip - -Create a partial using a bound function if you want to require from the same `fromDir` multiple times: - -```js -const resolveFromFoo = resolveFrom.bind(null, 'foo'); - -resolveFromFoo('./bar'); -resolveFromFoo('./baz'); -``` - - -## License - -MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/saslprep/.editorconfig b/node_modules/saslprep/.editorconfig deleted file mode 100644 index d1d8a4176a416daffcfbfecdd3f35f24bd79fc7d..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/.editorconfig +++ /dev/null @@ -1,10 +0,0 @@ -# http://editorconfig.org -root = true - -[*] -indent_style = space -indent_size = 2 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true diff --git a/node_modules/saslprep/.eslintrc b/node_modules/saslprep/.eslintrc deleted file mode 100644 index 06c76844fec8077bf88ba32990060c27b161f23c..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/.eslintrc +++ /dev/null @@ -1,17 +0,0 @@ -{ - "plugins": [ - "prettier" - ], - "env": { - "browser": true, - "node": true, - "es6": true - }, - "rules": { - "prettier/prettier": ["error", { - "semi": false, - "singleQuote": true, - "trailingComma": "es5" - }] - } -} diff --git a/node_modules/saslprep/.gitattributes b/node_modules/saslprep/.gitattributes deleted file mode 100644 index 3ba45360c5e16ac15e53d12e07063bb5d84375fc..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.mem binary diff --git a/node_modules/saslprep/.travis.yml b/node_modules/saslprep/.travis.yml deleted file mode 100644 index 53b824df4db8dd245f2f20d7d6117a3a1a3f070c..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -sudo: false -language: node_js -node_js: - - "6" - - "8" diff --git a/node_modules/saslprep/LICENSE b/node_modules/saslprep/LICENSE deleted file mode 100644 index 481c7a50f96cf594ff078ba43267185b9c5cccc7..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2014 Dmitry Tsvettsikh - -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/saslprep/code-points.mem b/node_modules/saslprep/code-points.mem deleted file mode 100644 index 4781b066802688bdf954d2e89bcfac967db29c09..0000000000000000000000000000000000000000 Binary files a/node_modules/saslprep/code-points.mem and /dev/null differ diff --git a/node_modules/saslprep/generate-code-points.js b/node_modules/saslprep/generate-code-points.js deleted file mode 100644 index 95f085fe56ce9684a0d289a15e931c1d50b68d72..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/generate-code-points.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -const bitfield = require('sparse-bitfield'); -const codePoints = require('./lib/code-points'); - -const unassigned_code_points = bitfield(); -const commonly_mapped_to_nothing = bitfield(); -const non_ascii_space_characters = bitfield(); -const prohibited_characters = bitfield(); -const bidirectional_r_al = bitfield(); -const bidirectional_l = bitfield(); - -/** - * @param {bitfield} bits - * @param {array} src - */ -function traverse(bits, src) { - for(const code of src.keys()) { - bits.set(code, true); - } - - const buffer = bits.toBuffer(); - return Buffer.concat([ createSize(buffer), buffer ]); -} - -/** - * @param {Buffer} buffer - * @returns {Buffer} - */ -function createSize(buffer) { - const buf = Buffer.alloc(4); - buf.writeUInt32BE(buffer.length); - - return buf; -} - -const memory = []; - -memory.push( - traverse(unassigned_code_points, codePoints.unassigned_code_points), - traverse(commonly_mapped_to_nothing, codePoints.commonly_mapped_to_nothing), - traverse(non_ascii_space_characters, codePoints.non_ASCII_space_characters), - traverse(prohibited_characters, codePoints.prohibited_characters), - traverse(bidirectional_r_al, codePoints.bidirectional_r_al), - traverse(bidirectional_l, codePoints.bidirectional_l), -); - -process.stdout.write(Buffer.concat(memory)); diff --git a/node_modules/saslprep/index.js b/node_modules/saslprep/index.js deleted file mode 100644 index 94fb1320bb43221fbbb20b9dee0d80106f83be59..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/index.js +++ /dev/null @@ -1,120 +0,0 @@ -'use strict' - -const { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l, -} = require('./lib/memory-code-points') - -module.exports = saslprep - -// 2.1. Mapping - -/** - * non-ASCII space characters [StringPrep, C.1.2] that can be - * mapped to SPACE (U+0020) - */ -const mapping2space = non_ASCII_space_characters - -/** - * the "commonly mapped to nothing" characters [StringPrep, B.1] - * that can be mapped to nothing. - */ -const mapping2nothing = commonly_mapped_to_nothing - -// utils -const getCodePoint = character => character.codePointAt(0) -const first = x => x[0] -const last = x => x[x.length - 1] - -/** - * SASLprep. - * @param {string} input - * @param {object} opts - * @param {boolean} opts.allowUnassigned - */ -function saslprep(input, opts = {}) { - if (typeof input !== 'string') { - throw new TypeError('Expected string.') - } - - if (input.length === 0) { - return '' - } - - // 1. Map - const mapped_input = input - .split('') - .map(getCodePoint) - // 1.1 mapping to space - .map(character => (mapping2space.get(character) ? 0x20 : character)) - // 1.2 mapping to nothing - .filter(character => !mapping2nothing.get(character)) - - // 2. Normalize - const normalized_input = String.fromCodePoint(...mapped_input).normalize('NFKC') - - const normalized_map = normalized_input.split('').map(getCodePoint) - - // 3. Prohibit - const hasProhibited = normalized_map.some(character => - prohibited_characters.get(character) - ) - - if (hasProhibited) { - throw new Error( - 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' - ) - } - - // Unassigned Code Points - if (opts.allowUnassigned !== true) { - const hasUnassigned = normalized_map.some(character => - unassigned_code_points.get(character) - ) - - if (hasUnassigned) { - throw new Error( - 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' - ) - } - } - - // 4. check bidi - - const hasBidiRAL = normalized_map - .some((character) => bidirectional_r_al.get(character)) - - const hasBidiL = normalized_map - .some((character) => bidirectional_l.get(character)) - - // 4.1 If a string contains any RandALCat character, the string MUST NOT - // contain any LCat character. - if (hasBidiRAL && hasBidiL) { - throw new Error( - 'String must not contain RandALCat and LCat at the same time,' + - ' see https://tools.ietf.org/html/rfc3454#section-6' - ) - } - - /** - * 4.2 If a string contains any RandALCat character, a RandALCat - * character MUST be the first character of the string, and a - * RandALCat character MUST be the last character of the string. - */ - - const isFirstBidiRAL = bidirectional_r_al.get(getCodePoint(first(normalized_input))) - const isLastBidiRAL = bidirectional_r_al.get(getCodePoint(last(normalized_input))) - - if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { - throw new Error( - 'Bidirectional RandALCat character must be the first and the last' + - ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' - ) - } - - return normalized_input -} diff --git a/node_modules/saslprep/lib/code-points.js b/node_modules/saslprep/lib/code-points.js deleted file mode 100644 index 4c5885a2f9cca1cdc27a173fac922ddd6db2589e..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/lib/code-points.js +++ /dev/null @@ -1,996 +0,0 @@ -'use strict' - -const { range } = require('./util') - -/** - * A.1 Unassigned code points in Unicode 3.2 - * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 - */ -const unassigned_code_points = new Set([ - 0x0221, - ...range(0x0234, 0x024F), - ...range(0x02AE, 0x02AF), - ...range(0x02EF, 0x02FF), - ...range(0x0350, 0x035F), - ...range(0x0370, 0x0373), - ...range(0x0376, 0x0379), - ...range(0x037B, 0x037D), - ...range(0x037F, 0x0383), - 0x038B, - 0x038D, - 0x03A2, - 0x03CF, - ...range(0x03F7, 0x03FF), - 0x0487, - 0x04CF, - ...range(0x04F6, 0x04F7), - ...range(0x04FA, 0x04FF), - ...range(0x0510, 0x0530), - ...range(0x0557, 0x0558), - 0x0560, - 0x0588, - ...range(0x058B, 0x0590), - 0x05A2, - 0x05BA, - ...range(0x05C5, 0x05CF), - ...range(0x05EB, 0x05EF), - ...range(0x05F5, 0x060B), - ...range(0x060D, 0x061A), - ...range(0x061C, 0x061E), - 0x0620, - ...range(0x063B, 0x063F), - ...range(0x0656, 0x065F), - ...range(0x06EE, 0x06EF), - 0x06FF, - 0x070E, - ...range(0x072D, 0x072F), - ...range(0x074B, 0x077F), - ...range(0x07B2, 0x0900), - 0x0904, - ...range(0x093A, 0x093B), - ...range(0x094E, 0x094F), - ...range(0x0955, 0x0957), - ...range(0x0971, 0x0980), - 0x0984, - ...range(0x098D, 0x098E), - ...range(0x0991, 0x0992), - 0x09A9, - 0x09B1, - ...range(0x09B3, 0x09B5), - ...range(0x09BA, 0x09BB), - 0x09BD, - ...range(0x09C5, 0x09C6), - ...range(0x09C9, 0x09CA), - ...range(0x09CE, 0x09D6), - ...range(0x09D8, 0x09DB), - 0x09DE, - ...range(0x09E4, 0x09E5), - ...range(0x09FB, 0x0A01), - ...range(0x0A03, 0x0A04), - ...range(0x0A0B, 0x0A0E), - ...range(0x0A11, 0x0A12), - 0x0A29, - 0x0A31, - 0x0A34, - 0x0A37, - ...range(0x0A3A, 0x0A3B), - 0x0A3D, - ...range(0x0A43, 0x0A46), - ...range(0x0A49, 0x0A4A), - ...range(0x0A4E, 0x0A58), - 0x0A5D, - ...range(0x0A5F, 0x0A65), - ...range(0x0A75, 0x0A80), - 0x0A84, - 0x0A8C, - 0x0A8E, - 0x0A92, - 0x0AA9, - 0x0AB1, - 0x0AB4, - ...range(0x0ABA, 0x0ABB), - 0x0AC6, - 0x0ACA, - ...range(0x0ACE, 0x0ACF), - ...range(0x0AD1, 0x0ADF), - ...range(0x0AE1, 0x0AE5), - ...range(0x0AF0, 0x0B00), - 0x0B04, - ...range(0x0B0D, 0x0B0E), - ...range(0x0B11, 0x0B12), - 0x0B29, - 0x0B31, - ...range(0x0B34, 0x0B35), - ...range(0x0B3A, 0x0B3B), - ...range(0x0B44, 0x0B46), - ...range(0x0B49, 0x0B4A), - ...range(0x0B4E, 0x0B55), - ...range(0x0B58, 0x0B5B), - 0x0B5E, - ...range(0x0B62, 0x0B65), - ...range(0x0B71, 0x0B81), - 0x0B84, - ...range(0x0B8B, 0x0B8D), - 0x0B91, - ...range(0x0B96, 0x0B98), - 0x0B9B, - 0x0B9D, - ...range(0x0BA0, 0x0BA2), - ...range(0x0BA5, 0x0BA7), - ...range(0x0BAB, 0x0BAD), - 0x0BB6, - ...range(0x0BBA, 0x0BBD), - ...range(0x0BC3, 0x0BC5), - 0x0BC9, - ...range(0x0BCE, 0x0BD6), - ...range(0x0BD8, 0x0BE6), - ...range(0x0BF3, 0x0C00), - 0x0C04, - 0x0C0D, - 0x0C11, - 0x0C29, - 0x0C34, - ...range(0x0C3A, 0x0C3D), - 0x0C45, - 0x0C49, - ...range(0x0C4E, 0x0C54), - ...range(0x0C57, 0x0C5F), - ...range(0x0C62, 0x0C65), - ...range(0x0C70, 0x0C81), - 0x0C84, - 0x0C8D, - 0x0C91, - 0x0CA9, - 0x0CB4, - ...range(0x0CBA, 0x0CBD), - 0x0CC5, - 0x0CC9, - ...range(0x0CCE, 0x0CD4), - ...range(0x0CD7, 0x0CDD), - 0x0CDF, - ...range(0x0CE2, 0x0CE5), - ...range(0x0CF0, 0x0D01), - 0x0D04, - 0x0D0D, - 0x0D11, - 0x0D29, - ...range(0x0D3A, 0x0D3D), - ...range(0x0D44, 0x0D45), - 0x0D49, - ...range(0x0D4E, 0x0D56), - ...range(0x0D58, 0x0D5F), - ...range(0x0D62, 0x0D65), - ...range(0x0D70, 0x0D81), - 0x0D84, - ...range(0x0D97, 0x0D99), - 0x0DB2, - 0x0DBC, - ...range(0x0DBE, 0x0DBF), - ...range(0x0DC7, 0x0DC9), - ...range(0x0DCB, 0x0DCE), - 0x0DD5, - 0x0DD7, - ...range(0x0DE0, 0x0DF1), - ...range(0x0DF5, 0x0E00), - ...range(0x0E3B, 0x0E3E), - ...range(0x0E5C, 0x0E80), - 0x0E83, - ...range(0x0E85, 0x0E86), - 0x0E89, - ...range(0x0E8B, 0x0E8C), - ...range(0x0E8E, 0x0E93), - 0x0E98, - 0x0EA0, - 0x0EA4, - 0x0EA6, - ...range(0x0EA8, 0x0EA9), - 0x0EAC, - 0x0EBA, - ...range(0x0EBE, 0x0EBF), - 0x0EC5, - 0x0EC7, - ...range(0x0ECE, 0x0ECF), - ...range(0x0EDA, 0x0EDB), - ...range(0x0EDE, 0x0EFF), - 0x0F48, - ...range(0x0F6B, 0x0F70), - ...range(0x0F8C, 0x0F8F), - 0x0F98, - 0x0FBD, - ...range(0x0FCD, 0x0FCE), - ...range(0x0FD0, 0x0FFF), - 0x1022, - 0x1028, - 0x102B, - ...range(0x1033, 0x1035), - ...range(0x103A, 0x103F), - ...range(0x105A, 0x109F), - ...range(0x10C6, 0x10CF), - ...range(0x10F9, 0x10FA), - ...range(0x10FC, 0x10FF), - ...range(0x115A, 0x115E), - ...range(0x11A3, 0x11A7), - ...range(0x11FA, 0x11FF), - 0x1207, - 0x1247, - 0x1249, - ...range(0x124E, 0x124F), - 0x1257, - 0x1259, - ...range(0x125E, 0x125F), - 0x1287, - 0x1289, - ...range(0x128E, 0x128F), - 0x12AF, - 0x12B1, - ...range(0x12B6, 0x12B7), - 0x12BF, - 0x12C1, - ...range(0x12C6, 0x12C7), - 0x12CF, - 0x12D7, - 0x12EF, - 0x130F, - 0x1311, - ...range(0x1316, 0x1317), - 0x131F, - 0x1347, - ...range(0x135B, 0x1360), - ...range(0x137D, 0x139F), - ...range(0x13F5, 0x1400), - ...range(0x1677, 0x167F), - ...range(0x169D, 0x169F), - ...range(0x16F1, 0x16FF), - 0x170D, - ...range(0x1715, 0x171F), - ...range(0x1737, 0x173F), - ...range(0x1754, 0x175F), - 0x176D, - 0x1771, - ...range(0x1774, 0x177F), - ...range(0x17DD, 0x17DF), - ...range(0x17EA, 0x17FF), - 0x180F, - ...range(0x181A, 0x181F), - ...range(0x1878, 0x187F), - ...range(0x18AA, 0x1DFF), - ...range(0x1E9C, 0x1E9F), - ...range(0x1EFA, 0x1EFF), - ...range(0x1F16, 0x1F17), - ...range(0x1F1E, 0x1F1F), - ...range(0x1F46, 0x1F47), - ...range(0x1F4E, 0x1F4F), - 0x1F58, - 0x1F5A, - 0x1F5C, - 0x1F5E, - ...range(0x1F7E, 0x1F7F), - 0x1FB5, - 0x1FC5, - ...range(0x1FD4, 0x1FD5), - 0x1FDC, - ...range(0x1FF0, 0x1FF1), - 0x1FF5, - 0x1FFF, - ...range(0x2053, 0x2056), - ...range(0x2058, 0x205E), - ...range(0x2064, 0x2069), - ...range(0x2072, 0x2073), - ...range(0x208F, 0x209F), - ...range(0x20B2, 0x20CF), - ...range(0x20EB, 0x20FF), - ...range(0x213B, 0x213C), - ...range(0x214C, 0x2152), - ...range(0x2184, 0x218F), - ...range(0x23CF, 0x23FF), - ...range(0x2427, 0x243F), - ...range(0x244B, 0x245F), - 0x24FF, - ...range(0x2614, 0x2615), - 0x2618, - ...range(0x267E, 0x267F), - ...range(0x268A, 0x2700), - 0x2705, - ...range(0x270A, 0x270B), - 0x2728, - 0x274C, - 0x274E, - ...range(0x2753, 0x2755), - 0x2757, - ...range(0x275F, 0x2760), - ...range(0x2795, 0x2797), - 0x27B0, - ...range(0x27BF, 0x27CF), - ...range(0x27EC, 0x27EF), - ...range(0x2B00, 0x2E7F), - 0x2E9A, - ...range(0x2EF4, 0x2EFF), - ...range(0x2FD6, 0x2FEF), - ...range(0x2FFC, 0x2FFF), - 0x3040, - ...range(0x3097, 0x3098), - ...range(0x3100, 0x3104), - ...range(0x312D, 0x3130), - 0x318F, - ...range(0x31B8, 0x31EF), - ...range(0x321D, 0x321F), - ...range(0x3244, 0x3250), - ...range(0x327C, 0x327E), - ...range(0x32CC, 0x32CF), - 0x32FF, - ...range(0x3377, 0x337A), - ...range(0x33DE, 0x33DF), - 0x33FF, - ...range(0x4DB6, 0x4DFF), - ...range(0x9FA6, 0x9FFF), - ...range(0xA48D, 0xA48F), - ...range(0xA4C7, 0xABFF), - ...range(0xD7A4, 0xD7FF), - ...range(0xFA2E, 0xFA2F), - ...range(0xFA6B, 0xFAFF), - ...range(0xFB07, 0xFB12), - ...range(0xFB18, 0xFB1C), - 0xFB37, - 0xFB3D, - 0xFB3F, - 0xFB42, - 0xFB45, - ...range(0xFBB2, 0xFBD2), - ...range(0xFD40, 0xFD4F), - ...range(0xFD90, 0xFD91), - ...range(0xFDC8, 0xFDCF), - ...range(0xFDFD, 0xFDFF), - ...range(0xFE10, 0xFE1F), - ...range(0xFE24, 0xFE2F), - ...range(0xFE47, 0xFE48), - 0xFE53, - 0xFE67, - ...range(0xFE6C, 0xFE6F), - 0xFE75, - ...range(0xFEFD, 0xFEFE), - 0xFF00, - ...range(0xFFBF, 0xFFC1), - ...range(0xFFC8, 0xFFC9), - ...range(0xFFD0, 0xFFD1), - ...range(0xFFD8, 0xFFD9), - ...range(0xFFDD, 0xFFDF), - 0xFFE7, - ...range(0xFFEF, 0xFFF8), - ...range(0x10000, 0x102FF), - 0x1031F, - ...range(0x10324, 0x1032F), - ...range(0x1034B, 0x103FF), - ...range(0x10426, 0x10427), - ...range(0x1044E, 0x1CFFF), - ...range(0x1D0F6, 0x1D0FF), - ...range(0x1D127, 0x1D129), - ...range(0x1D1DE, 0x1D3FF), - 0x1D455, - 0x1D49D, - ...range(0x1D4A0, 0x1D4A1), - ...range(0x1D4A3, 0x1D4A4), - ...range(0x1D4A7, 0x1D4A8), - 0x1D4AD, - 0x1D4BA, - 0x1D4BC, - 0x1D4C1, - 0x1D4C4, - 0x1D506, - ...range(0x1D50B, 0x1D50C), - 0x1D515, - 0x1D51D, - 0x1D53A, - 0x1D53F, - 0x1D545, - ...range(0x1D547, 0x1D549), - 0x1D551, - ...range(0x1D6A4, 0x1D6A7), - ...range(0x1D7CA, 0x1D7CD), - ...range(0x1D800, 0x1FFFD), - ...range(0x2A6D7, 0x2F7FF), - ...range(0x2FA1E, 0x2FFFD), - ...range(0x30000, 0x3FFFD), - ...range(0x40000, 0x4FFFD), - ...range(0x50000, 0x5FFFD), - ...range(0x60000, 0x6FFFD), - ...range(0x70000, 0x7FFFD), - ...range(0x80000, 0x8FFFD), - ...range(0x90000, 0x9FFFD), - ...range(0xA0000, 0xAFFFD), - ...range(0xB0000, 0xBFFFD), - ...range(0xC0000, 0xCFFFD), - ...range(0xD0000, 0xDFFFD), - 0xE0000, - ...range(0xE0002, 0xE001F), - ...range(0xE0080, 0xEFFFD), -]) - -/** - * B.1 Commonly mapped to nothing - * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 - */ -const commonly_mapped_to_nothing = new Set([ - 0x00AD, - 0x034F, - 0x1806, - 0x180B, - 0x180C, - 0x180D, - 0x200B, - 0x200C, - 0x200D, - 0x2060, - 0xFE00, - 0xFE01, - 0xFE02, - 0xFE03, - 0xFE04, - 0xFE05, - 0xFE06, - 0xFE07, - 0xFE08, - 0xFE09, - 0xFE0A, - 0xFE0B, - 0xFE0C, - 0xFE0D, - 0xFE0E, - 0xFE0F, - 0xFEFF, -]) - -/** - * C.1.2 Non-ASCII space characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 - */ -const non_ASCII_space_characters = new Set([ - 0x00a0 /* NO-BREAK SPACE */, - 0x1680 /* OGHAM SPACE MARK */, - 0x2000 /* EN QUAD */, - 0x2001 /* EM QUAD */, - 0x2002 /* EN SPACE */, - 0x2003 /* EM SPACE */, - 0x2004 /* THREE-PER-EM SPACE */, - 0x2005 /* FOUR-PER-EM SPACE */, - 0x2006 /* SIX-PER-EM SPACE */, - 0x2007 /* FIGURE SPACE */, - 0x2008 /* PUNCTUATION SPACE */, - 0x2009 /* THIN SPACE */, - 0x200a /* HAIR SPACE */, - 0x200b /* ZERO WIDTH SPACE */, - 0x202f /* NARROW NO-BREAK SPACE */, - 0x205f /* MEDIUM MATHEMATICAL SPACE */, - 0x3000 /* IDEOGRAPHIC SPACE */, -]) - -/** - * 2.3. Prohibited Output - * @type {Set} - */ -const prohibited_characters = new Set([ - ...non_ASCII_space_characters, - - /** - * C.2.1 ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 - */ - ...range(0, 0x001f) /* [CONTROL CHARACTERS] */, - 0x007f /* DELETE */, - - /** - * C.2.2 Non-ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 - */ - ...range(0x0080, 0x009F), /* [CONTROL CHARACTERS] */ - 0x06DD, /* ARABIC END OF AYAH */ - 0x070F, /* SYRIAC ABBREVIATION MARK */ - 0x180E, /* MONGOLIAN VOWEL SEPARATOR */ - 0x200C, /* ZERO WIDTH NON-JOINER */ - 0x200D, /* ZERO WIDTH JOINER */ - 0x2028, /* LINE SEPARATOR */ - 0x2029, /* PARAGRAPH SEPARATOR */ - 0x2060, /* WORD JOINER */ - 0x2061, /* FUNCTION APPLICATION */ - 0x2062, /* INVISIBLE TIMES */ - 0x2063, /* INVISIBLE SEPARATOR */ - ...range(0x206A, 0x206F), /* [CONTROL CHARACTERS] */ - 0xFEFF, /* ZERO WIDTH NO-BREAK SPACE */ - ...range(0xFFF9, 0xFFFC), /* [CONTROL CHARACTERS] */ - ...range(0x1D173, 0x1D17A), /* [MUSICAL CONTROL CHARACTERS] */ - - /** - * C.3 Private use - * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 - */ - ...range(0xE000, 0xF8FF), /* [PRIVATE USE, PLANE 0] */ - ...range(0xF0000, 0xFFFFD), /* [PRIVATE USE, PLANE 15] */ - ...range(0x100000, 0x10FFFD), /* [PRIVATE USE, PLANE 16] */ - - /** - * C.4 Non-character code points - * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 - */ - ...range(0xFDD0, 0xFDEF), /* [NONCHARACTER CODE POINTS] */ - ...range(0xFFFE, 0xFFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0x1FFFE, 0x1FFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0x2FFFE, 0x2FFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0x3FFFE, 0x3FFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0x4FFFE, 0x4FFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0x5FFFE, 0x5FFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0x6FFFE, 0x6FFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0x7FFFE, 0x7FFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0x8FFFE, 0x8FFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0x9FFFE, 0x9FFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0xAFFFE, 0xAFFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0xBFFFE, 0xBFFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0xCFFFE, 0xCFFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0xDFFFE, 0xDFFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0xEFFFE, 0xEFFFF), /* [NONCHARACTER CODE POINTS] */ - ...range(0x10FFFE, 0x10FFFF), /* [NONCHARACTER CODE POINTS] */ - - /** - * C.5 Surrogate codes - * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 - */ - ...range(0xD800, 0xDFFF), - - /** - * C.6 Inappropriate for plain text - * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 - */ - 0xFFF9, /* INTERLINEAR ANNOTATION ANCHOR */ - 0xFFFA, /* INTERLINEAR ANNOTATION SEPARATOR */ - 0xFFFB, /* INTERLINEAR ANNOTATION TERMINATOR */ - 0xFFFC, /* OBJECT REPLACEMENT CHARACTER */ - 0xFFFD, /* REPLACEMENT CHARACTER */ - - /** - * C.7 Inappropriate for canonical representation - * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 - */ - ...range(0x2FF0, 0x2FFB), /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */ - - /** - * C.8 Change display properties or are deprecated - * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 - */ - 0x0340, /* COMBINING GRAVE TONE MARK */ - 0x0341, /* COMBINING ACUTE TONE MARK */ - 0x200E, /* LEFT-TO-RIGHT MARK */ - 0x200F, /* RIGHT-TO-LEFT MARK */ - 0x202A, /* LEFT-TO-RIGHT EMBEDDING */ - 0x202B, /* RIGHT-TO-LEFT EMBEDDING */ - 0x202C, /* POP DIRECTIONAL FORMATTING */ - 0x202D, /* LEFT-TO-RIGHT OVERRIDE */ - 0x202E, /* RIGHT-TO-LEFT OVERRIDE */ - 0x206A, /* INHIBIT SYMMETRIC SWAPPING */ - 0x206B, /* ACTIVATE SYMMETRIC SWAPPING */ - 0x206C, /* INHIBIT ARABIC FORM SHAPING */ - 0x206D, /* ACTIVATE ARABIC FORM SHAPING */ - 0x206E, /* NATIONAL DIGIT SHAPES */ - 0x206F, /* NOMINAL DIGIT SHAPES */ - - /** - * C.9 Tagging characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 - */ - 0xE0001, /* LANGUAGE TAG */ - ...range(0xE0020, 0xE007F) /* [TAGGING CHARACTERS] */ -]) - -/** - * D.1 Characters with bidirectional property "R" or "AL" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 - */ -const bidirectional_r_al = new Set([ - 0x05BE, - 0x05C0, - 0x05C3, - ...range(0x05D0, 0x05EA), - ...range(0x05F0, 0x05F4), - 0x061B, - 0x061F, - ...range(0x0621, 0x063A), - ...range(0x0640, 0x064A), - ...range(0x066D, 0x066F), - ...range(0x0671, 0x06D5), - 0x06DD, - ...range(0x06E5, 0x06E6), - ...range(0x06FA, 0x06FE), - ...range(0x0700, 0x070D), - 0x0710, - ...range(0x0712, 0x072C), - ...range(0x0780, 0x07A5), - 0x07B1, - 0x200F, - 0xFB1D, - ...range(0xFB1F, 0xFB28), - ...range(0xFB2A, 0xFB36), - ...range(0xFB38, 0xFB3C), - 0xFB3E, - ...range(0xFB40, 0xFB41), - ...range(0xFB43, 0xFB44), - ...range(0xFB46, 0xFBB1), - ...range(0xFBD3, 0xFD3D), - ...range(0xFD50, 0xFD8F), - ...range(0xFD92, 0xFDC7), - ...range(0xFDF0, 0xFDFC), - ...range(0xFE70, 0xFE74), - ...range(0xFE76, 0xFEFC), -]) - -/** - * D.2 Characters with bidirectional property "L" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 - */ -const bidirectional_l = new Set([ - ...range(0x0041, 0x005A), - ...range(0x0061, 0x007A), - 0x00AA, - 0x00B5, - 0x00BA, - ...range(0x00C0, 0x00D6), - ...range(0x00D8, 0x00F6), - ...range(0x00F8, 0x0220), - ...range(0x0222, 0x0233), - ...range(0x0250, 0x02AD), - ...range(0x02B0, 0x02B8), - ...range(0x02BB, 0x02C1), - ...range(0x02D0, 0x02D1), - ...range(0x02E0, 0x02E4), - 0x02EE, - 0x037A, - 0x0386, - ...range(0x0388, 0x038A), - 0x038C, - ...range(0x038E, 0x03A1), - ...range(0x03A3, 0x03CE), - ...range(0x03D0, 0x03F5), - ...range(0x0400, 0x0482), - ...range(0x048A, 0x04CE), - ...range(0x04D0, 0x04F5), - ...range(0x04F8, 0x04F9), - ...range(0x0500, 0x050F), - ...range(0x0531, 0x0556), - ...range(0x0559, 0x055F), - ...range(0x0561, 0x0587), - 0x0589, - 0x0903, - ...range(0x0905, 0x0939), - ...range(0x093D, 0x0940), - ...range(0x0949, 0x094C), - 0x0950, - ...range(0x0958, 0x0961), - ...range(0x0964, 0x0970), - ...range(0x0982, 0x0983), - ...range(0x0985, 0x098C), - ...range(0x098F, 0x0990), - ...range(0x0993, 0x09A8), - ...range(0x09AA, 0x09B0), - 0x09B2, - ...range(0x09B6, 0x09B9), - ...range(0x09BE, 0x09C0), - ...range(0x09C7, 0x09C8), - ...range(0x09CB, 0x09CC), - 0x09D7, - ...range(0x09DC, 0x09DD), - ...range(0x09DF, 0x09E1), - ...range(0x09E6, 0x09F1), - ...range(0x09F4, 0x09FA), - ...range(0x0A05, 0x0A0A), - ...range(0x0A0F, 0x0A10), - ...range(0x0A13, 0x0A28), - ...range(0x0A2A, 0x0A30), - ...range(0x0A32, 0x0A33), - ...range(0x0A35, 0x0A36), - ...range(0x0A38, 0x0A39), - ...range(0x0A3E, 0x0A40), - ...range(0x0A59, 0x0A5C), - 0x0A5E, - ...range(0x0A66, 0x0A6F), - ...range(0x0A72, 0x0A74), - 0x0A83, - ...range(0x0A85, 0x0A8B), - 0x0A8D, - ...range(0x0A8F, 0x0A91), - ...range(0x0A93, 0x0AA8), - ...range(0x0AAA, 0x0AB0), - ...range(0x0AB2, 0x0AB3), - ...range(0x0AB5, 0x0AB9), - ...range(0x0ABD, 0x0AC0), - 0x0AC9, - ...range(0x0ACB, 0x0ACC), - 0x0AD0, - 0x0AE0, - ...range(0x0AE6, 0x0AEF), - ...range(0x0B02, 0x0B03), - ...range(0x0B05, 0x0B0C), - ...range(0x0B0F, 0x0B10), - ...range(0x0B13, 0x0B28), - ...range(0x0B2A, 0x0B30), - ...range(0x0B32, 0x0B33), - ...range(0x0B36, 0x0B39), - ...range(0x0B3D, 0x0B3E), - 0x0B40, - ...range(0x0B47, 0x0B48), - ...range(0x0B4B, 0x0B4C), - 0x0B57, - ...range(0x0B5C, 0x0B5D), - ...range(0x0B5F, 0x0B61), - ...range(0x0B66, 0x0B70), - 0x0B83, - ...range(0x0B85, 0x0B8A), - ...range(0x0B8E, 0x0B90), - ...range(0x0B92, 0x0B95), - ...range(0x0B99, 0x0B9A), - 0x0B9C, - ...range(0x0B9E, 0x0B9F), - ...range(0x0BA3, 0x0BA4), - ...range(0x0BA8, 0x0BAA), - ...range(0x0BAE, 0x0BB5), - ...range(0x0BB7, 0x0BB9), - ...range(0x0BBE, 0x0BBF), - ...range(0x0BC1, 0x0BC2), - ...range(0x0BC6, 0x0BC8), - ...range(0x0BCA, 0x0BCC), - 0x0BD7, - ...range(0x0BE7, 0x0BF2), - ...range(0x0C01, 0x0C03), - ...range(0x0C05, 0x0C0C), - ...range(0x0C0E, 0x0C10), - ...range(0x0C12, 0x0C28), - ...range(0x0C2A, 0x0C33), - ...range(0x0C35, 0x0C39), - ...range(0x0C41, 0x0C44), - ...range(0x0C60, 0x0C61), - ...range(0x0C66, 0x0C6F), - ...range(0x0C82, 0x0C83), - ...range(0x0C85, 0x0C8C), - ...range(0x0C8E, 0x0C90), - ...range(0x0C92, 0x0CA8), - ...range(0x0CAA, 0x0CB3), - ...range(0x0CB5, 0x0CB9), - 0x0CBE, - ...range(0x0CC0, 0x0CC4), - ...range(0x0CC7, 0x0CC8), - ...range(0x0CCA, 0x0CCB), - ...range(0x0CD5, 0x0CD6), - 0x0CDE, - ...range(0x0CE0, 0x0CE1), - ...range(0x0CE6, 0x0CEF), - ...range(0x0D02, 0x0D03), - ...range(0x0D05, 0x0D0C), - ...range(0x0D0E, 0x0D10), - ...range(0x0D12, 0x0D28), - ...range(0x0D2A, 0x0D39), - ...range(0x0D3E, 0x0D40), - ...range(0x0D46, 0x0D48), - ...range(0x0D4A, 0x0D4C), - 0x0D57, - ...range(0x0D60, 0x0D61), - ...range(0x0D66, 0x0D6F), - ...range(0x0D82, 0x0D83), - ...range(0x0D85, 0x0D96), - ...range(0x0D9A, 0x0DB1), - ...range(0x0DB3, 0x0DBB), - 0x0DBD, - ...range(0x0DC0, 0x0DC6), - ...range(0x0DCF, 0x0DD1), - ...range(0x0DD8, 0x0DDF), - ...range(0x0DF2, 0x0DF4), - ...range(0x0E01, 0x0E30), - ...range(0x0E32, 0x0E33), - ...range(0x0E40, 0x0E46), - ...range(0x0E4F, 0x0E5B), - ...range(0x0E81, 0x0E82), - 0x0E84, - ...range(0x0E87, 0x0E88), - 0x0E8A, - 0x0E8D, - ...range(0x0E94, 0x0E97), - ...range(0x0E99, 0x0E9F), - ...range(0x0EA1, 0x0EA3), - 0x0EA5, - 0x0EA7, - ...range(0x0EAA, 0x0EAB), - ...range(0x0EAD, 0x0EB0), - ...range(0x0EB2, 0x0EB3), - 0x0EBD, - ...range(0x0EC0, 0x0EC4), - 0x0EC6, - ...range(0x0ED0, 0x0ED9), - ...range(0x0EDC, 0x0EDD), - ...range(0x0F00, 0x0F17), - ...range(0x0F1A, 0x0F34), - 0x0F36, - 0x0F38, - ...range(0x0F3E, 0x0F47), - ...range(0x0F49, 0x0F6A), - 0x0F7F, - 0x0F85, - ...range(0x0F88, 0x0F8B), - ...range(0x0FBE, 0x0FC5), - ...range(0x0FC7, 0x0FCC), - 0x0FCF, - ...range(0x1000, 0x1021), - ...range(0x1023, 0x1027), - ...range(0x1029, 0x102A), - 0x102C, - 0x1031, - 0x1038, - ...range(0x1040, 0x1057), - ...range(0x10A0, 0x10C5), - ...range(0x10D0, 0x10F8), - 0x10FB, - ...range(0x1100, 0x1159), - ...range(0x115F, 0x11A2), - ...range(0x11A8, 0x11F9), - ...range(0x1200, 0x1206), - ...range(0x1208, 0x1246), - 0x1248, - ...range(0x124A, 0x124D), - ...range(0x1250, 0x1256), - 0x1258, - ...range(0x125A, 0x125D), - ...range(0x1260, 0x1286), - 0x1288, - ...range(0x128A, 0x128D), - ...range(0x1290, 0x12AE), - 0x12B0, - ...range(0x12B2, 0x12B5), - ...range(0x12B8, 0x12BE), - 0x12C0, - ...range(0x12C2, 0x12C5), - ...range(0x12C8, 0x12CE), - ...range(0x12D0, 0x12D6), - ...range(0x12D8, 0x12EE), - ...range(0x12F0, 0x130E), - 0x1310, - ...range(0x1312, 0x1315), - ...range(0x1318, 0x131E), - ...range(0x1320, 0x1346), - ...range(0x1348, 0x135A), - ...range(0x1361, 0x137C), - ...range(0x13A0, 0x13F4), - ...range(0x1401, 0x1676), - ...range(0x1681, 0x169A), - ...range(0x16A0, 0x16F0), - ...range(0x1700, 0x170C), - ...range(0x170E, 0x1711), - ...range(0x1720, 0x1731), - ...range(0x1735, 0x1736), - ...range(0x1740, 0x1751), - ...range(0x1760, 0x176C), - ...range(0x176E, 0x1770), - ...range(0x1780, 0x17B6), - ...range(0x17BE, 0x17C5), - ...range(0x17C7, 0x17C8), - ...range(0x17D4, 0x17DA), - 0x17DC, - ...range(0x17E0, 0x17E9), - ...range(0x1810, 0x1819), - ...range(0x1820, 0x1877), - ...range(0x1880, 0x18A8), - ...range(0x1E00, 0x1E9B), - ...range(0x1EA0, 0x1EF9), - ...range(0x1F00, 0x1F15), - ...range(0x1F18, 0x1F1D), - ...range(0x1F20, 0x1F45), - ...range(0x1F48, 0x1F4D), - ...range(0x1F50, 0x1F57), - 0x1F59, - 0x1F5B, - 0x1F5D, - ...range(0x1F5F, 0x1F7D), - ...range(0x1F80, 0x1FB4), - ...range(0x1FB6, 0x1FBC), - 0x1FBE, - ...range(0x1FC2, 0x1FC4), - ...range(0x1FC6, 0x1FCC), - ...range(0x1FD0, 0x1FD3), - ...range(0x1FD6, 0x1FDB), - ...range(0x1FE0, 0x1FEC), - ...range(0x1FF2, 0x1FF4), - ...range(0x1FF6, 0x1FFC), - 0x200E, - 0x2071, - 0x207F, - 0x2102, - 0x2107, - ...range(0x210A, 0x2113), - 0x2115, - ...range(0x2119, 0x211D), - 0x2124, - 0x2126, - 0x2128, - ...range(0x212A, 0x212D), - ...range(0x212F, 0x2131), - ...range(0x2133, 0x2139), - ...range(0x213D, 0x213F), - ...range(0x2145, 0x2149), - ...range(0x2160, 0x2183), - ...range(0x2336, 0x237A), - 0x2395, - ...range(0x249C, 0x24E9), - ...range(0x3005, 0x3007), - ...range(0x3021, 0x3029), - ...range(0x3031, 0x3035), - ...range(0x3038, 0x303C), - ...range(0x3041, 0x3096), - ...range(0x309D, 0x309F), - ...range(0x30A1, 0x30FA), - ...range(0x30FC, 0x30FF), - ...range(0x3105, 0x312C), - ...range(0x3131, 0x318E), - ...range(0x3190, 0x31B7), - ...range(0x31F0, 0x321C), - ...range(0x3220, 0x3243), - ...range(0x3260, 0x327B), - ...range(0x327F, 0x32B0), - ...range(0x32C0, 0x32CB), - ...range(0x32D0, 0x32FE), - ...range(0x3300, 0x3376), - ...range(0x337B, 0x33DD), - ...range(0x33E0, 0x33FE), - ...range(0x3400, 0x4DB5), - ...range(0x4E00, 0x9FA5), - ...range(0xA000, 0xA48C), - ...range(0xAC00, 0xD7A3), - ...range(0xD800, 0xFA2D), - ...range(0xFA30, 0xFA6A), - ...range(0xFB00, 0xFB06), - ...range(0xFB13, 0xFB17), - ...range(0xFF21, 0xFF3A), - ...range(0xFF41, 0xFF5A), - ...range(0xFF66, 0xFFBE), - ...range(0xFFC2, 0xFFC7), - ...range(0xFFCA, 0xFFCF), - ...range(0xFFD2, 0xFFD7), - ...range(0xFFDA, 0xFFDC), - ...range(0x10300, 0x1031E), - ...range(0x10320, 0x10323), - ...range(0x10330, 0x1034A), - ...range(0x10400, 0x10425), - ...range(0x10428, 0x1044D), - ...range(0x1D000, 0x1D0F5), - ...range(0x1D100, 0x1D126), - ...range(0x1D12A, 0x1D166), - ...range(0x1D16A, 0x1D172), - ...range(0x1D183, 0x1D184), - ...range(0x1D18C, 0x1D1A9), - ...range(0x1D1AE, 0x1D1DD), - ...range(0x1D400, 0x1D454), - ...range(0x1D456, 0x1D49C), - ...range(0x1D49E, 0x1D49F), - 0x1D4A2, - ...range(0x1D4A5, 0x1D4A6), - ...range(0x1D4A9, 0x1D4AC), - ...range(0x1D4AE, 0x1D4B9), - 0x1D4BB, - ...range(0x1D4BD, 0x1D4C0), - ...range(0x1D4C2, 0x1D4C3), - ...range(0x1D4C5, 0x1D505), - ...range(0x1D507, 0x1D50A), - ...range(0x1D50D, 0x1D514), - ...range(0x1D516, 0x1D51C), - ...range(0x1D51E, 0x1D539), - ...range(0x1D53B, 0x1D53E), - ...range(0x1D540, 0x1D544), - 0x1D546, - ...range(0x1D54A, 0x1D550), - ...range(0x1D552, 0x1D6A3), - ...range(0x1D6A8, 0x1D7C9), - ...range(0x20000, 0x2A6D6), - ...range(0x2F800, 0x2FA1D), - ...range(0xF0000, 0xFFFFD), - ...range(0x100000, 0x10FFFD) -]) - -module.exports = { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l -} diff --git a/node_modules/saslprep/lib/memory-code-points.js b/node_modules/saslprep/lib/memory-code-points.js deleted file mode 100644 index c776d427f328420c5d2121c4dfc33b9358f6ef9d..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/lib/memory-code-points.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const bitfield = require('sparse-bitfield'); - -const memory = fs.readFileSync(path.resolve(__dirname, '../code-points.mem')); -let offset = 0; - -function read() { - const size = memory.readUInt32BE(offset); - offset += 4; - - const codepoints = memory.slice(offset, offset + size); - offset += size; - - return bitfield({ buffer: codepoints }); -} - -const unassigned_code_points = read(); -const commonly_mapped_to_nothing = read(); -const non_ASCII_space_characters = read(); -const prohibited_characters = read(); -const bidirectional_r_al = read(); -const bidirectional_l = read(); - -module.exports = { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l, -} diff --git a/node_modules/saslprep/lib/util.js b/node_modules/saslprep/lib/util.js deleted file mode 100644 index 697e0d0fcbf27ca3741e2cd1a6b80144fca63780..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/lib/util.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict' - -function range(from, to) { - // TODO: make this inlined. - const list = new Array(to - from + 1) - - for(let i = 0; i < list.length; ++i) { - list[i] = from + i - } - return list -} - -module.exports = { - range -} diff --git a/node_modules/saslprep/package.json b/node_modules/saslprep/package.json deleted file mode 100644 index c3b7ca1519c6266618fcf813883dd688a7897dd7..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "_from": "saslprep@^1.0.0", - "_id": "saslprep@1.0.2", - "_inBundle": false, - "_integrity": "sha512-4cDsYuAjXssUSjxHKRe4DTZC0agDwsCqcMqtJAQPzC74nJ7LfAJflAtC1Zed5hMzEQKj82d3tuzqdGNRsLJ4Gw==", - "_location": "/saslprep", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "saslprep@^1.0.0", - "name": "saslprep", - "escapedName": "saslprep", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/mongodb-core" - ], - "_resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.2.tgz", - "_shasum": "da5ab936e6ea0bbae911ffec77534be370c9f52d", - "_spec": "saslprep@^1.0.0", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongodb-core", - "author": { - "name": "Dmitry Tsvettsikh", - "email": "me@reklatsmasters.com" - }, - "bugs": { - "url": "https://github.com/reklatsmasters/saslprep/issues" - }, - "bundleDependencies": false, - "dependencies": { - "sparse-bitfield": "^3.0.3" - }, - "deprecated": false, - "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013.", - "devDependencies": { - "ava": "^0.25.0", - "eslint-plugin-prettier": "^2.1.2", - "prettier": "^1.4.4" - }, - "engines": { - "node": ">=6" - }, - "homepage": "https://github.com/reklatsmasters/saslprep#readme", - "keywords": [ - "sasl", - "saslprep", - "stringprep", - "rfc4013", - "4013" - ], - "license": "MIT", - "main": "index.js", - "name": "saslprep", - "repository": { - "type": "git", - "url": "git+https://github.com/reklatsmasters/saslprep.git" - }, - "scripts": { - "gen-code-points": "node generate-code-points.js > code-points.mem", - "test": "ava" - }, - "version": "1.0.2" -} diff --git a/node_modules/saslprep/readme.md b/node_modules/saslprep/readme.md deleted file mode 100644 index a94e7600535689d68d79523fcb52145d63bd0159..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/readme.md +++ /dev/null @@ -1,31 +0,0 @@ -# saslprep -[](https://travis-ci.org/reklatsmasters/saslprep) -[](https://npmjs.org/package/saslprep) -[](https://npmjs.org/package/saslprep) -[](https://npmjs.org/package/saslprep) -[](https://npmjs.org/package/saslprep) - -Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013) - -### Usage - -```js -const saslprep = require('saslprep') - -saslprep('password\u00AD') // password -saslprep('password\u0007') // Error: prohibited character -``` - -### API - -##### `saslprep(input: String, opts: Options): String` - -Normalize user name or password. - -##### `Options.allowUnassigned: bool` - -A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default. - -## License - -MIT, 2017 (c) Dmitriy Tsvettsikh diff --git a/node_modules/saslprep/test/index.js b/node_modules/saslprep/test/index.js deleted file mode 100644 index 1fb71cf0df9a65e9a092649d1693fbdc8e9a16f1..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/test/index.js +++ /dev/null @@ -1,70 +0,0 @@ -import test from 'ava' -import saslprep from '../' - -const chr = String.fromCodePoint - -test('should work with liatin letters', (t) => { - const str = 'user' - t.is(saslprep(str), str) -}) - -test('should work be case preserved', (t) => { - const str = 'USER' - t.is(saslprep(str), str) -}) - -test('should remove `mapped to nothing` characters', (t) => { - t.is(saslprep('I\u00ADX'), 'IX') -}) - -test('should replace `Non-ASCII space characters` with space', (t) => { - t.is(saslprep('a\u00A0b'), 'a\u0020b') -}) - -test('should normalize as NFKC', (t) => { - t.is(saslprep('\u00AA'), 'a') - t.is(saslprep('\u2168'), 'IX') -}) - -test('should throws when prohibited characters', (t) => { - // C.2.1 ASCII control characters - t.throws(() => saslprep('a\u007Fb')) - - // C.2.2 Non-ASCII control characters - t.throws(() => saslprep('a\u06DDb')) - - // C.3 Private use - t.throws(() => saslprep('a\uE000b')) - - // C.4 Non-character code points - t.throws(() => saslprep(`a${chr(0x1FFFE)}b`)) - - // C.5 Surrogate codes - t.throws(() => saslprep('a\uD800b')) - - // C.6 Inappropriate for plain text - t.throws(() => saslprep('a\uFFF9b')) - - // C.7 Inappropriate for canonical representation - t.throws(() => saslprep('a\u2FF0b')) - - // C.8 Change display properties or are deprecated - t.throws(() => saslprep('a\u200Eb')) - - // C.9 Tagging characters - t.throws(() => saslprep(`a${chr(0xE0001)}b`)) -}) - -test('should not containt RandALCat and LCat bidi', (t) => { - t.throws(() => saslprep('a\u06DD\u00AAb')) -}) - -test('RandALCat should be first and last', (t) => { - t.notThrows(() => saslprep('\u0627\u0031\u0628')) - t.throws(() => saslprep('\u0627\u0031')) -}) - -test('should handle unassigned code points', (t) => { - t.throws(() => saslprep('a\u0487')) - t.notThrows(() => saslprep('a\u0487', {allowUnassigned: true})) -}) diff --git a/node_modules/saslprep/test/util.js b/node_modules/saslprep/test/util.js deleted file mode 100644 index fb39a85a18c780d3ac572b734e5de96513e91dd0..0000000000000000000000000000000000000000 --- a/node_modules/saslprep/test/util.js +++ /dev/null @@ -1,15 +0,0 @@ -import { setFlagsFromString } from 'v8' -import { range } from '../lib/util' -import test from 'ava' - -// 984 by default. -setFlagsFromString('--stack_size=500') - -test('should work', (t) => { - const list = range(1, 3) - t.deepEqual(list, [1, 2, 3]) -}) - -test('should work for large ranges', (t) => { - t.notThrows(() => range(1, 1e6)) -}) diff --git a/node_modules/semver/LICENSE b/node_modules/semver/LICENSE deleted file mode 100644 index 19129e315fe593965a2fdd50ec0d1253bcbd2ece..0000000000000000000000000000000000000000 --- a/node_modules/semver/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -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/semver/README.md b/node_modules/semver/README.md deleted file mode 100644 index e0edbb7333112c03d0c84d32efe844f6c2f44b1e..0000000000000000000000000000000000000000 --- a/node_modules/semver/README.md +++ /dev/null @@ -1,399 +0,0 @@ -semver(1) -- The semantic versioner for npm -=========================================== - -## Install - -```bash -npm install --save semver -```` - -## Usage - -As a node module: - -```js -const semver = require('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 -semver.valid(semver.coerce('v2')) // '2.0.0' -semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' -``` - -As a command-line utility: - -``` -$ semver -h - -A JavaScript implementation of the http://semver.org/ specification -Copyright Isaac Z. Schlueter - -Usage: semver [options] <version> [<version> [...]] -Prints valid versions sorted by SemVer precedence - -Options: --r --range <range> - Print versions that match the specified range. - --i --increment [<level>] - 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> - Identifier to be used to prefix premajor, preminor, - prepatch or prerelease version increments. - --l --loose - Interpret versions and ranges loosely - --p --include-prerelease - Always include prerelease versions in range matching - --c --coerce - Coerce a string into SemVer if possible - (does not imply --loose) - -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. -``` - -## Versions - -A "version" is described by the `v2.0.0` specification found at -<http://semver.org/>. - -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', 'prerelease', 'beta') -// '1.2.4-beta.0' -``` - -command-line example: - -```bash -$ semver 1.2.3 -i prerelease --preid beta -1.2.4-beta.0 -``` - -Which then can be used to increment further: - -```bash -$ 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` - -### Range Grammar - -Putting all this together, here is a Backus-Naur grammar for ranges, -for the benefit of parser authors: - -```bnf -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ -``` - -## Functions - -All methods and classes take a final `options` object argument. All -options in this object are `false` by default. The options supported -are: - -- `loose` Be more forgiving about not-quite-valid semver strings. - (Any resulting output will always be 100% strict compliant, of - course.) For backwards compatibility reasons, if the `options` - argument is a boolean value instead of an object, it is interpreted - to be the `loose` param. -- `includePrerelease` Set to suppress the [default - behavior](https://github.com/npm/node-semver#prerelease-tags) of - excluding prerelease tagged versions from ranges unless they are - explicitly opted into. - -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. -* `prerelease(v)`: Returns an array of prerelease components, or null - if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` -* `major(v)`: Return the major version number. -* `minor(v)`: Return the minor version number. -* `patch(v)`: Return the patch version number. -* `intersects(r1, r2, loose)`: Return true if the two supplied ranges - or comparators intersect. - -### 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. - -### Comparators - -* `intersects(comparator)`: Return true if the comparators intersect - -### 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. -* `minSatisfying(versions, range)`: Return the lowest 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`.) -* `intersects(range)`: Return true if any of the ranges comparators intersect - -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. - -### Coercion - -* `coerce(version)`: Coerces a string to semver if possible - -This aims to provide a very forgiving translation of a non-semver -string to semver. It looks for the first digit in a string, and -consumes all remaining characters which satisfy at least a partial semver -(e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). -Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). -All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). -Only text which lacks digits will fail coercion (`version one` is not valid). -The maximum length for any semver component considered for coercion is 16 characters; -longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). -The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; -higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). diff --git a/node_modules/semver/bin/semver b/node_modules/semver/bin/semver deleted file mode 100755 index 9100ed42b8821d1ee8c9bd244a5e38dc93cdc647..0000000000000000000000000000000000000000 --- a/node_modules/semver/bin/semver +++ /dev/null @@ -1,153 +0,0 @@ -#!/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 - , includePrerelease = false - , coerce = false - , identifier = undefined - , semver = require("../semver") - , reverse = false - , options = {} - -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 "-p": case "--include-prerelease": - includePrerelease = 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 "-c": case "--coerce": - coerce = true - break - case "-h": case "--help": case "-?": - return help() - default: - versions.push(a) - break - } - } - - var options = { loose: loose, includePrerelease: includePrerelease } - - versions = versions.map(function (v) { - return coerce ? (semver.coerce(v) || {version: v}).version : v - }).filter(function (v) { - return semver.valid(v) - }) - 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], options) - }) - 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, options) - }).map(function (v) { - return semver.clean(v, options) - }).map(function (v) { - return inc ? semver.inc(v, inc, options, 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] <version> [<version> [...]]" - ,"Prints valid versions sorted by SemVer precedence" - ,"" - ,"Options:" - ,"-r --range <range>" - ," Print versions that match the specified range." - ,"" - ,"-i --increment [<level>]" - ," 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>" - ," Identifier to be used to prefix premajor, preminor," - ," prepatch or prerelease version increments." - ,"" - ,"-l --loose" - ," Interpret versions and ranges loosely" - ,"" - ,"-p --include-prerelease" - ," Always include prerelease versions in range matching" - ,"" - ,"-c --coerce" - ," Coerce a string into SemVer if possible" - ," (does not imply --loose)" - ,"" - ,"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/semver/package.json b/node_modules/semver/package.json deleted file mode 100644 index 1c2d17a0f0bbe08a39c048df8c00f6633896abf5..0000000000000000000000000000000000000000 --- a/node_modules/semver/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "_from": "semver@^5.1.0", - "_id": "semver@5.6.0", - "_inBundle": false, - "_integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==", - "_location": "/semver", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "semver@^5.1.0", - "name": "semver", - "escapedName": "semver", - "rawSpec": "^5.1.0", - "saveSpec": null, - "fetchSpec": "^5.1.0" - }, - "_requiredBy": [ - "/require_optional" - ], - "_resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", - "_shasum": "7e74256fbaa49c75aa7c7a205cc22799cac80004", - "_spec": "semver@^5.1.0", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/require_optional", - "bin": { - "semver": "./bin/semver" - }, - "bugs": { - "url": "https://github.com/npm/node-semver/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "The semantic version parser used by npm.", - "devDependencies": { - "tap": "^12.0.1" - }, - "files": [ - "bin", - "range.bnf", - "semver.js" - ], - "homepage": "https://github.com/npm/node-semver#readme", - "license": "ISC", - "main": "semver.js", - "name": "semver", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/node-semver.git" - }, - "scripts": { - "test": "tap test/*.js --cov -J" - }, - "version": "5.6.0" -} diff --git a/node_modules/semver/range.bnf b/node_modules/semver/range.bnf deleted file mode 100644 index d4c6ae0d76c9ac0c10c93062e5ff9cec277b07cd..0000000000000000000000000000000000000000 --- a/node_modules/semver/range.bnf +++ /dev/null @@ -1,16 +0,0 @@ -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | [1-9] ( [0-9] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/semver/semver.js b/node_modules/semver/semver.js deleted file mode 100644 index 0cc57350c2c8e8a4368024adea01c60ef6d67b38..0000000000000000000000000000000000000000 --- a/node_modules/semver/semver.js +++ /dev/null @@ -1,1352 +0,0 @@ -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; - -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16; - -// 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] + '$'; - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++; -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])'; - -// 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, options) { - if (!options || typeof options !== 'object') - options = { loose: !!options, includePrerelease: false } - - if (version instanceof SemVer) - return version; - - if (typeof version !== 'string') - return null; - - if (version.length > MAX_LENGTH) - return null; - - var r = options.loose ? re[LOOSE] : re[FULL]; - if (!r.test(version)) - return null; - - try { - return new SemVer(version, options); - } catch (er) { - return null; - } -} - -exports.valid = valid; -function valid(version, options) { - var v = parse(version, options); - return v ? v.version : null; -} - - -exports.clean = clean; -function clean(version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null; -} - -exports.SemVer = SemVer; - -function SemVer(version, options) { - if (!options || typeof options !== 'object') - options = { loose: !!options, includePrerelease: false } - if (version instanceof SemVer) { - if (version.loose === options.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, options); - - debug('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - - var m = version.trim().match(options.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.toString = function() { - return this.version; -}; - -SemVer.prototype.compare = function(other) { - debug('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer)) - other = new SemVer(other, this.options); - - return this.compareMain(other) || this.comparePre(other); -}; - -SemVer.prototype.compareMain = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.options); - - 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.options); - - // 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(); - this.raw = this.version; - 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(new SemVer(b, loose)); -} - -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, options) { - if (!options || typeof options !== 'object') - options = { loose: !!options, includePrerelease: false } - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) - return comp; - else - comp = comp.value; - } - - if (!(this instanceof Comparator)) - return new Comparator(comp, options); - - debug('comparator', comp, options); - this.options = options; - this.loose = !!options.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.options.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.options.loose); -}; - -Comparator.prototype.toString = function() { - return this.value; -}; - -Comparator.prototype.test = function(version) { - debug('Comparator.test', version, this.options.loose); - - if (this.semver === ANY) - return true; - - if (typeof version === 'string') - version = new SemVer(version, this.options); - - return cmp(version, this.operator, this.semver, this.options); -}; - -Comparator.prototype.intersects = function(comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required'); - } - - if (!options || typeof options !== 'object') - options = { loose: !!options, includePrerelease: false } - - var rangeTmp; - - if (this.operator === '') { - rangeTmp = new Range(comp.value, options); - return satisfies(this.value, rangeTmp, options); - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options); - return satisfies(comp.semver, rangeTmp, options); - } - - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - var sameSemVer = this.semver.version === comp.semver.version; - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')); - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')); - - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; -}; - - -exports.Range = Range; -function Range(range, options) { - if (!options || typeof options !== 'object') - options = { loose: !!options, includePrerelease: false } - - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range; - } else { - return new Range(range.raw, options); - } - } - - if (range instanceof Comparator) { - return new Range(range.value, options); - } - - if (!(this instanceof Range)) - return new Range(range, options); - - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease - - // 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.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.options.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); - 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, this.options); - }, this).join(' ').split(/\s+/); - if (this.options.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, this.options); - }, this); - - return set; -}; - -Range.prototype.intersects = function(range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required'); - } - - return this.set.some(function(thisComparators) { - return thisComparators.every(function(thisComparator) { - return range.set.some(function(rangeComparators) { - return rangeComparators.every(function(rangeComparator) { - return thisComparator.intersects(rangeComparator, options); - }); - }); - }); - }); -}; - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators; -function toComparators(range, options) { - return new Range(range, options).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, options) { - debug('comp', comp, options); - comp = replaceCarets(comp, options); - debug('caret', comp); - comp = replaceTildes(comp, options); - debug('tildes', comp); - comp = replaceXRanges(comp, options); - debug('xrange', comp); - comp = replaceStars(comp, options); - 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, options) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceTilde(comp, options); - }).join(' '); -} - -function replaceTilde(comp, options) { - if (!options || typeof options !== 'object') - options = { loose: !!options, includePrerelease: false } - var r = options.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, options) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceCaret(comp, options); - }).join(' '); -} - -function replaceCaret(comp, options) { - debug('caret', comp, options); - if (!options || typeof options !== 'object') - options = { loose: !!options, includePrerelease: false } - var r = options.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, options) { - debug('replaceXRanges', comp, options); - return comp.split(/\s+/).map(function(comp) { - return replaceXRange(comp, options); - }).join(' '); -} - -function replaceXRange(comp, options) { - comp = comp.trim(); - if (!options || typeof options !== 'object') - options = { loose: !!options, includePrerelease: false } - var r = options.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, options) { - debug('replaceStars', comp, options); - // 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.options); - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) - return true; - } - return false; -}; - -function testSet(set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) - return false; - } - - if (!options) - options = {} - - if (version.prerelease.length && !options.includePrerelease) { - // 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, options) { - try { - range = new Range(range, options); - } catch (er) { - return false; - } - return range.test(version); -} - -exports.maxSatisfying = maxSatisfying; -function maxSatisfying(versions, range, options) { - var max = null; - var maxSV = null; - try { - var rangeObj = new Range(range, options); - } catch (er) { - return null; - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) - max = v; - maxSV = new SemVer(max, options); - } - } - }) - return max; -} - -exports.minSatisfying = minSatisfying; -function minSatisfying(versions, range, options) { - var min = null; - var minSV = null; - try { - var rangeObj = new Range(range, options); - } catch (er) { - return null; - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { // compare(min, v, true) - min = v; - minSV = new SemVer(min, options); - } - } - }) - return min; -} - -exports.validRange = validRange; -function validRange(range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).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, options) { - return outside(version, range, '<', options); -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr; -function gtr(version, range, options) { - return outside(version, range, '>', options); -} - -exports.outside = outside; -function outside(version, range, hilo, options) { - version = new SemVer(version, options); - range = new Range(range, options); - - 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, options)) { - 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, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - 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; -} - -exports.prerelease = prerelease; -function prerelease(version, options) { - var parsed = parse(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; -} - -exports.intersects = intersects; -function intersects(r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} - -exports.coerce = coerce; -function coerce(version) { - if (version instanceof SemVer) - return version; - - if (typeof version !== 'string') - return null; - - var match = version.match(re[COERCE]); - - if (match == null) - return null; - - return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0')); -} diff --git a/node_modules/sliced/History.md b/node_modules/sliced/History.md deleted file mode 100644 index e45cefe8f78d614226923c3d4b9b025e65cda5db..0000000000000000000000000000000000000000 --- a/node_modules/sliced/History.md +++ /dev/null @@ -1,41 +0,0 @@ - -1.0.1 / 2015-07-14 -================== - - * fixed; missing file introduced in 4f5cea1 - -1.0.0 / 2015-07-12 -================== - - * Remove unnecessary files from npm package - #6 via joaquimserafim - * updated readme stats - -0.0.5 / 2013-02-05 -================== - - * optimization: remove use of arguments [jkroso](https://github.com/jkroso) - * add scripts to component.json [jkroso](https://github.com/jkroso) - * tests; remove time for travis - -0.0.4 / 2013-01-07 -================== - - * added component.json #1 [jkroso](https://github.com/jkroso) - * reversed array loop #1 [jkroso](https://github.com/jkroso) - * remove fn params - -0.0.3 / 2012-09-29 -================== - - * faster with negative start args - -0.0.2 / 2012-09-29 -================== - - * support full [].slice semantics - -0.0.1 / 2012-09-29 -=================== - - * initial release - diff --git a/node_modules/sliced/README.md b/node_modules/sliced/README.md deleted file mode 100644 index b6ff85eb2b562fa177d8e6ddd01fbae0cc0a3ef8..0000000000000000000000000000000000000000 --- a/node_modules/sliced/README.md +++ /dev/null @@ -1,62 +0,0 @@ -#sliced -========== - -A faster alternative to `[].slice.call(arguments)`. - -[](http://travis-ci.org/aheckmann/sliced) - -Example output from [benchmark.js](https://github.com/bestiejs/benchmark.js) - - Array.prototype.slice.call x 1,401,820 ops/sec ±2.16% (90 runs sampled) - [].slice.call x 1,313,116 ops/sec ±2.04% (96 runs sampled) - cached slice.call x 10,297,910 ops/sec ±1.81% (96 runs sampled) - sliced x 19,906,019 ops/sec ±1.23% (89 runs sampled) - fastest is sliced - - Array.prototype.slice.call(arguments, 1) x 1,373,238 ops/sec ±1.84% (95 runs sampled) - [].slice.call(arguments, 1) x 1,395,336 ops/sec ±1.36% (93 runs sampled) - cached slice.call(arguments, 1) x 9,926,018 ops/sec ±1.67% (92 runs sampled) - sliced(arguments, 1) x 20,747,990 ops/sec ±1.16% (93 runs sampled) - fastest is sliced(arguments, 1) - - Array.prototype.slice.call(arguments, -1) x 1,319,908 ops/sec ±2.12% (91 runs sampled) - [].slice.call(arguments, -1) x 1,336,170 ops/sec ±1.33% (97 runs sampled) - cached slice.call(arguments, -1) x 10,078,718 ops/sec ±1.21% (98 runs sampled) - sliced(arguments, -1) x 20,471,474 ops/sec ±1.81% (92 runs sampled) - fastest is sliced(arguments, -1) - - Array.prototype.slice.call(arguments, -2, -10) x 1,369,246 ops/sec ±1.68% (97 runs sampled) - [].slice.call(arguments, -2, -10) x 1,387,935 ops/sec ±1.70% (95 runs sampled) - cached slice.call(arguments, -2, -10) x 9,593,428 ops/sec ±1.23% (97 runs sampled) - sliced(arguments, -2, -10) x 23,178,931 ops/sec ±1.70% (92 runs sampled) - fastest is sliced(arguments, -2, -10) - - Array.prototype.slice.call(arguments, -2, -1) x 1,441,300 ops/sec ±1.26% (98 runs sampled) - [].slice.call(arguments, -2, -1) x 1,410,326 ops/sec ±1.96% (93 runs sampled) - cached slice.call(arguments, -2, -1) x 9,854,419 ops/sec ±1.02% (97 runs sampled) - sliced(arguments, -2, -1) x 22,550,801 ops/sec ±1.86% (91 runs sampled) - fastest is sliced(arguments, -2, -1) - -_Benchmark [source](https://github.com/aheckmann/sliced/blob/master/bench.js)._ - -##Usage - -`sliced` accepts the same arguments as `Array#slice` so you can easily swap it out. - -```js -function zing () { - var slow = [].slice.call(arguments, 1, 8); - var args = slice(arguments, 1, 8); - - var slow = Array.prototype.slice.call(arguments); - var args = slice(arguments); - // etc -} -``` - -## install - - npm install sliced - - -[LICENSE](https://github.com/aheckmann/sliced/blob/master/LICENSE) diff --git a/node_modules/sliced/index.js b/node_modules/sliced/index.js deleted file mode 100644 index d88c85b102633777e98f93535f1c5957b7cfe889..0000000000000000000000000000000000000000 --- a/node_modules/sliced/index.js +++ /dev/null @@ -1,33 +0,0 @@ - -/** - * An Array.prototype.slice.call(arguments) alternative - * - * @param {Object} args something with a length - * @param {Number} slice - * @param {Number} sliceEnd - * @api public - */ - -module.exports = function (args, slice, sliceEnd) { - var ret = []; - var len = args.length; - - if (0 === len) return ret; - - var start = slice < 0 - ? Math.max(0, slice + len) - : slice || 0; - - if (sliceEnd !== undefined) { - len = sliceEnd < 0 - ? sliceEnd + len - : sliceEnd - } - - while (len-- > start) { - ret[len - start] = args[len]; - } - - return ret; -} - diff --git a/node_modules/sliced/package.json b/node_modules/sliced/package.json deleted file mode 100644 index 96b8b8a9ab59df206b5185ab461b6a2ea6bc3d3e..0000000000000000000000000000000000000000 --- a/node_modules/sliced/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "_from": "sliced@1.0.1", - "_id": "sliced@1.0.1", - "_inBundle": false, - "_integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E=", - "_location": "/sliced", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "sliced@1.0.1", - "name": "sliced", - "escapedName": "sliced", - "rawSpec": "1.0.1", - "saveSpec": null, - "fetchSpec": "1.0.1" - }, - "_requiredBy": [ - "/mongoose", - "/mquery" - ], - "_resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", - "_shasum": "0b3a662b5d04c3177b1926bea82b03f837a2ef41", - "_spec": "sliced@1.0.1", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mongoose", - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "bugs": { - "url": "https://github.com/aheckmann/sliced/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", - "devDependencies": { - "benchmark": "~1.0.0", - "mocha": "1.5.0" - }, - "files": [ - "LICENSE", - "README.md", - "index.js" - ], - "homepage": "https://github.com/aheckmann/sliced#readme", - "keywords": [ - "arguments", - "slice", - "array" - ], - "license": "MIT", - "main": "index.js", - "name": "sliced", - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/sliced.git" - }, - "scripts": { - "test": "make test" - }, - "version": "1.0.1" -} diff --git a/node_modules/sparse-bitfield/.npmignore b/node_modules/sparse-bitfield/.npmignore deleted file mode 100644 index 3c3629e647f5ddf82548912e337bea9826b434af..0000000000000000000000000000000000000000 --- a/node_modules/sparse-bitfield/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/sparse-bitfield/.travis.yml b/node_modules/sparse-bitfield/.travis.yml deleted file mode 100644 index c0428217037e472e73fc90e620d9f71bae940c31..0000000000000000000000000000000000000000 --- a/node_modules/sparse-bitfield/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - '0.10' - - '0.12' - - '4.0' - - '5.0' diff --git a/node_modules/sparse-bitfield/LICENSE b/node_modules/sparse-bitfield/LICENSE deleted file mode 100644 index bae9da7bfae2b5e22cfb0945b362b23ca822c8bb..0000000000000000000000000000000000000000 --- a/node_modules/sparse-bitfield/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 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. diff --git a/node_modules/sparse-bitfield/README.md b/node_modules/sparse-bitfield/README.md deleted file mode 100644 index 7b6b8f9ed33bc995571f0138ac1450b7420a6642..0000000000000000000000000000000000000000 --- a/node_modules/sparse-bitfield/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# sparse-bitfield - -Bitfield implementation that allocates a series of 1kb buffers to support sparse bitfields -without allocating a massive buffer. If you want to simple implementation of a flat bitfield -see the [bitfield](https://github.com/fb55/bitfield) module. - -This module is mostly useful if you need a big bitfield where you won't nessecarily set every bit. - -``` -npm install sparse-bitfield -``` - -[](http://travis-ci.org/mafintosh/sparse-bitfield) - -## Usage - -``` js -var bitfield = require('sparse-bitfield') -var bits = bitfield() - -bits.set(0, true) // set first bit -bits.set(1, true) // set second bit -bits.set(1000000000000, true) // set the 1.000.000.000.000th bit -``` - -Running the above example will allocate two 1kb buffers internally. -Each 1kb buffer can hold information about 8192 bits so the first one will be used to store information about the first two bits and the second will be used to store the 1.000.000.000.000th bit. - -## API - -#### `var bits = bitfield([options])` - -Create a new bitfield. Options include - -``` js -{ - pageSize: 1024, // how big should the partial buffers be - buffer: anExistingBitfield, - trackUpdates: false // track when pages are being updated in the pager -} -``` - -#### `bits.set(index, value)` - -Set a bit to true or false. - -#### `bits.get(index)` - -Get the value of a bit. - -#### `bits.pages` - -A [memory-pager](https://github.com/mafintosh/memory-pager) instance that is managing the underlying memory. -If you set `trackUpdates` to true in the constructor you can use `.lastUpdate()` on this instance to get the last updated memory page. - -#### `var buffer = bits.toBuffer()` - -Get a single buffer representing the entire bitfield. - -## License - -MIT diff --git a/node_modules/sparse-bitfield/index.js b/node_modules/sparse-bitfield/index.js deleted file mode 100644 index ff458c974fcd4e6051b44b3ae2e4674c3ce70b01..0000000000000000000000000000000000000000 --- a/node_modules/sparse-bitfield/index.js +++ /dev/null @@ -1,95 +0,0 @@ -var pager = require('memory-pager') - -module.exports = Bitfield - -function Bitfield (opts) { - if (!(this instanceof Bitfield)) return new Bitfield(opts) - if (!opts) opts = {} - if (Buffer.isBuffer(opts)) opts = {buffer: opts} - - this.pageOffset = opts.pageOffset || 0 - this.pageSize = opts.pageSize || 1024 - this.pages = opts.pages || pager(this.pageSize) - - this.byteLength = this.pages.length * this.pageSize - this.length = 8 * this.byteLength - - if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') - - this._trackUpdates = !!opts.trackUpdates - this._pageMask = this.pageSize - 1 - - if (opts.buffer) { - for (var i = 0; i < opts.buffer.length; i += this.pageSize) { - this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) - } - this.byteLength = opts.buffer.length - this.length = 8 * this.byteLength - } -} - -Bitfield.prototype.get = function (i) { - var o = i & 7 - var j = (i - o) / 8 - - return !!(this.getByte(j) & (128 >> o)) -} - -Bitfield.prototype.getByte = function (i) { - var o = i & this._pageMask - var j = (i - o) / this.pageSize - var page = this.pages.get(j, true) - - return page ? page.buffer[o + this.pageOffset] : 0 -} - -Bitfield.prototype.set = function (i, v) { - var o = i & 7 - var j = (i - o) / 8 - var b = this.getByte(j) - - return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) -} - -Bitfield.prototype.toBuffer = function () { - var all = alloc(this.pages.length * this.pageSize) - - for (var i = 0; i < this.pages.length; i++) { - var next = this.pages.get(i, true) - var allOffset = i * this.pageSize - if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) - } - - return all -} - -Bitfield.prototype.setByte = function (i, b) { - var o = i & this._pageMask - var j = (i - o) / this.pageSize - var page = this.pages.get(j, false) - - o += this.pageOffset - - if (page.buffer[o] === b) return false - page.buffer[o] = b - - if (i >= this.byteLength) { - this.byteLength = i + 1 - this.length = this.byteLength * 8 - } - - if (this._trackUpdates) this.pages.updated(page) - - return true -} - -function alloc (n) { - if (Buffer.alloc) return Buffer.alloc(n) - var b = new Buffer(n) - b.fill(0) - return b -} - -function powerOfTwo (x) { - return !(x & (x - 1)) -} diff --git a/node_modules/sparse-bitfield/package.json b/node_modules/sparse-bitfield/package.json deleted file mode 100644 index 886eccdc5ef9671b59ee8598a888489af1fc0fe9..0000000000000000000000000000000000000000 --- a/node_modules/sparse-bitfield/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "_from": "sparse-bitfield@^3.0.3", - "_id": "sparse-bitfield@3.0.3", - "_inBundle": false, - "_integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", - "_location": "/sparse-bitfield", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "sparse-bitfield@^3.0.3", - "name": "sparse-bitfield", - "escapedName": "sparse-bitfield", - "rawSpec": "^3.0.3", - "saveSpec": null, - "fetchSpec": "^3.0.3" - }, - "_requiredBy": [ - "/saslprep" - ], - "_resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", - "_shasum": "ff4ae6e68656056ba4b3e792ab3334d38273ca11", - "_spec": "sparse-bitfield@^3.0.3", - "_where": "/home/capsule_man/developpement/happy-botday/node_modules/saslprep", - "author": { - "name": "Mathias Buus", - "url": "@mafintosh" - }, - "bugs": { - "url": "https://github.com/mafintosh/sparse-bitfield/issues" - }, - "bundleDependencies": false, - "dependencies": { - "memory-pager": "^1.0.2" - }, - "deprecated": false, - "description": "Bitfield that allocates a series of small buffers to support sparse bits without allocating a massive buffer", - "devDependencies": { - "buffer-alloc": "^1.1.0", - "standard": "^9.0.0", - "tape": "^4.6.3" - }, - "homepage": "https://github.com/mafintosh/sparse-bitfield", - "license": "MIT", - "main": "index.js", - "name": "sparse-bitfield", - "repository": { - "type": "git", - "url": "git+https://github.com/mafintosh/sparse-bitfield.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "3.0.3" -} diff --git a/node_modules/sparse-bitfield/test.js b/node_modules/sparse-bitfield/test.js deleted file mode 100644 index ae42ef467309493e2a01cc51d567fae98382b5d4..0000000000000000000000000000000000000000 --- a/node_modules/sparse-bitfield/test.js +++ /dev/null @@ -1,79 +0,0 @@ -var alloc = require('buffer-alloc') -var tape = require('tape') -var bitfield = require('./') - -tape('set and get', function (t) { - var bits = bitfield() - - t.same(bits.get(0), false, 'first bit is false') - bits.set(0, true) - t.same(bits.get(0), true, 'first bit is true') - t.same(bits.get(1), false, 'second bit is false') - bits.set(0, false) - t.same(bits.get(0), false, 'first bit is reset') - t.end() -}) - -tape('set large and get', function (t) { - var bits = bitfield() - - t.same(bits.get(9999999999999), false, 'large bit is false') - bits.set(9999999999999, true) - t.same(bits.get(9999999999999), true, 'large bit is true') - t.same(bits.get(9999999999999 + 1), false, 'large bit + 1 is false') - bits.set(9999999999999, false) - t.same(bits.get(9999999999999), false, 'large bit is reset') - t.end() -}) - -tape('get and set buffer', function (t) { - var bits = bitfield({trackUpdates: true}) - - t.same(bits.pages.get(0, true), undefined) - t.same(bits.pages.get(Math.floor(9999999999999 / 8 / 1024), true), undefined) - bits.set(9999999999999, true) - - var bits2 = bitfield() - var upd = bits.pages.lastUpdate() - bits2.pages.set(Math.floor(upd.offset / 1024), upd.buffer) - t.same(bits2.get(9999999999999), true, 'bit is set') - t.end() -}) - -tape('toBuffer', function (t) { - var bits = bitfield() - - t.same(bits.toBuffer(), alloc(0)) - - bits.set(0, true) - - t.same(bits.toBuffer(), bits.pages.get(0).buffer) - - bits.set(9000, true) - - t.same(bits.toBuffer(), Buffer.concat([bits.pages.get(0).buffer, bits.pages.get(1).buffer])) - t.end() -}) - -tape('pass in buffer', function (t) { - var bits = bitfield() - - bits.set(0, true) - bits.set(9000, true) - - var clone = bitfield(bits.toBuffer()) - - t.same(clone.get(0), true) - t.same(clone.get(9000), true) - t.end() -}) - -tape('set small buffer', function (t) { - var buf = alloc(1) - buf[0] = 255 - var bits = bitfield(buf) - - t.same(bits.get(0), true) - t.same(bits.pages.get(0).buffer.length, bits.pageSize) - t.end() -}) diff --git a/node_modules/sqlstring/HISTORY.md b/node_modules/sqlstring/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..e2c7e51fdcc2045d77d879ff7d21a8bb528f44a1 --- /dev/null +++ b/node_modules/sqlstring/HISTORY.md @@ -0,0 +1,43 @@ +2.3.1 / 2018-02-24 +================== + + * Fix incorrectly replacing non-placeholders in SQL + +2.3.0 / 2017-10-01 +================== + + * Add `.toSqlString()` escape overriding + * Add `raw` method to wrap raw strings for escape overriding + * Small performance improvement on `escapeId` + +2.2.0 / 2016-11-01 +================== + + * Escape invalid `Date` objects as `NULL` + +2.1.0 / 2016-09-26 +================== + + * Accept numbers and other value types in `escapeId` + * Run `buffer.toString()` through escaping + +2.0.1 / 2016-06-06 +================== + + * Fix npm package to include missing `lib/` directory + +2.0.0 / 2016-06-06 +================== + + * Bring repository up-to-date with `mysql` module changes + * Support Node.js 0.6.x + +1.0.0 / 2014-11-09 +================== + + * Support Node.js 0.8.x + +0.0.1 / 2014-02-25 +================== + + * Initial release diff --git a/node_modules/sqlstring/LICENSE b/node_modules/sqlstring/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c7ff12a2f8af2e2c57f39da1754409c25b35f46a --- /dev/null +++ b/node_modules/sqlstring/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/sqlstring/README.md b/node_modules/sqlstring/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fafe6f4b58addfeff1c6bb48a3ea0e1c9c8e95ec --- /dev/null +++ b/node_modules/sqlstring/README.md @@ -0,0 +1,206 @@ +# sqlstring + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Simple SQL escape and format for MySQL + +## Install + +```sh +$ npm install sqlstring +``` + +## Usage + +<!-- eslint-disable no-unused-vars --> + +```js +var SqlString = require('sqlstring'); +``` + +### Escaping query values + +**Caution** These methods of escaping values only works when the +[NO_BACKSLASH_ESCAPES](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_backslash_escapes) +SQL mode is disabled (which is the default state for MySQL servers). + +In order to avoid SQL Injection attacks, you should always escape any user +provided data before using it inside a SQL query. You can do so using the +`SqlString.escape()` method: + +```js +var userId = 'some user provided value'; +var sql = 'SELECT * FROM users WHERE id = ' + SqlString.escape(userId); +console.log(sql); // SELECT * FROM users WHERE id = 'some user provided value' +``` + +Alternatively, you can use `?` characters as placeholders for values you would +like to have escaped like this: + +```js +var userId = 1; +var sql = SqlString.format('SELECT * FROM users WHERE id = ?', [userId]); +console.log(sql); // SELECT * FROM users WHERE id = 1 +``` + +Multiple placeholders are mapped to values in the same order as passed. For example, +in the following query `foo` equals `a`, `bar` equals `b`, `baz` equals `c`, and +`id` will be `userId`: + +```js +var userId = 1; +var sql = SqlString.format('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', + ['a', 'b', 'c', userId]); +console.log(sql); // UPDATE users SET foo = 'a', bar = 'b', baz = 'c' WHERE id = 1 +``` + +This looks similar to prepared statements in MySQL, however it really just uses +the same `SqlString.escape()` method internally. + +**Caution** This also differs from prepared statements in that all `?` are +replaced, even those contained in comments and strings. + +Different value types are escaped differently, here is how: + +* Numbers are left untouched +* Booleans are converted to `true` / `false` +* Date objects are converted to `'YYYY-mm-dd HH:ii:ss'` strings +* Buffers are converted to hex strings, e.g. `X'0fa5'` +* Strings are safely escaped +* Arrays are turned into list, e.g. `['a', 'b']` turns into `'a', 'b'` +* Nested arrays are turned into grouped lists (for bulk inserts), e.g. `[['a', + 'b'], ['c', 'd']]` turns into `('a', 'b'), ('c', 'd')` +* Objects that have a `toSqlString` method will have `.toSqlString()` called + and the returned value is used as the raw SQL. +* Objects are turned into `key = 'val'` pairs for each enumerable property on + the object. If the property's value is a function, it is skipped; if the + property's value is an object, toString() is called on it and the returned + value is used. +* `undefined` / `null` are converted to `NULL` +* `NaN` / `Infinity` are left as-is. MySQL does not support these, and trying + to insert them as values will trigger MySQL errors until they implement + support. + +You may have noticed that this escaping allows you to do neat things like this: + +```js +var post = {id: 1, title: 'Hello MySQL'}; +var sql = SqlString.format('INSERT INTO posts SET ?', post); +console.log(sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL' +``` + +And the `toSqlString` method allows you to form complex queries with functions: + +```js +var CURRENT_TIMESTAMP = { toSqlString: function() { return 'CURRENT_TIMESTAMP()'; } }; +var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 +``` + +To generate objects with a `toSqlString` method, the `SqlString.raw()` method can +be used. This creates an object that will be left un-touched when using in a `?` +placeholder, useful for using functions as dynamic values: + +**Caution** The string provided to `SqlString.raw()` will skip all escaping +functions when used, so be careful when passing in unvalidated input. + +```js +var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()'); +var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 +``` + +If you feel the need to escape queries by yourself, you can also use the escaping +function directly: + +```js +var sql = 'SELECT * FROM posts WHERE title=' + SqlString.escape('Hello MySQL'); +console.log(sql); // SELECT * FROM posts WHERE title='Hello MySQL' +``` + +### Escaping query identifiers + +If you can't trust an SQL identifier (database / table / column name) because it is +provided by a user, you should escape it with `SqlString.escapeId(identifier)` like this: + +```js +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter); +console.log(sql); // SELECT * FROM posts ORDER BY `date` +``` + +It also supports adding qualified identifiers. It will escape both parts. + +```js +var sorter = 'date'; +var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId('posts.' + sorter); +console.log(sql); // SELECT * FROM posts ORDER BY `posts`.`date` +``` + +If you do not want to treat `.` as qualified identifiers, you can set the second +argument to `true` in order to keep the string as a literal identifier: + +```js +var sorter = 'date.2'; +var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter, true); +console.log(sql); // SELECT * FROM posts ORDER BY `date.2` +``` + +Alternatively, you can use `??` characters as placeholders for identifiers you would +like to have escaped like this: + +```js +var userId = 1; +var columns = ['username', 'email']; +var sql = SqlString.format('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId]); +console.log(sql); // SELECT `username`, `email` FROM `users` WHERE id = 1 +``` +**Please note that this last character sequence is experimental and syntax might change** + +When you pass an Object to `.escape()` or `.format()`, `.escapeId()` is used to avoid SQL injection in object keys. + +### Formatting queries + +You can use `SqlString.format` to prepare a query with multiple insertion points, +utilizing the proper escaping for ids and values. A simple example of this follows: + +```js +var userId = 1; +var inserts = ['users', 'id', userId]; +var sql = SqlString.format('SELECT * FROM ?? WHERE ?? = ?', inserts); +console.log(sql); // SELECT * FROM `users` WHERE `id` = 1 +``` + +Following this you then have a valid, escaped query that you can then send to the database safely. +This is useful if you are looking to prepare the query before actually sending it to the database. +You also have the option (but are not required) to pass in `stringifyObject` and `timeZone`, +allowing you provide a custom means of turning objects into strings, as well as a +location-specific/timezone-aware `Date`. + +This can be further combined with the `SqlString.raw()` helper to generate SQL +that includes MySQL functions as dynamic vales: + +```js +var userId = 1; +var data = { email: 'foobar@example.com', modified: SqlString.raw('NOW()') }; +var sql = SqlString.format('UPDATE ?? SET ? WHERE `id` = ?', ['users', data, userId]); +console.log(sql); // UPDATE `users` SET `email` = 'foobar@example.com', `modified` = NOW() WHERE `id` = 1 +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/sqlstring.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/sqlstring.svg +[npm-url]: https://npmjs.org/package/sqlstring +[travis-image]: https://img.shields.io/travis/mysqljs/sqlstring/master.svg +[travis-url]: https://travis-ci.org/mysqljs/sqlstring +[coveralls-image]: https://img.shields.io/coveralls/mysqljs/sqlstring/master.svg +[coveralls-url]: https://coveralls.io/r/mysqljs/sqlstring?branch=master +[node-image]: https://img.shields.io/node/v/sqlstring.svg +[node-url]: https://nodejs.org/en/download diff --git a/node_modules/sqlstring/index.js b/node_modules/sqlstring/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4ef5944ef471391f9e82627b9e395b394fae8ea4 --- /dev/null +++ b/node_modules/sqlstring/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/SqlString'); diff --git a/node_modules/sqlstring/lib/SqlString.js b/node_modules/sqlstring/lib/SqlString.js new file mode 100644 index 0000000000000000000000000000000000000000..419adec0d787c96832b47b94ecde884c89585206 --- /dev/null +++ b/node_modules/sqlstring/lib/SqlString.js @@ -0,0 +1,237 @@ +var SqlString = exports; + +var ID_GLOBAL_REGEXP = /`/g; +var QUAL_GLOBAL_REGEXP = /\./g; +var CHARS_GLOBAL_REGEXP = /[\0\b\t\n\r\x1a\"\'\\]/g; // eslint-disable-line no-control-regex +var CHARS_ESCAPE_MAP = { + '\0' : '\\0', + '\b' : '\\b', + '\t' : '\\t', + '\n' : '\\n', + '\r' : '\\r', + '\x1a' : '\\Z', + '"' : '\\"', + '\'' : '\\\'', + '\\' : '\\\\' +}; + +SqlString.escapeId = function escapeId(val, forbidQualified) { + if (Array.isArray(val)) { + var sql = ''; + + for (var i = 0; i < val.length; i++) { + sql += (i === 0 ? '' : ', ') + SqlString.escapeId(val[i], forbidQualified); + } + + return sql; + } else if (forbidQualified) { + return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``') + '`'; + } else { + return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``').replace(QUAL_GLOBAL_REGEXP, '`.`') + '`'; + } +}; + +SqlString.escape = function escape(val, stringifyObjects, timeZone) { + if (val === undefined || val === null) { + return 'NULL'; + } + + switch (typeof val) { + case 'boolean': return (val) ? 'true' : 'false'; + case 'number': return val + ''; + case 'object': + if (val instanceof Date) { + return SqlString.dateToString(val, timeZone || 'local'); + } else if (Array.isArray(val)) { + return SqlString.arrayToList(val, timeZone); + } else if (Buffer.isBuffer(val)) { + return SqlString.bufferToString(val); + } else if (typeof val.toSqlString === 'function') { + return String(val.toSqlString()); + } else if (stringifyObjects) { + return escapeString(val.toString()); + } else { + return SqlString.objectToValues(val, timeZone); + } + default: return escapeString(val); + } +}; + +SqlString.arrayToList = function arrayToList(array, timeZone) { + var sql = ''; + + for (var i = 0; i < array.length; i++) { + var val = array[i]; + + if (Array.isArray(val)) { + sql += (i === 0 ? '' : ', ') + '(' + SqlString.arrayToList(val, timeZone) + ')'; + } else { + sql += (i === 0 ? '' : ', ') + SqlString.escape(val, true, timeZone); + } + } + + return sql; +}; + +SqlString.format = function format(sql, values, stringifyObjects, timeZone) { + if (values == null) { + return sql; + } + + if (!(values instanceof Array || Array.isArray(values))) { + values = [values]; + } + + var chunkIndex = 0; + var placeholdersRegex = /\?+/g; + var result = ''; + var valuesIndex = 0; + var match; + + while (valuesIndex < values.length && (match = placeholdersRegex.exec(sql))) { + var len = match[0].length; + + if (len > 2) { + continue; + } + + var value = len === 2 + ? SqlString.escapeId(values[valuesIndex]) + : SqlString.escape(values[valuesIndex], stringifyObjects, timeZone); + + result += sql.slice(chunkIndex, match.index) + value; + chunkIndex = placeholdersRegex.lastIndex; + valuesIndex++; + } + + if (chunkIndex === 0) { + // Nothing was replaced + return sql; + } + + if (chunkIndex < sql.length) { + return result + sql.slice(chunkIndex); + } + + return result; +}; + +SqlString.dateToString = function dateToString(date, timeZone) { + var dt = new Date(date); + + if (isNaN(dt.getTime())) { + return 'NULL'; + } + + var year; + var month; + var day; + var hour; + var minute; + var second; + var millisecond; + + if (timeZone === 'local') { + year = dt.getFullYear(); + month = dt.getMonth() + 1; + day = dt.getDate(); + hour = dt.getHours(); + minute = dt.getMinutes(); + second = dt.getSeconds(); + millisecond = dt.getMilliseconds(); + } else { + var tz = convertTimezone(timeZone); + + if (tz !== false && tz !== 0) { + dt.setTime(dt.getTime() + (tz * 60000)); + } + + year = dt.getUTCFullYear(); + month = dt.getUTCMonth() + 1; + day = dt.getUTCDate(); + hour = dt.getUTCHours(); + minute = dt.getUTCMinutes(); + second = dt.getUTCSeconds(); + millisecond = dt.getUTCMilliseconds(); + } + + // YYYY-MM-DD HH:mm:ss.mmm + var str = zeroPad(year, 4) + '-' + zeroPad(month, 2) + '-' + zeroPad(day, 2) + ' ' + + zeroPad(hour, 2) + ':' + zeroPad(minute, 2) + ':' + zeroPad(second, 2) + '.' + + zeroPad(millisecond, 3); + + return escapeString(str); +}; + +SqlString.bufferToString = function bufferToString(buffer) { + return 'X' + escapeString(buffer.toString('hex')); +}; + +SqlString.objectToValues = function objectToValues(object, timeZone) { + var sql = ''; + + for (var key in object) { + var val = object[key]; + + if (typeof val === 'function') { + continue; + } + + sql += (sql.length === 0 ? '' : ', ') + SqlString.escapeId(key) + ' = ' + SqlString.escape(val, true, timeZone); + } + + return sql; +}; + +SqlString.raw = function raw(sql) { + if (typeof sql !== 'string') { + throw new TypeError('argument sql must be a string'); + } + + return { + toSqlString: function toSqlString() { return sql; } + }; +}; + +function escapeString(val) { + var chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex = 0; + var escapedVal = ''; + var match; + + while ((match = CHARS_GLOBAL_REGEXP.exec(val))) { + escapedVal += val.slice(chunkIndex, match.index) + CHARS_ESCAPE_MAP[match[0]]; + chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex; + } + + if (chunkIndex === 0) { + // Nothing was escaped + return "'" + val + "'"; + } + + if (chunkIndex < val.length) { + return "'" + escapedVal + val.slice(chunkIndex) + "'"; + } + + return "'" + escapedVal + "'"; +} + +function zeroPad(number, length) { + number = number.toString(); + while (number.length < length) { + number = '0' + number; + } + + return number; +} + +function convertTimezone(tz) { + if (tz === 'Z') { + return 0; + } + + var m = tz.match(/([\+\-\s])(\d\d):?(\d\d)?/); + if (m) { + return (m[1] === '-' ? -1 : 1) * (parseInt(m[2], 10) + ((m[3] ? parseInt(m[3], 10) : 0) / 60)) * 60; + } + return false; +} diff --git a/node_modules/sqlstring/package.json b/node_modules/sqlstring/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6fecb78ba085d0529b954efa74e7618355ffe8c6 --- /dev/null +++ b/node_modules/sqlstring/package.json @@ -0,0 +1,98 @@ +{ + "_from": "sqlstring@2.3.1", + "_id": "sqlstring@2.3.1", + "_inBundle": false, + "_integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A=", + "_location": "/sqlstring", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "sqlstring@2.3.1", + "name": "sqlstring", + "escapedName": "sqlstring", + "rawSpec": "2.3.1", + "saveSpec": null, + "fetchSpec": "2.3.1" + }, + "_requiredBy": [ + "/mysql" + ], + "_resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz", + "_shasum": "475393ff9e91479aea62dcaf0ca3d14983a7fb40", + "_spec": "sqlstring@2.3.1", + "_where": "/home/capsule_man/developpement/happy-botday/node_modules/mysql", + "bugs": { + "url": "https://github.com/mysqljs/sqlstring/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Adri Van Houdt", + "email": "adri.van.houdt@gmail.com" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "fengmk2", + "email": "fengmk2@gmail.com", + "url": "http://fengmk2.github.com" + }, + { + "name": "Kevin Jose Martin", + "email": "kevin@tiliq.com" + }, + { + "name": "Nathan Woltman", + "email": "nwoltman@outlook.com" + }, + { + "name": "Sergej Sintschilin", + "email": "seregpie@gmail.com" + } + ], + "deprecated": false, + "description": "Simple SQL escape and format for MySQL", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "4.18.1", + "eslint-plugin-markdown": "1.0.0-beta.6", + "nyc": "10.3.2", + "urun": "0.0.8", + "utest": "0.0.8" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "homepage": "https://github.com/mysqljs/sqlstring#readme", + "keywords": [ + "sqlstring", + "sql", + "escape", + "sql escape" + ], + "license": "MIT", + "name": "sqlstring", + "repository": { + "type": "git", + "url": "git+https://github.com/mysqljs/sqlstring.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "node test/run.js", + "test-ci": "nyc --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "version": "2.3.1" +} diff --git a/package-lock.json b/package-lock.json index b1268b0c938001cb289fd13e4290e2404904724b..82edeaaa895d00c876d27bec36db5592ad88f5ce 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,24 @@ "lockfileVersion": 1, "requires": true, "dependencies": { + "@types/bluebird": { + "version": "3.5.25", + "resolved": "https://registry.npmjs.org/@types/bluebird/-/bluebird-3.5.25.tgz", + "integrity": "sha512-yfhIBix+AIFTmYGtkC0Bi+XGjSkOINykqKvO/Wqdz/DuXlAKK7HmhLAXdPIGsV4xzKcL3ev/zYc4yLNo+OvGaw==" + }, + "@types/mysql": { + "version": "2.15.5", + "resolved": "https://registry.npmjs.org/@types/mysql/-/mysql-2.15.5.tgz", + "integrity": "sha512-4QAISTUGZbcFh7bqdndo08xRdES5OTU+JODy8VCZbe1yiXyGjqw1H83G43XjQ3IbC10wn9xlGd44A5RXJwNh0Q==", + "requires": { + "@types/node": "*" + } + }, + "@types/node": { + "version": "11.9.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-11.9.4.tgz", + "integrity": "sha512-Zl8dGvAcEmadgs1tmSPcvwzO1YRsz38bVJQvH1RvRqSR9/5n61Q1ktcDL0ht3FXWR+ZpVmXVwN1LuH4Ax23NsA==" + }, "accepts": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz", @@ -51,14 +69,6 @@ "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" }, - "async": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.1.tgz", - "integrity": "sha512-fNEiL2+AZt6AlAw/29Cr0UDe4sRAHCpEHh54WMz+Bb7QfNcFw4h3loofyJpLeQs4Yx7yuqu/2dLgM5hKOs6HlQ==", - "requires": { - "lodash": "^4.17.10" - } - }, "asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -82,6 +92,11 @@ "tweetnacl": "^0.14.3" } }, + "bignumber.js": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz", + "integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA==" + }, "bl": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/bl/-/bl-1.2.2.tgz", @@ -128,11 +143,6 @@ } } }, - "bson": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.0.tgz", - "integrity": "sha512-9Aeai9TacfNtWXOYarkFJRW2CWo+dRon+fuLZYJmvLV3+MiUp0bEI6IAZfXEIg7/Pl/7IWlLaDnhzTsD81etQA==" - }, "bytes": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", @@ -579,11 +589,6 @@ "verror": "1.10.0" } }, - "kareem": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.3.0.tgz", - "integrity": "sha512-6hHxsp9e6zQU8nXsP+02HGWXwTkOEw6IROhF2ZA28cYbUk4eJ6QbtZvdqZOdD9YPKghG3apk5eOCvs+tLl3lRg==" - }, "lodash": { "version": "4.17.11", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", @@ -599,12 +604,6 @@ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" }, - "memory-pager": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", - "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", - "optional": true - }, "merge-descriptors": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", @@ -646,92 +645,22 @@ "moment": ">= 2.9.0" } }, - "mongodb": { - "version": "3.1.13", - "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.13.tgz", - "integrity": "sha512-sz2dhvBZQWf3LRNDhbd30KHVzdjZx9IKC0L+kSZ/gzYquCF5zPOgGqRz6sSCqYZtKP2ekB4nfLxhGtzGHnIKxA==", - "requires": { - "mongodb-core": "3.1.11", - "safe-buffer": "^5.1.2" - } - }, - "mongodb-core": { - "version": "3.1.11", - "resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-3.1.11.tgz", - "integrity": "sha512-rD2US2s5qk/ckbiiGFHeu+yKYDXdJ1G87F6CG3YdaZpzdOm5zpoAZd/EKbPmFO6cQZ+XVXBXBJ660sSI0gc6qg==", - "requires": { - "bson": "^1.1.0", - "require_optional": "^1.0.1", - "safe-buffer": "^5.1.2", - "saslprep": "^1.0.0" - } - }, - "mongoose": { - "version": "5.4.12", - "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.4.12.tgz", - "integrity": "sha512-+Xlw2JhARps/yAtMaWluJnHAidk+v38YhJNu1nX4RYleQIyXYnzFlANoD01vZyZL8X6PjOwkWDjnMFbfyy9Shg==", - "requires": { - "async": "2.6.1", - "bson": "~1.1.0", - "kareem": "2.3.0", - "mongodb": "3.1.13", - "mongodb-core": "3.1.11", - "mongoose-legacy-pluralize": "1.0.2", - "mpath": "0.5.1", - "mquery": "3.2.0", - "ms": "2.1.1", - "regexp-clone": "0.0.1", - "safe-buffer": "5.1.2", - "sliced": "1.0.1" - } - }, - "mongoose-legacy-pluralize": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/mongoose-legacy-pluralize/-/mongoose-legacy-pluralize-1.0.2.tgz", - "integrity": "sha512-Yo/7qQU4/EyIS8YDFSeenIvXxZN+ld7YdV9LqFVQJzTLye8unujAWPZ4NWKfFA+RNjh+wvTWKY9Z3E5XM6ZZiQ==" - }, - "mpath": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.5.1.tgz", - "integrity": "sha512-H8OVQ+QEz82sch4wbODFOz+3YQ61FYz/z3eJ5pIdbMEaUzDqA268Wd+Vt4Paw9TJfvDgVKaayC0gBzMIw2jhsg==" - }, - "mquery": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/mquery/-/mquery-3.2.0.tgz", - "integrity": "sha512-qPJcdK/yqcbQiKoemAt62Y0BAc0fTEKo1IThodBD+O5meQRJT/2HSe5QpBNwaa4CjskoGrYWsEyjkqgiE0qjhg==", - "requires": { - "bluebird": "3.5.1", - "debug": "3.1.0", - "regexp-clone": "0.0.1", - "safe-buffer": "5.1.2", - "sliced": "1.0.1" - }, - "dependencies": { - "bluebird": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", - "integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA==" - }, - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" - } - } - }, "ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" }, + "mysql": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.16.0.tgz", + "integrity": "sha512-dPbN2LHonQp7D5ja5DJXNbCLe/HRdu+f3v61aguzNRQIrmZLOeRoymBYyeThrR6ug+FqzDL95Gc9maqZUJS+Gw==", + "requires": { + "bignumber.js": "4.1.0", + "readable-stream": "2.3.6", + "safe-buffer": "5.1.2", + "sqlstring": "2.3.1" + } + }, "negotiator": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz", @@ -811,6 +740,17 @@ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==" }, + "promise-mysql": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/promise-mysql/-/promise-mysql-3.3.1.tgz", + "integrity": "sha512-PE+J6TtAqMJpdREvSphKvd+pn0IgGiLgxaDBb12oZNBR1VSxYSzknveuiSBmkptZC1ZDRwU+zBxBJeBgGFkCRA==", + "requires": { + "@types/bluebird": "^3.5.19", + "@types/mysql": "^2.15.2", + "bluebird": "^3.5.0", + "mysql": "^2.14.1" + } + }, "proxy-addr": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.4.tgz", @@ -874,11 +814,6 @@ "util-deprecate": "~1.0.1" } }, - "regexp-clone": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz", - "integrity": "sha1-p8LgmJH9vzj7sQ03b7cwA+aKxYk=" - }, "request": { "version": "2.88.0", "resolved": "https://registry.npmjs.org/request/-/request-2.88.0.tgz", @@ -925,20 +860,6 @@ "lodash": "^4.17.11" } }, - "require_optional": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", - "integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", - "requires": { - "resolve-from": "^2.0.0", - "semver": "^5.1.0" - } - }, - "resolve-from": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", - "integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=" - }, "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", @@ -949,20 +870,6 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, - "saslprep": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.2.tgz", - "integrity": "sha512-4cDsYuAjXssUSjxHKRe4DTZC0agDwsCqcMqtJAQPzC74nJ7LfAJflAtC1Zed5hMzEQKj82d3tuzqdGNRsLJ4Gw==", - "optional": true, - "requires": { - "sparse-bitfield": "^3.0.3" - } - }, - "semver": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", - "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==" - }, "send": { "version": "0.16.2", "resolved": "https://registry.npmjs.org/send/-/send-0.16.2.tgz", @@ -1019,24 +926,15 @@ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==" }, - "sliced": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", - "integrity": "sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E=" - }, "sorted-array-functions": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/sorted-array-functions/-/sorted-array-functions-1.2.0.tgz", "integrity": "sha512-sWpjPhIZJtqO77GN+LD8dDsDKcWZ9GCOJNqKzi1tvtjGIzwfoyuRH8S0psunmc6Z5P+qfDqztSbwYR5X/e1UTg==" }, - "sparse-bitfield": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", - "integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", - "optional": true, - "requires": { - "memory-pager": "^1.0.2" - } + "sqlstring": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz", + "integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A=" }, "sshpk": { "version": "1.16.1", diff --git a/package.json b/package.json index 65d25e1750f419204f79a5b32a7dd22427085b64..4fc8a98f7323f258bba3cc21a5aa4f2e87d17170 100644 --- a/package.json +++ b/package.json @@ -20,9 +20,9 @@ "license": "ISC", "dependencies": { "express": "^4.16.4", - "mongoose": "^5.4.12", "node-schedule": "^1.3.2", "node-telegram-bot-api": "^0.30.0", + "promise-mysql": "^3.3.1", "request": "^2.88.0", "request-promise": "^4.2.4" } diff --git a/requests.js b/requests.js index 76025aa9c182510e041257199c2f300e10fb7244..7034ef026ec871f00546d64771f09936b33f66fb 100644 --- a/requests.js +++ b/requests.js @@ -1,4 +1,10 @@ +// Modules extérieurs const rp = require('request-promise'); + +// Modules propres +var { modifyChan } = require('./connection-db'); + +// Configurations const config = require('./config'); // Fonction d'envoi d'une requête au GraphQL de LinkCS @@ -66,11 +72,10 @@ function getNewToken(chan) { return rp(options).then(body => { if (!chan) { return req.query.state } rep = JSON.parse(body); - console.log(rep); chan.token = rep.access_token; chan.refresh = rep.refresh_token; chan.expiration = rep.expires_at * 1000; - return chan.save() + return modifyChan(chan) }) }; diff --git a/telegram.js b/telegram.js index cb6fe26adec54ce4013e661f2d2248e1f9f17e5c..0699093da8e299b4812131ca07707e6cdb58793e 100644 --- a/telegram.js +++ b/telegram.js @@ -5,7 +5,7 @@ var TelegramBot = require('node-telegram-bot-api'); var schedule = require('node-schedule'); // Modules propres -var Channel = require('./models/Channel'); +var { query, getChanByChatId, createChan, deleteChanByChatId, modifyChan, addGroup, getGroups } = require('./connection-db'); var { getBirthdays, searchGroups, getGroupById, getNewToken } = require('./requests'); // Configurations @@ -16,20 +16,28 @@ var bot = new TelegramBot(config.telegram.token, { polling: true }); var schedules = {}; +// En cas de redémarrage de l'appli +query(`SELECT chatId, schedule FROM channel WHERE schedule <> ""`).then(rep => { + rep.forEach(chan => { + + }) +}) + + // A la connexion, création d'un document Channel dans MongoDB bot.onText(/\/start/, msg => { const chatId = msg.chat.id; - return Channel.findOne({ - chatId: chatId - }).then(chan => { + return getChanByChatId(chatId).then(chan => { // /start déjà fait... if (chan) return bot.sendMessage(chatId, 'Vous avez déjà fait lancé le bot sur cette conversation. Pour tout réinitialiser, faites /reset.') - return Channel.create({ + return createChan({ chatId: chatId, username: '', state: '', token: '', - groups: [] + refresh: '', + expiration: '', + schedule: '' }).then(_ => { const resp = 'Holà, je suis le Happy Botday, je suis là pour vous souhaiter vous rapeller les anniversaires de vos potes !\nPour commencer, il faut que quelqu\'un s\'identifie : /connect'; bot.sendMessage(chatId, resp); @@ -45,11 +53,9 @@ bot.onText(/\/reset/, msg => { schedule[chatId].cancel(); delete (schedule[chatId]); } - return Channel.findOneAndDelete({ - chatId: chatId - }).then(_ => { + return deleteChanByChatId(chatId).then(_ => { const resp = 'Toutes vos paramètres ont été supprimés. Pour recommencer à m\'utiliser, faites /start.'; - return bot.sendMessage(chatId, resp); + bot.sendMessage(chatId, resp); }) }) @@ -57,9 +63,7 @@ bot.onText(/\/reset/, msg => { // Si rien n'a été fait avant, propose un lien de connexion à l'OAuth2 de VR bot.onText(/\/connect/, (msg, _) => { const chatId = msg.chat.id; - Channel.findOne({ - chatId: chatId - }).then(chan => { + getChanByChatId(chatId).then(chan => { // start pas encore fait if (!chan) return bot.sendMessage(chatId, 'Avant de vous authentifier, faites /start.'); // /connect déjà fait, renvoie vers le lien précédent @@ -69,7 +73,7 @@ bot.onText(/\/connect/, (msg, _) => { // dans le reste des cas, création d'un lien pour l'authentification et enregistrement dans l'objet pour être sur chan.state = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); chan.username = msg.from.username; - chan.save().then(chan => { + modifyChan(chan).then(chan => { const resp = `Pour vous identifier, connectez-vous via l\'OAuth2 de ViaRézo depuis ce lien :\n${config.website.protocol}://${config.website.hostname}/?state=${chan.state}`; return bot.sendMessage(chatId, resp); }) @@ -79,23 +83,19 @@ bot.onText(/\/connect/, (msg, _) => { // Annulation de la demande de connexion bot.onText(/\/cancel/, msg => { const chatId = msg.chat.id; - Channel.findOne({ - chatId: chatId - }).then(chan => { + getChanByChatId(chatId).then(chan => { // ne peut pas annuler une demande déjà acceptée if (chan.token.length !== 0) return bot.sendMessage(chatId, 'La demande d\'athentification a déjà été acceptée, elle ne peut pas être annulée. Pour se déconnecter, faites /disconnect.') chan.username = ''; chan.state = ''; - return chan.save().then(chan => { - return bot.sendMessage(chatId, 'La demande d\'authentification a été annulée. Vous pouvez vous reconnecter avec /connect.') - }) + modifyChan(chan).then(_ => bot.sendMessage(chatId, 'La demande d\'authentification a été annulée. Vous pouvez vous reconnecter avec /connect.')) }) }) // Permet de déconnecter l'utilisateur qui s'est authentifié sur l'OAuth2 bot.onText(/\/disconnect/, msg => { const chatId = msg.chat.id; - Channel.findOne({ chatId: chatId }).then(chan => { + getChanByChatId(chatId).then(chan => { // s'il n'y a pas de token, personne ne s'est connecté if (chan.token.length === 0) return bot.sendMessage(chatId, 'Personne ne s\'est connecté...'); // suppression de tous les paramètres de connexion et save() @@ -103,9 +103,7 @@ bot.onText(/\/disconnect/, msg => { chan.token = ''; chan.expiration = Date.now(0); chan.username = ''; - chan.save().then(_ => { - return bot.sendMessage(chatId, `@${username} n'est plus connecté à l'OAuth2.`); - }) + modifyChan(chan).then(_ => bot.sendMessage(chatId, `@${username} n'est plus connecté à l'OAuth2.`)); }) }); @@ -113,16 +111,14 @@ bot.onText(/\/disconnect/, msg => { bot.onText(/\/allbirthdays/, msg => { const chatId = msg.chat.id; // recherche du token du chan actuel - Channel.findOne({ - chatId: chatId, - }).then(chan => { + getChanByChatId(chatId).then(chan => { return getBirthdays(chan.token) }).then(users => { var msg = '**Joyeux anniversaire** à :\n' users.forEach(user => { msg += `${user.name}\n` }); - return bot.sendMessage(chatId, msg, { parse_mode: 'Markdown' }); + bot.sendMessage(chatId, msg, { parse_mode: 'Markdown' }); }) }); @@ -130,13 +126,14 @@ bot.onText(/\/allbirthdays/, msg => { bot.onText(/\/birthdays/, msg => { const chatId = msg.chat.id; // recherche du token du chan actuel - Channel.findOne({ - chatId: chatId, - }).then(chan => { - return Promise.all([getBirthdays(chan.token), chan]) - }).then(([users, chan]) => { + getChanByChatId(chatId).then(chan => { + return Promise.all([ + getBirthdays(chan.token), + getGroups(chatId), + ]) + }).then(([users, groups]) => { // récupère que les personnes du jour qui font partie des groupes ciblés - const newUsers = users.filter(user => user.asso.some(asso => chan.groups.indexOf(asso) !== -1)); + const newUsers = users.filter(user => user.asso.some(asso => groups.indexOf(asso) !== -1)); if (newUsers.length === 0) return bot.sendMessage(chatId, 'Pas d\'anniversaire à souhaiter aujourd\'hui.') var msg = '**Joyeux anniversaire** à :\n' newUsers.forEach(user => { @@ -150,9 +147,7 @@ bot.onText(/\/birthdays/, msg => { bot.onText(/\/search (.+)/, (msg, match) => { const chatId = msg.chat.id; const research = match[1]; - Channel.findOne({ - chatId: chatId - }).then(chan => { + getChanByChatId(chatId).then(chan => { return searchGroups(chan.token, research) }).then(groups => { if (groups.length == 0) return bot.sendMessage(chatId, 'Pas de groupe à ce nom...'); @@ -170,19 +165,20 @@ bot.onText(/\/search (.+)/, (msg, match) => { // Ajout d'un groupe dans la liste des groupes bot.onText(/\/add (.+)/, (msg, match) => { const chatId = msg.chat.id; - Channel.findOne({ - chatId: chatId - }).then(chan => { + getChanByChatId(chatId).then(chan => { const id = parseInt(match[1].split(' ')[0]); - return Promise.all([getGroupById(chan.token, id), chan, id]); - }).then(([group, chan, id]) => { + return Promise.all([ + getGroupById(chan.token, id), + getGroups(chatId), + id + ]); + }).then(([group, groups, id]) => { // si pas de groupe trouvé if (!group) return bot.sendMessage(chatId, 'Pas de groupe trouvé ayant cette ID'); // si le groupe y est déjà - if (chan.groups.indexOf(id) !== -1) return bot.sendMessage(chatId, 'Ce groupe est déjà est dans votre liste d\'anniversaire.'); + if (groups.indexOf(id) !== -1) return bot.sendMessage(chatId, 'Ce groupe est déjà est dans votre liste d\'anniversaire.'); // sinon on le rajoute - chan.groups.push(id); - return chan.save().then(_ => { + return addGroup(chatId, id).then(_ => { bot.sendMessage(chatId, `Ajout du groupe \`${group}\` à la liste des anniversaires.`, { parse_mode: 'Markdown' }); }) }) @@ -195,19 +191,20 @@ bot.onText(/\/schedule (.+)/, (msg, match) => { if (!RegExp('^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$').test(time)) return bot.sendMessage(chatId, 'Le temps entré n\'est pas au format hh:mm'); const hour = parseInt(time.split(':')[0]); const minute = parseInt(time.split(':')[1]); - Channel.findOne({ - chatId: chatId - }).then(chan => { + getChanByChatId(chatId).then(chan => { if (!chan) return bot.sendMessage(chatId, 'Pas de compte enregistré, faites /start pour commencer'); chan.schedule = time; - chan.save() - }).then(chan => { + return Promise.all([ + modifyChan(chan), + getGroups(chatId) + ]) + }).then(([chan, groups]) => { schedules[chan.chatId] = schedule.scheduleJob({ hour: hour, minute: minute }, function () { return getNewToken(chan).then(chan => { return getBirthdays(chan.token) }).then(users => { // récupère que les personnes du jour qui font partie des groupes ciblés - const newUsers = users.filter(user => user.asso.some(asso => chan.groups.indexOf(asso) !== -1)); + const newUsers = users.filter(user => user.asso.some(asso => groups.indexOf(asso) !== -1)); if (newUsers.length === 0) return var msg = '**Joyeux anniversaire** à :\n' newUsers.forEach(user => { @@ -216,6 +213,7 @@ bot.onText(/\/schedule (.+)/, (msg, match) => { return bot.sendMessage(chan.chatId, msg, { parse_mode: 'Markdown' }); }) }); + bot.sendMessage(chatId, `Votre rappel est configuré pour tous les jours à ${time}`); }) }) diff --git a/website.js b/website.js index 2841acc551d281b9b0c6617e51349963dbe1e26b..005b95c3fe47d56808e19a58546afd880d565474 100644 --- a/website.js +++ b/website.js @@ -1,9 +1,14 @@ +// Modules extérieurs +var app = require('express')(); +var rp = require('request-promise'); + +// Modules propres +var bot = require('./telegram'); +var { modifyChan, getChanByState } = require('./connection-db'); + +// Configurations const config = require('./config'); -const app = require('express')(); -const rp = require('request-promise'); -const bot = require('./telegram'); -const Channel = require('./models/Channel'); app.listen(80, config.website.hostname, () => { console.log(`[express] Website is up and accessible on ${config.website.protocol}://${config.website.hostname}/`); @@ -11,9 +16,12 @@ app.listen(80, config.website.hostname, () => { app.get('/', function (req, res) { - if (!req.query.state) { return res.sendFile(`${__dirname}/index.html`) }; + // GET / : renvoie la page de base + if (!req.query.state) return res.sendFile(`${__dirname}/index.html`); + // surement une tentative de XSS (plus gros point d'entrée) + if (req.query.state.indexOf(';') !== -1) return res.sendFile(`${__dirname}/index.html`); - Channel.findOne({ state: req.query.state }).then(chan => { + getChanByState(req.query.state).then(chan => { if (!chan || chan.token) return res.sendFile(`${__dirname}/index.html`); @@ -47,19 +55,18 @@ app.get('/auth', function (req, res) { } return rp(options).then(body => { - return Promise.all([body, Channel.findOne({ state: req.query.state })]) + return Promise.all([body, getChanByState(req.query.state)]) }).then(([body, chan]) => { - if (!chan) { return req.query.state } + if (!chan) return rep = JSON.parse(body); - console.log(rep); chan.token = rep.access_token; chan.refresh = rep.refresh_token; - chan.expiration = rep.expires_at * 1000; + chan.expiration = rep.expires_at; chan.state = ''; - return chan.save() + return modifyChan(chan) }).then(chan => { - bot.sendMessage(chan.chatId, `@${chan.username} s'est connecté à OAuth2, shall we begin?`); - return res.redirect(301, `${config.website.protocol}://${config.website.hostname}/auth`) + bot.sendMessage(chan.chatId, `@${chan.username} s'est connecté à OAuth2, shall we begin?`) + res.redirect(301, `${config.website.protocol}://${config.website.hostname}/auth`) }) })