Donghoon Kim

Merge branch 'master' into api

Showing 209 changed files with 31400 additions and 396 deletions
1 var pos; 1 var pos;
2 +var map;
2 var infowindow; 3 var infowindow;
3 var service; 4 var service;
4 5
5 -var result_entertainment = []
6 -var result_food = []
7 -var result_room = []
8 -
9 function initMap() { 6 function initMap() {
7 +
8 + map = new google.maps.Map(document.getElementById('map'), {
9 + center: {lat: -34.397, lng: 150.644},
10 + zoom: 17
11 + });
12 + infowindow = new google.maps.InfoWindow();
13 +
10 // Try HTML5 geolocation. 14 // Try HTML5 geolocation.
11 if (navigator.geolocation) { 15 if (navigator.geolocation) {
12 navigator.geolocation.getCurrentPosition(function(position) { 16 navigator.geolocation.getCurrentPosition(function(position) {
...@@ -58,6 +62,7 @@ function initMap() { ...@@ -58,6 +62,7 @@ function initMap() {
58 } 62 }
59 } 63 }
60 64
65 +
61 function searchPlace(str, placeType) { 66 function searchPlace(str, placeType) {
62 switch(placeType) { 67 switch(placeType) {
63 case 'food': 68 case 'food':
...@@ -90,7 +95,7 @@ function searchPlace(str, placeType) { ...@@ -90,7 +95,7 @@ function searchPlace(str, placeType) {
90 function callback_foods(results, status) { 95 function callback_foods(results, status) {
91 if (status === google.maps.places.PlacesServiceStatus.OK) { 96 if (status === google.maps.places.PlacesServiceStatus.OK) {
92 for (var i = 0; i < results.length; i++) { 97 for (var i = 0; i < results.length; i++) {
93 - result_food.push(results[i]); 98 + putDataToDB(results[i], 'food')
94 createMarker_foods(results[i]); 99 createMarker_foods(results[i]);
95 } 100 }
96 } 101 }
...@@ -99,7 +104,7 @@ function callback_foods(results, status) { ...@@ -99,7 +104,7 @@ function callback_foods(results, status) {
99 function callback_entertainment(results, status) { 104 function callback_entertainment(results, status) {
100 if (status === google.maps.places.PlacesServiceStatus.OK) { 105 if (status === google.maps.places.PlacesServiceStatus.OK) {
101 for (var i = 0; i < results.length; i++) { 106 for (var i = 0; i < results.length; i++) {
102 - result_entertainment.push(results[i]); 107 + putDataToDB(results[i], 'entertainment')
103 createMarker_entertainment(results[i]); 108 createMarker_entertainment(results[i]);
104 } 109 }
105 } 110 }
...@@ -108,7 +113,7 @@ function callback_entertainment(results, status) { ...@@ -108,7 +113,7 @@ function callback_entertainment(results, status) {
108 function callback_rooms(results, status) { 113 function callback_rooms(results, status) {
109 if (status === google.maps.places.PlacesServiceStatus.OK) { 114 if (status === google.maps.places.PlacesServiceStatus.OK) {
110 for (var i = 0; i < results.length; i++) { 115 for (var i = 0; i < results.length; i++) {
111 - result_room.push(results[i]); 116 + putDataToDB(results[i], 'room')
112 createMarker_rooms(results[i]); 117 createMarker_rooms(results[i]);
113 } 118 }
114 } 119 }
...@@ -157,17 +162,20 @@ function createMarker_rooms(place) { ...@@ -157,17 +162,20 @@ function createMarker_rooms(place) {
157 } 162 }
158 163
159 function putDataToDB(result, category1) { 164 function putDataToDB(result, category1) {
160 - const id = result; 165 + const id = result['id'];
161 - const place_id =result; 166 + const place_id =result['place_id'];
162 - const name = result; 167 + const name = result['name'];
163 - const address = result; 168 + const address = result['vicinity'];
164 let category_big = category1 169 let category_big = category1
165 - const category_small = result; 170 + const category_small = result.types[0];
166 - const image = result; 171 + const image = "default"
167 - const rating = result; 172 + const rating = result.rating;
168 - const lng = result; 173 + const lng = result.geometry.viewport.ea.j;
169 - const lat =result; 174 + const lat =result.geometry.viewport.la.j;
170 175
176 + if(rating == null) {
177 + rating = 0;
178 + }
171 const QueryCheck = () => { 179 const QueryCheck = () => {
172 if (!id || !place_id || !name || !address || !category_big || !category_small || !image || !rating || !lng || !lat) { 180 if (!id || !place_id || !name || !address || !category_big || !category_small || !image || !rating || !lng || !lat) {
173 return Promise.reject({ 181 return Promise.reject({
...@@ -193,7 +201,7 @@ function putDataToDB(result, category1) { ...@@ -193,7 +201,7 @@ function putDataToDB(result, category1) {
193 201
194 // 1. Query Check 202 // 1. Query Check
195 const FindQueryCheck = () => { 203 const FindQueryCheck = () => {
196 - if (!keyword) { 204 + if (!id) {
197 return Promise.reject({ 205 return Promise.reject({
198 message: 'Query Error' 206 message: 'Query Error'
199 }) 207 })
...@@ -203,7 +211,7 @@ function putDataToDB(result, category1) { ...@@ -203,7 +211,7 @@ function putDataToDB(result, category1) {
203 211
204 // 2. SQL Start 212 // 2. SQL Start
205 const FindSQLStart = (pool) => { 213 const FindSQLStart = (pool) => {
206 - return pool.query(`SELECT * FROM PLACE WHERE ID LIKE '%${id}%') 214 + return pool.query('SELECT * FROM PLACE WHERE ID LIKE '+id.toString())
207 } 215 }
208 216
209 // 3. Response 217 // 3. Response
......
1 +const mysql = require('promise-mysql')
2 +
3 +module.exports = mysql.createConnection({
4 + host: "52.79.82.27",
5 + user: "root",
6 + password: "oss",
7 + database: "OSS"
8 +})
1 + MIT License
2 +
3 + Copyright (c) Microsoft Corporation. All rights reserved.
4 +
5 + Permission is hereby granted, free of charge, to any person obtaining a copy
6 + of this software and associated documentation files (the "Software"), to deal
7 + in the Software without restriction, including without limitation the rights
8 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 + copies of the Software, and to permit persons to whom the Software is
10 + furnished to do so, subject to the following conditions:
11 +
12 + The above copyright notice and this permission notice shall be included in all
13 + copies or substantial portions of the Software.
14 +
15 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 + SOFTWARE
1 +# Installation
2 +> `npm install --save @types/bluebird`
3 +
4 +# Summary
5 +This package contains type definitions for bluebird (https://github.com/petkaantonov/bluebird).
6 +
7 +# Details
8 +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/bluebird
9 +
10 +Additional Details
11 + * Last updated: Mon, 27 Aug 2018 22:59:40 GMT
12 + * Dependencies: none
13 + * Global values: none
14 +
15 +# Credits
16 +These definitions were written by Leonard Hecker <https://github.com/lhecker>.
1 +// Type definitions for bluebird 3.5
2 +// Project: https://github.com/petkaantonov/bluebird
3 +// Definitions by: Leonard Hecker <https://github.com/lhecker>
4 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
5 +// TypeScript Version: 2.8
6 +
7 +/*!
8 + * The code following this comment originates from:
9 + * https://github.com/types/npm-bluebird
10 + *
11 + * Note for browser users: use bluebird-global typings instead of this one
12 + * if you want to use Bluebird via the global Promise symbol.
13 + *
14 + * Licensed under:
15 + * The MIT License (MIT)
16 + *
17 + * Copyright (c) 2016 unional
18 + *
19 + * Permission is hereby granted, free of charge, to any person obtaining a copy
20 + * of this software and associated documentation files (the "Software"), to deal
21 + * in the Software without restriction, including without limitation the rights
22 + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23 + * copies of the Software, and to permit persons to whom the Software is
24 + * furnished to do so, subject to the following conditions:
25 + *
26 + * The above copyright notice and this permission notice shall be included in
27 + * all copies or substantial portions of the Software.
28 + *
29 + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30 + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31 + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33 + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34 + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 + * THE SOFTWARE.
36 + */
37 +
38 +type CatchFilter<E> = (new (...args: any[]) => E) | ((error: E) => boolean) | (object & E);
39 +type IterableItem<R> = R extends Iterable<infer U> ? U : never;
40 +type IterableOrNever<R> = Extract<R, Iterable<any>>;
41 +type Resolvable<R> = R | PromiseLike<R>;
42 +type IterateFunction<T, R> = (item: T, index: number, arrayLength: number) => Resolvable<R>;
43 +
44 +declare class Bluebird<R> implements PromiseLike<R>, Bluebird.Inspection<R> {
45 + /**
46 + * Create a new promise. The passed in function will receive functions
47 + * `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
48 + *
49 + * If promise cancellation is enabled, passed in function will receive
50 + * one more function argument `onCancel` that allows to register an optional cancellation callback.
51 + */
52 + constructor(callback: (resolve: (thenableOrResult?: Resolvable<R>) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void);
53 +
54 + /**
55 + * Promises/A+ `.then()`. Returns a new promise chained from this promise.
56 + *
57 + * The new promise will be rejected or resolved depending on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
58 + */
59 + // Based on PromiseLike.then, but returns a Bluebird instance.
60 + then<U>(onFulfill?: (value: R) => Resolvable<U>, onReject?: (error: any) => Resolvable<U>): Bluebird<U>; // For simpler signature help.
61 + then<TResult1 = R, TResult2 = never>(
62 + onfulfilled?: ((value: R) => Resolvable<TResult1>) | null,
63 + onrejected?: ((reason: any) => Resolvable<TResult2>) | null
64 + ): Bluebird<TResult1 | TResult2>;
65 +
66 + /**
67 + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise.
68 + *
69 + * Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
70 + *
71 + * Alias `.caught();` for compatibility with earlier ECMAScript version.
72 + */
73 + catch<U = R>(onReject: ((error: any) => Resolvable<U>) | undefined | null): Bluebird<U | R>;
74 +
75 + /**
76 + * This extends `.catch` to work more like catch-clauses in languages like Java or C#.
77 + *
78 + * Instead of manually checking `instanceof` or `.name === "SomeError"`,
79 + * you may specify a number of error constructors which are eligible for this catch handler.
80 + * The catch handler that is first met that has eligible constructors specified, is the one that will be called.
81 + *
82 + * This method also supports predicate-based filters.
83 + * If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument.
84 + * The return result of the predicate will be used determine whether the error handler should be called.
85 + *
86 + * Alias `.caught();` for compatibility with earlier ECMAScript version.
87 + */
88 + catch<E1, E2, E3, E4, E5>(
89 + filter1: CatchFilter<E1>,
90 + filter2: CatchFilter<E2>,
91 + filter3: CatchFilter<E3>,
92 + filter4: CatchFilter<E4>,
93 + filter5: CatchFilter<E5>,
94 + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<R>,
95 + ): Bluebird<R>;
96 + catch<U, E1, E2, E3, E4, E5>(
97 + filter1: CatchFilter<E1>,
98 + filter2: CatchFilter<E2>,
99 + filter3: CatchFilter<E3>,
100 + filter4: CatchFilter<E4>,
101 + filter5: CatchFilter<E5>,
102 + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<U>,
103 + ): Bluebird<U | R>;
104 +
105 + catch<E1, E2, E3, E4>(
106 + filter1: CatchFilter<E1>,
107 + filter2: CatchFilter<E2>,
108 + filter3: CatchFilter<E3>,
109 + filter4: CatchFilter<E4>,
110 + onReject: (error: E1 | E2 | E3 | E4) => Resolvable<R>,
111 + ): Bluebird<R>;
112 +
113 + catch<U, E1, E2, E3, E4>(
114 + filter1: CatchFilter<E1>,
115 + filter2: CatchFilter<E2>,
116 + filter3: CatchFilter<E3>,
117 + filter4: CatchFilter<E4>,
118 + onReject: (error: E1 | E2 | E3 | E4) => Resolvable<U>,
119 + ): Bluebird<U | R>;
120 +
121 + catch<E1, E2, E3>(
122 + filter1: CatchFilter<E1>,
123 + filter2: CatchFilter<E2>,
124 + filter3: CatchFilter<E3>,
125 + onReject: (error: E1 | E2 | E3) => Resolvable<R>,
126 + ): Bluebird<R>;
127 + catch<U, E1, E2, E3>(
128 + filter1: CatchFilter<E1>,
129 + filter2: CatchFilter<E2>,
130 + filter3: CatchFilter<E3>,
131 + onReject: (error: E1 | E2 | E3) => Resolvable<U>,
132 + ): Bluebird<U | R>;
133 +
134 + catch<E1, E2>(
135 + filter1: CatchFilter<E1>,
136 + filter2: CatchFilter<E2>,
137 + onReject: (error: E1 | E2) => Resolvable<R>,
138 + ): Bluebird<R>;
139 + catch<U, E1, E2>(
140 + filter1: CatchFilter<E1>,
141 + filter2: CatchFilter<E2>,
142 + onReject: (error: E1 | E2) => Resolvable<U>,
143 + ): Bluebird<U | R>;
144 +
145 + catch<E1>(
146 + filter1: CatchFilter<E1>,
147 + onReject: (error: E1) => Resolvable<R>,
148 + ): Bluebird<R>;
149 + catch<U, E1>(
150 + filter1: CatchFilter<E1>,
151 + onReject: (error: E1) => Resolvable<U>,
152 + ): Bluebird<U | R>;
153 +
154 + /**
155 + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise.
156 + *
157 + * Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
158 + *
159 + * Alias `.caught();` for compatibility with earlier ECMAScript version.
160 + */
161 + caught: Bluebird<R>["catch"];
162 +
163 + /**
164 + * Like `.catch` but instead of catching all types of exceptions,
165 + * it only catches those that don't originate from thrown errors but rather from explicit rejections.
166 + */
167 + error<U>(onReject: (reason: any) => Resolvable<U>): Bluebird<U>;
168 +
169 + /**
170 + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise.
171 + *
172 + * There are special semantics for `.finally()` in that the final value cannot be modified from the handler.
173 + *
174 + * Alias `.lastly();` for compatibility with earlier ECMAScript version.
175 + */
176 + finally(handler: () => Resolvable<any>): Bluebird<R>;
177 +
178 + lastly: Bluebird<R>["finally"];
179 +
180 + /**
181 + * Create a promise that follows this promise, but is bound to the given `thisArg` value.
182 + * A bound promise will call its handlers with the bound value set to `this`.
183 + *
184 + * Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise.
185 + */
186 + bind(thisArg: any): Bluebird<R>;
187 +
188 + /**
189 + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error.
190 + */
191 + done<U>(onFulfilled?: (value: R) => Resolvable<U>, onRejected?: (error: any) => Resolvable<U>): void;
192 +
193 + /**
194 + * Like `.finally()`, but not called for rejections.
195 + */
196 + tap(onFulFill: (value: R) => Resolvable<any>): Bluebird<R>;
197 +
198 + /**
199 + * Like `.catch()` but rethrows the error
200 + */
201 + tapCatch(onReject: (error?: any) => Resolvable<any>): Bluebird<R>;
202 +
203 + tapCatch<E1, E2, E3, E4, E5>(
204 + filter1: CatchFilter<E1>,
205 + filter2: CatchFilter<E2>,
206 + filter3: CatchFilter<E3>,
207 + filter4: CatchFilter<E4>,
208 + filter5: CatchFilter<E5>,
209 + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<any>,
210 + ): Bluebird<R>;
211 + tapCatch<E1, E2, E3, E4>(
212 + filter1: CatchFilter<E1>,
213 + filter2: CatchFilter<E2>,
214 + filter3: CatchFilter<E3>,
215 + filter4: CatchFilter<E4>,
216 + onReject: (error: E1 | E2 | E3 | E4) => Resolvable<any>,
217 + ): Bluebird<R>;
218 + tapCatch<E1, E2, E3>(
219 + filter1: CatchFilter<E1>,
220 + filter2: CatchFilter<E2>,
221 + filter3: CatchFilter<E3>,
222 + onReject: (error: E1 | E2 | E3) => Resolvable<any>,
223 + ): Bluebird<R>;
224 + tapCatch<E1, E2>(
225 + filter1: CatchFilter<E1>,
226 + filter2: CatchFilter<E2>,
227 + onReject: (error: E1 | E2) => Resolvable<any>,
228 + ): Bluebird<R>;
229 + tapCatch<E1>(
230 + filter1: CatchFilter<E1>,
231 + onReject: (error: E1) => Resolvable<any>,
232 + ): Bluebird<R>;
233 +
234 + /**
235 + * Same as calling `Promise.delay(ms, this)`.
236 + */
237 + delay(ms: number): Bluebird<R>;
238 +
239 + /**
240 + * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason.
241 + * However, if this promise is not fulfilled or rejected within ms milliseconds, the returned promise
242 + * is rejected with a TimeoutError or the error as the reason.
243 + *
244 + * You may specify a custom error message with the `message` parameter.
245 + */
246 + timeout(ms: number, message?: string | Error): Bluebird<R>;
247 +
248 + /**
249 + * Register a node-style callback on this promise.
250 + *
251 + * When this promise is is either fulfilled or rejected,
252 + * the node callback will be called back with the node.js convention
253 + * where error reason is the first argument and success value is the second argument.
254 + *
255 + * The error argument will be `null` in case of success.
256 + * If the `callback` argument is not a function, this method does not do anything.
257 + */
258 + nodeify(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this;
259 + nodeify(...sink: any[]): this;
260 + asCallback(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this;
261 + asCallback(...sink: any[]): this;
262 +
263 + /**
264 + * See if this `promise` has been fulfilled.
265 + */
266 + isFulfilled(): boolean;
267 +
268 + /**
269 + * See if this `promise` has been rejected.
270 + */
271 + isRejected(): boolean;
272 +
273 + /**
274 + * See if this `promise` is still defer.
275 + */
276 + isPending(): boolean;
277 +
278 + /**
279 + * See if this `promise` has been cancelled.
280 + */
281 + isCancelled(): boolean;
282 +
283 + /**
284 + * See if this `promise` is resolved -> either fulfilled or rejected.
285 + */
286 + isResolved(): boolean;
287 +
288 + /**
289 + * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet.
290 + *
291 + * throws `TypeError`
292 + */
293 + value(): R;
294 +
295 + /**
296 + * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet.
297 + *
298 + * throws `TypeError`
299 + */
300 + reason(): any;
301 +
302 + /**
303 + * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of
304 + * the promise as snapshotted at the time of calling `.reflect()`.
305 + */
306 + reflect(): Bluebird<Bluebird.Inspection<R>>;
307 + reflect(): Bluebird<Bluebird.Inspection<any>>;
308 +
309 + /**
310 + * This is a convenience method for doing:
311 + *
312 + * <code>
313 + * promise.then(function(obj){
314 + * return obj[propertyName].call(obj, arg...);
315 + * });
316 + * </code>
317 + */
318 + call<U extends keyof R>(propertyName: U, ...args: any[]): Bluebird<R[U] extends (...args: any[]) => any ? ReturnType<R[U]> : never>;
319 +
320 + /**
321 + * This is a convenience method for doing:
322 + *
323 + * <code>
324 + * promise.then(function(obj){
325 + * return obj[propertyName];
326 + * });
327 + * </code>
328 + */
329 + get<U extends keyof R>(key: U): Bluebird<R[U]>;
330 +
331 + /**
332 + * Convenience method for:
333 + *
334 + * <code>
335 + * .then(function() {
336 + * return value;
337 + * });
338 + * </code>
339 + *
340 + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()`
341 + *
342 + * Alias `.thenReturn();` for compatibility with earlier ECMAScript version.
343 + */
344 + return(): Bluebird<void>;
345 + return<U>(value: U): Bluebird<U>;
346 + thenReturn(): Bluebird<void>;
347 + thenReturn<U>(value: U): Bluebird<U>;
348 +
349 + /**
350 + * Convenience method for:
351 + *
352 + * <code>
353 + * .then(function() {
354 + * throw reason;
355 + * });
356 + * </code>
357 + * Same limitations apply as with `.return()`.
358 + *
359 + * Alias `.thenThrow();` for compatibility with earlier ECMAScript version.
360 + */
361 + throw(reason: Error): Bluebird<never>;
362 + thenThrow(reason: Error): Bluebird<never>;
363 +
364 + /**
365 + * Convenience method for:
366 + *
367 + * <code>
368 + * .catch(function() {
369 + * return value;
370 + * });
371 + * </code>
372 + *
373 + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.catchReturn()`
374 + */
375 + catchReturn<U>(value: U): Bluebird<R | U>;
376 +
377 + // No need to be specific about Error types in these overrides, since there's no handler function
378 + catchReturn<U>(
379 + filter1: CatchFilter<Error>,
380 + filter2: CatchFilter<Error>,
381 + filter3: CatchFilter<Error>,
382 + filter4: CatchFilter<Error>,
383 + filter5: CatchFilter<Error>,
384 + value: U,
385 + ): Bluebird<R | U>;
386 + catchReturn<U>(
387 + filter1: CatchFilter<Error>,
388 + filter2: CatchFilter<Error>,
389 + filter3: CatchFilter<Error>,
390 + filter4: CatchFilter<Error>,
391 + value: U,
392 + ): Bluebird<R | U>;
393 + catchReturn<U>(
394 + filter1: CatchFilter<Error>,
395 + filter2: CatchFilter<Error>,
396 + filter3: CatchFilter<Error>,
397 + value: U,
398 + ): Bluebird<R | U>;
399 + catchReturn<U>(
400 + filter1: CatchFilter<Error>,
401 + filter2: CatchFilter<Error>,
402 + value: U,
403 + ): Bluebird<R | U>;
404 + catchReturn<U>(
405 + filter1: CatchFilter<Error>,
406 + value: U,
407 + ): Bluebird<R | U>;
408 +
409 + /**
410 + * Convenience method for:
411 + *
412 + * <code>
413 + * .catch(function() {
414 + * throw reason;
415 + * });
416 + * </code>
417 + * Same limitations apply as with `.catchReturn()`.
418 + */
419 + catchThrow(reason: Error): Bluebird<R>;
420 +
421 + // No need to be specific about Error types in these overrides, since there's no handler function
422 + catchThrow(
423 + filter1: CatchFilter<Error>,
424 + filter2: CatchFilter<Error>,
425 + filter3: CatchFilter<Error>,
426 + filter4: CatchFilter<Error>,
427 + filter5: CatchFilter<Error>,
428 + reason: Error,
429 + ): Bluebird<R>;
430 + catchThrow(
431 + filter1: CatchFilter<Error>,
432 + filter2: CatchFilter<Error>,
433 + filter3: CatchFilter<Error>,
434 + filter4: CatchFilter<Error>,
435 + reason: Error,
436 + ): Bluebird<R>;
437 + catchThrow(
438 + filter1: CatchFilter<Error>,
439 + filter2: CatchFilter<Error>,
440 + filter3: CatchFilter<Error>,
441 + reason: Error,
442 + ): Bluebird<R>;
443 + catchThrow(
444 + filter1: CatchFilter<Error>,
445 + filter2: CatchFilter<Error>,
446 + reason: Error,
447 + ): Bluebird<R>;
448 + catchThrow(
449 + filter1: CatchFilter<Error>,
450 + reason: Error,
451 + ): Bluebird<R>;
452 +
453 + /**
454 + * Convert to String.
455 + */
456 + toString(): string;
457 +
458 + /**
459 + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`.
460 + */
461 + toJSON(): object;
462 +
463 + /**
464 + * 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.
465 + */
466 + spread<U>(fulfilledHandler: (...values: Array<IterableItem<R>>) => Resolvable<U>): Bluebird<U>;
467 +
468 + /**
469 + * 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.
470 + */
471 + all(): Bluebird<IterableOrNever<R>>;
472 +
473 + /**
474 + * 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.
475 + */
476 + props<K, V>(this: PromiseLike<Map<K, Resolvable<V>>>): Bluebird<Map<K, V>>;
477 + props<T>(this: PromiseLike<Bluebird.ResolvableProps<T>>): Bluebird<T>;
478 +
479 + /**
480 + * 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.
481 + */
482 + any(): Bluebird<IterableItem<R>>;
483 +
484 + /**
485 + * 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.
486 + */
487 + some(count: number): Bluebird<IterableOrNever<R>>;
488 +
489 + /**
490 + * 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.
491 + */
492 + race(): Bluebird<IterableItem<R>>;
493 +
494 + /**
495 + * 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.
496 + */
497 + map<U>(mapper: IterateFunction<IterableItem<R>, U>, options?: Bluebird.ConcurrencyOption): Bluebird<R extends Iterable<any> ? U[] : never>;
498 +
499 + /**
500 + * 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.
501 + */
502 + reduce<U>(reducer: (memo: U, item: IterableItem<R>, index: number, arrayLength: number) => Resolvable<U>, initialValue?: U): Bluebird<R extends Iterable<any> ? U : never>;
503 +
504 + /**
505 + * 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.
506 + */
507 + filter(filterer: IterateFunction<IterableItem<R>, boolean>, options?: Bluebird.ConcurrencyOption): Bluebird<IterableOrNever<R>>;
508 +
509 + /**
510 + * 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.
511 + */
512 + each(iterator: IterateFunction<IterableItem<R>, any>): Bluebird<IterableOrNever<R>>;
513 +
514 + /**
515 + * 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.
516 + */
517 + mapSeries<U>(iterator: IterateFunction<IterableItem<R>, U>): Bluebird<R extends Iterable<any> ? U[] : never>;
518 +
519 + /**
520 + * Cancel this `promise`. Will not do anything if this promise is already settled or if the cancellation feature has not been enabled
521 + */
522 + cancel(): void;
523 +
524 + /**
525 + * Basically sugar for doing: somePromise.catch(function(){});
526 + *
527 + * Which is needed in case error handlers are attached asynchronously to the promise later, which would otherwise result in premature unhandled rejection reporting.
528 + */
529 + suppressUnhandledRejections(): void;
530 +
531 + /**
532 + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise.
533 + *
534 + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call.
535 + * Otherwise it is passed as is as the first argument for the function call.
536 + *
537 + * Alias for `attempt();` for compatibility with earlier ECMAScript version.
538 + */
539 + static try<R>(fn: () => Resolvable<R>): Bluebird<R>;
540 + static attempt<R>(fn: () => Resolvable<R>): Bluebird<R>;
541 +
542 + /**
543 + * Returns a new function that wraps the given function `fn`.
544 + * 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.
545 + * This method is convenient when a function can sometimes return synchronously or throw synchronously.
546 + */
547 + static method<R>(fn: () => Resolvable<R>): () => Bluebird<R>;
548 + static method<R, A1>(fn: (arg1: A1) => Resolvable<R>): (arg1: A1) => Bluebird<R>;
549 + static method<R, A1, A2>(fn: (arg1: A1, arg2: A2) => Resolvable<R>): (arg1: A1, arg2: A2) => Bluebird<R>;
550 + static method<R, A1, A2, A3>(fn: (arg1: A1, arg2: A2, arg3: A3) => Resolvable<R>): (arg1: A1, arg2: A2, arg3: A3) => Bluebird<R>;
551 + 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>;
552 + 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>;
553 + static method<R>(fn: (...args: any[]) => Resolvable<R>): (...args: any[]) => Bluebird<R>;
554 +
555 + /**
556 + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state.
557 + */
558 + static resolve(): Bluebird<void>;
559 + static resolve<R>(value: Resolvable<R>): Bluebird<R>;
560 +
561 + /**
562 + * Create a promise that is rejected with the given `reason`.
563 + */
564 + static reject(reason: any): Bluebird<never>;
565 +
566 + /**
567 + * @deprecated
568 + * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution).
569 + * @see http://bluebirdjs.com/docs/deprecated-apis.html#promise-resolution
570 + */
571 + static defer<R>(): Bluebird.Resolver<R>; // tslint:disable-line no-unnecessary-generics
572 +
573 + /**
574 + * Cast the given `value` to a trusted promise.
575 + *
576 + * 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.
577 + * 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.
578 + */
579 + static cast<R>(value: Resolvable<R>): Bluebird<R>;
580 +
581 + /**
582 + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`.
583 + */
584 + static bind(thisArg: any): Bluebird<void>;
585 +
586 + /**
587 + * See if `value` is a trusted Promise.
588 + */
589 + static is(value: any): boolean;
590 +
591 + /**
592 + * Call this right after the library is loaded to enabled long stack traces.
593 + *
594 + * Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created.
595 + * Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency.
596 + */
597 + static longStackTraces(): void;
598 +
599 + /**
600 + * Returns a promise that will be resolved with value (or undefined) after given ms milliseconds.
601 + * If value is a promise, the delay will start counting down when it is fulfilled and the returned
602 + * promise will be fulfilled with the fulfillment value of the value promise.
603 + */
604 + static delay<R>(ms: number, value: Resolvable<R>): Bluebird<R>;
605 + static delay(ms: number): Bluebird<void>;
606 +
607 + /**
608 + * Returns a function that will wrap the given `nodeFunction`.
609 + *
610 + * 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.
611 + * The node function should conform to node.js convention of accepting a callback as last argument and
612 + * calling that callback with error as the first argument and success value on the second argument.
613 + *
614 + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them.
615 + *
616 + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`.
617 + */
618 + static promisify<T>(
619 + func: (callback: (err: any, result?: T) => void) => void,
620 + options?: Bluebird.PromisifyOptions
621 + ): () => Bluebird<T>;
622 + static promisify<T, A1>(
623 + func: (arg1: A1, callback: (err: any, result?: T) => void) => void,
624 + options?: Bluebird.PromisifyOptions
625 + ): (arg1: A1) => Bluebird<T>;
626 + static promisify<T, A1, A2>(
627 + func: (arg1: A1, arg2: A2, callback: (err: any, result?: T) => void) => void,
628 + options?: Bluebird.PromisifyOptions
629 + ): (arg1: A1, arg2: A2) => Bluebird<T>;
630 + static promisify<T, A1, A2, A3>(
631 + func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result?: T) => void) => void,
632 + options?: Bluebird.PromisifyOptions
633 + ): (arg1: A1, arg2: A2, arg3: A3) => Bluebird<T>;
634 + static promisify<T, A1, A2, A3, A4>(
635 + func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result?: T) => void) => void,
636 + options?: Bluebird.PromisifyOptions
637 + ): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird<T>;
638 + static promisify<T, A1, A2, A3, A4, A5>(
639 + func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result?: T) => void) => void,
640 + options?: Bluebird.PromisifyOptions
641 + ): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird<T>;
642 + static promisify(nodeFunction: (...args: any[]) => void, options?: Bluebird.PromisifyOptions): (...args: any[]) => Bluebird<any>;
643 +
644 + /**
645 + * 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.
646 + *
647 + * The promisified method name will be the original method name postfixed with `Async`. Returns the input object.
648 + *
649 + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example,
650 + * if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
651 + */
652 + // TODO how to model promisifyAll?
653 + static promisifyAll<T extends object>(target: T, options?: Bluebird.PromisifyAllOptions<T>): T;
654 +
655 + /**
656 + * Returns a promise that is resolved by a node style callback function.
657 + */
658 + static fromNode<T>(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird<T>;
659 + static fromCallback<T>(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird<T>;
660 +
661 + /**
662 + * Returns a function that can use `yield` to run asynchronous code synchronously.
663 + *
664 + * This feature requires the support of generators which are drafted in the next version of the language.
665 + * Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
666 + */
667 + // TODO: After https://github.com/Microsoft/TypeScript/issues/2983 is implemented, we can use
668 + // the return type propagation of generators to automatically infer the return type T.
669 + static coroutine<T>(
670 + generatorFunction: () => IterableIterator<any>,
671 + options?: Bluebird.CoroutineOptions
672 + ): () => Bluebird<T>;
673 + static coroutine<T, A1>(
674 + generatorFunction: (a1: A1) => IterableIterator<any>,
675 + options?: Bluebird.CoroutineOptions
676 + ): (a1: A1) => Bluebird<T>;
677 + static coroutine<T, A1, A2>(
678 + generatorFunction: (a1: A1, a2: A2) => IterableIterator<any>,
679 + options?: Bluebird.CoroutineOptions
680 + ): (a1: A1, a2: A2) => Bluebird<T>;
681 + static coroutine<T, A1, A2, A3>(
682 + generatorFunction: (a1: A1, a2: A2, a3: A3) => IterableIterator<any>,
683 + options?: Bluebird.CoroutineOptions
684 + ): (a1: A1, a2: A2, a3: A3) => Bluebird<T>;
685 + static coroutine<T, A1, A2, A3, A4>(
686 + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4) => IterableIterator<any>,
687 + options?: Bluebird.CoroutineOptions
688 + ): (a1: A1, a2: A2, a3: A3, a4: A4) => Bluebird<T>;
689 + static coroutine<T, A1, A2, A3, A4, A5>(
690 + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => IterableIterator<any>,
691 + options?: Bluebird.CoroutineOptions
692 + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => Bluebird<T>;
693 + static coroutine<T, A1, A2, A3, A4, A5, A6>(
694 + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => IterableIterator<any>,
695 + options?: Bluebird.CoroutineOptions
696 + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => Bluebird<T>;
697 + static coroutine<T, A1, A2, A3, A4, A5, A6, A7>(
698 + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => IterableIterator<any>,
699 + options?: Bluebird.CoroutineOptions
700 + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => Bluebird<T>;
701 + static coroutine<T, A1, A2, A3, A4, A5, A6, A7, A8>(
702 + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => IterableIterator<any>,
703 + options?: Bluebird.CoroutineOptions
704 + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => Bluebird<T>;
705 +
706 + /**
707 + * 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.
708 + *
709 + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
710 + */
711 + static onPossiblyUnhandledRejection(handler: (reason: any) => any): void;
712 +
713 + /**
714 + * Add handler as the handler to call when there is a possibly unhandled rejection.
715 + * The default handler logs the error stack to stderr or console.error in browsers.
716 + *
717 + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
718 + *
719 + * Note: this hook is specific to the bluebird instance its called on, application developers should use global rejection events.
720 + */
721 + static onPossiblyUnhandledRejection(handler?: (error: Error, promise: Bluebird<any>) => void): void;
722 +
723 + /**
724 + * 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.
725 + * The promise's fulfillment value is an array with fulfillment values at respective positions to the original array.
726 + * If any promise in the array rejects, the returned promise is rejected with the rejection reason.
727 + */
728 + // TODO enable more overloads
729 + // array with promises of different types
730 + static all<T1, T2, T3, T4, T5>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>]): Bluebird<[T1, T2, T3, T4, T5]>;
731 + static all<T1, T2, T3, T4>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>]): Bluebird<[T1, T2, T3, T4]>;
732 + static all<T1, T2, T3>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>]): Bluebird<[T1, T2, T3]>;
733 + static all<T1, T2>(values: [Resolvable<T1>, Resolvable<T2>]): Bluebird<[T1, T2]>;
734 + static all<T1>(values: [Resolvable<T1>]): Bluebird<[T1]>;
735 + // array with values
736 + static all<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R[]>;
737 +
738 + /**
739 + * 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.
740 + *
741 + * The promise's fulfillment value is an object with fulfillment values at respective keys to the original object.
742 + * If any promise in the object rejects, the returned promise is rejected with the rejection reason.
743 + *
744 + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties.
745 + * All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties.
746 + *
747 + * *The original object is not modified.*
748 + */
749 + // map
750 + static props<K, V>(map: Resolvable<Map<K, Resolvable<V>>>): Bluebird<Map<K, V>>;
751 + // trusted promise for object
752 + static props<T>(object: PromiseLike<Bluebird.ResolvableProps<T>>): Bluebird<T>; // tslint:disable-line:unified-signatures
753 + // object
754 + static props<T>(object: Bluebird.ResolvableProps<T>): Bluebird<T>; // tslint:disable-line:unified-signatures
755 +
756 + /**
757 + * 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.
758 + */
759 + static any<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R>;
760 +
761 + /**
762 + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is
763 + * fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value.
764 + *
765 + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending.
766 + */
767 + static race<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R>;
768 +
769 + /**
770 + * Initiate a competitive race between multiple promises or values (values will become immediately fulfilled promises).
771 + * When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of
772 + * the winners in order of resolution.
773 + *
774 + * If too many promises are rejected so that the promise can never become fulfilled,
775 + * it will be immediately rejected with an array of rejection reasons in the order they were thrown in.
776 + *
777 + * *The original array is not modified.*
778 + */
779 + static some<R>(values: Resolvable<Iterable<Resolvable<R>>>, count: number): Bluebird<R[]>;
780 +
781 + /**
782 + * Promise.join(
783 + * Promise<any>|any values...,
784 + * function handler
785 + * ) -> Promise
786 + * For coordinating multiple concurrent discrete promises.
787 + *
788 + * 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.
789 + * This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply
790 + */
791 + static join<R, A1>(
792 + arg1: Resolvable<A1>,
793 + handler: (arg1: A1) => Resolvable<R>
794 + ): Bluebird<R>;
795 + static join<R, A1, A2>(
796 + arg1: Resolvable<A1>,
797 + arg2: Resolvable<A2>,
798 + handler: (arg1: A1, arg2: A2) => Resolvable<R>
799 + ): Bluebird<R>;
800 + static join<R, A1, A2, A3>(
801 + arg1: Resolvable<A1>,
802 + arg2: Resolvable<A2>,
803 + arg3: Resolvable<A3>,
804 + handler: (arg1: A1, arg2: A2, arg3: A3) => Resolvable<R>
805 + ): Bluebird<R>;
806 + static join<R, A1, A2, A3, A4>(
807 + arg1: Resolvable<A1>,
808 + arg2: Resolvable<A2>,
809 + arg3: Resolvable<A3>,
810 + arg4: Resolvable<A4>,
811 + handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Resolvable<R>
812 + ): Bluebird<R>;
813 + static join<R, A1, A2, A3, A4, A5>(
814 + arg1: Resolvable<A1>,
815 + arg2: Resolvable<A2>,
816 + arg3: Resolvable<A3>,
817 + arg4: Resolvable<A4>,
818 + arg5: Resolvable<A5>,
819 + handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Resolvable<R>
820 + ): Bluebird<R>;
821 +
822 + // variadic array
823 + /** @deprecated use .all instead */
824 + static join<R>(...values: Array<Resolvable<R>>): Bluebird<R[]>;
825 +
826 + /**
827 + * Map an array, or a promise of an array,
828 + * which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)`
829 + * where `item` is the resolved value of a respective promise in the input array.
830 + * If any promise in the input array is rejected the returned promise is rejected as well.
831 + *
832 + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well.
833 + *
834 + * *The original array is not modified.*
835 + */
836 + static map<R, U>(
837 + values: Resolvable<Iterable<Resolvable<R>>>,
838 + mapper: IterateFunction<R, U>,
839 + options?: Bluebird.ConcurrencyOption
840 + ): Bluebird<U[]>;
841 +
842 + /**
843 + * Reduce an array, or a promise of an array,
844 + * which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)`
845 + * where `item` is the resolved value of a respective promise in the input array.
846 + * If any promise in the input array is rejected the returned promise is rejected as well.
847 + *
848 + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
849 + *
850 + * *The original array is not modified. If no `initialValue` is given and the array doesn't contain at least 2 items,
851 + * the callback will not be called and `undefined` is returned.
852 + *
853 + * If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.*
854 + */
855 + static reduce<R, U>(
856 + values: Resolvable<Iterable<Resolvable<R>>>,
857 + reducer: (total: U, current: R, index: number, arrayLength: number) => Resolvable<U>,
858 + initialValue?: U
859 + ): Bluebird<U>;
860 +
861 + /**
862 + * Filter an array, or a promise of an array,
863 + * which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)`
864 + * where `item` is the resolved value of a respective promise in the input array.
865 + * If any promise in the input array is rejected the returned promise is rejected as well.
866 + *
867 + * 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.
868 + *
869 + * *The original array is not modified.
870 + */
871 + static filter<R>(
872 + values: Resolvable<Iterable<Resolvable<R>>>,
873 + filterer: IterateFunction<R, boolean>,
874 + option?: Bluebird.ConcurrencyOption
875 + ): Bluebird<R[]>;
876 +
877 + /**
878 + * Iterate over an array, or a promise of an array,
879 + * which contains promises (or a mix of promises and values) with the given iterator function with the signature `(item, index, value)`
880 + * where item is the resolved value of a respective promise in the input array.
881 + * Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well.
882 + *
883 + * Resolves to the original array unmodified, this method is meant to be used for side effects.
884 + * If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
885 + */
886 + static each<R>(
887 + values: Resolvable<Iterable<Resolvable<R>>>,
888 + iterator: IterateFunction<R, any>
889 + ): Bluebird<R[]>;
890 +
891 + /**
892 + * Given an Iterable(arrays are Iterable), or a promise of an Iterable, which produces promises (or a mix of promises and values),
893 + * iterate over all the values in the Iterable into an array and iterate over the array serially, in-order.
894 + *
895 + * Returns a promise for an array that contains the values returned by the iterator function in their respective positions.
896 + * 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.
897 + * This results in a mapSeries kind of utility but it can also be used simply as a side effect iterator similar to Array#forEach.
898 + *
899 + * 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.
900 + */
901 + static mapSeries<R, U>(
902 + values: Resolvable<Iterable<Resolvable<R>>>,
903 + iterator: IterateFunction<R, U>
904 + ): Bluebird<U[]>;
905 +
906 + /**
907 + * A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`.
908 + *
909 + * Returns a Disposer object which encapsulates both the resource as well as the method to clean it up.
910 + * The user can pass this object to `Promise.using` to get access to the resource when it becomes available,
911 + * as well as to ensure its automatically cleaned up.
912 + *
913 + * The second argument passed to a disposer is the result promise of the using block, which you can
914 + * inspect synchronously.
915 + */
916 + disposer(disposeFn: (arg: R, promise: Bluebird<R>) => Resolvable<void>): Bluebird.Disposer<R>;
917 +
918 + /**
919 + * In conjunction with `.disposer`, using will make sure that no matter what, the specified disposer
920 + * will be called when the promise returned by the callback passed to using has settled. The disposer is
921 + * necessary because there is no standard interface in node for disposing resources.
922 + */
923 + static using<R, T>(
924 + disposer: Bluebird.Disposer<R>,
925 + executor: (transaction: R) => PromiseLike<T>
926 + ): Bluebird<T>;
927 + static using<R1, R2, T>(
928 + disposer: Bluebird.Disposer<R1>,
929 + disposer2: Bluebird.Disposer<R2>,
930 + executor: (transaction1: R1, transaction2: R2
931 + ) => PromiseLike<T>): Bluebird<T>;
932 + static using<R1, R2, R3, T>(
933 + disposer: Bluebird.Disposer<R1>,
934 + disposer2: Bluebird.Disposer<R2>,
935 + disposer3: Bluebird.Disposer<R3>,
936 + executor: (transaction1: R1, transaction2: R2, transaction3: R3) => PromiseLike<T>
937 + ): Bluebird<T>;
938 +
939 + /**
940 + * Configure long stack traces, warnings, monitoring and cancellation.
941 + * Note that even though false is the default here, a development environment might be detected which automatically
942 + * enables long stack traces and warnings.
943 + */
944 + static config(options: {
945 + /** Enable warnings */
946 + warnings?: boolean | {
947 + /** Enables all warnings except forgotten return statements. */
948 + wForgottenReturn: boolean;
949 + };
950 + /** Enable long stack traces */
951 + longStackTraces?: boolean;
952 + /** Enable cancellation */
953 + cancellation?: boolean;
954 + /** Enable monitoring */
955 + monitoring?: boolean;
956 + }): void;
957 +
958 + /**
959 + * 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.
960 + * If promise cancellation is enabled, passed in function will receive one more function argument `onCancel` that allows to register an optional cancellation callback.
961 + */
962 + static Promise: typeof Bluebird;
963 +
964 + /**
965 + * The version number of the library
966 + */
967 + static version: string;
968 +}
969 +
970 +declare namespace Bluebird {
971 + interface ConcurrencyOption {
972 + concurrency: number;
973 + }
974 + interface SpreadOption {
975 + spread: boolean;
976 + }
977 + interface FromNodeOptions {
978 + multiArgs?: boolean;
979 + }
980 + interface PromisifyOptions {
981 + context?: any;
982 + multiArgs?: boolean;
983 + }
984 + interface PromisifyAllOptions<T> extends PromisifyOptions {
985 + suffix?: string;
986 + filter?(name: string, func: (...args: any[]) => any, target?: any, passesDefaultFilter?: boolean): boolean;
987 + // The promisifier gets a reference to the original method and should return a function which returns a promise
988 + promisifier?(this: T, originalMethod: (...args: any[]) => any, defaultPromisifer: (...args: any[]) => (...args: any[]) => Bluebird<any>): () => PromiseLike<any>;
989 + }
990 + interface CoroutineOptions {
991 + yieldHandler(value: any): any;
992 + }
993 +
994 + /**
995 + * Represents an error is an explicit promise rejection as opposed to a thrown error.
996 + * For example, if an error is errbacked by a callback API promisified through undefined or undefined
997 + * and is not a typed error, it will be converted to a `OperationalError` which has the original error in
998 + * the `.cause` property.
999 + *
1000 + * `OperationalError`s are caught in `.error` handlers.
1001 + */
1002 + class OperationalError extends Error { }
1003 +
1004 + /**
1005 + * Signals that an operation has timed out. Used as a custom cancellation reason in `.timeout`.
1006 + */
1007 + class TimeoutError extends Error { }
1008 +
1009 + /**
1010 + * Signals that an operation has been aborted or cancelled. The default reason used by `.cancel`.
1011 + */
1012 + class CancellationError extends Error { }
1013 +
1014 + /**
1015 + * A collection of errors. `AggregateError` is an array-like object, with numeric indices and a `.length` property.
1016 + * It supports all generic array methods such as `.forEach` directly.
1017 + *
1018 + * `AggregateError`s are caught in `.error` handlers, even if the contained errors are not operational.
1019 + *
1020 + * `Promise.some` and `Promise.any` use `AggregateError` as rejection reason when they fail.
1021 + */
1022 + class AggregateError extends Error implements ArrayLike<Error> {
1023 + length: number;
1024 + [index: number]: Error;
1025 + join(separator?: string): string;
1026 + pop(): Error;
1027 + push(...errors: Error[]): number;
1028 + shift(): Error;
1029 + unshift(...errors: Error[]): number;
1030 + slice(begin?: number, end?: number): AggregateError;
1031 + filter(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError;
1032 + forEach(callback: (element: Error, index: number, array: AggregateError) => void, thisArg?: any): undefined;
1033 + some(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean;
1034 + every(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean;
1035 + map(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError;
1036 + indexOf(searchElement: Error, fromIndex?: number): number;
1037 + lastIndexOf(searchElement: Error, fromIndex?: number): number;
1038 + reduce(callback: (accumulator: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any;
1039 + reduceRight(callback: (previousValue: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any;
1040 + sort(compareFunction?: (errLeft: Error, errRight: Error) => number): AggregateError;
1041 + reverse(): AggregateError;
1042 + }
1043 +
1044 + /**
1045 + * returned by `Bluebird.disposer()`.
1046 + */
1047 + class Disposer<R> { }
1048 +
1049 + /** @deprecated Use PromiseLike<T> directly. */
1050 + type Thenable<T> = PromiseLike<T>;
1051 +
1052 + type ResolvableProps<T> = object & {[K in keyof T]: Resolvable<T[K]>};
1053 +
1054 + interface Resolver<R> {
1055 + /**
1056 + * Returns a reference to the controlled promise that can be passed to clients.
1057 + */
1058 + promise: Bluebird<R>;
1059 +
1060 + /**
1061 + * 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.
1062 + */
1063 + resolve(value: R): void;
1064 + resolve(): void;
1065 +
1066 + /**
1067 + * Reject the underlying promise with `reason` as the rejection reason.
1068 + */
1069 + reject(reason: any): void;
1070 +
1071 + /**
1072 + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property.
1073 + * The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions.
1074 + *
1075 + * If the the callback is called with multiple success values, the resolver fulfills its promise with an array of the values.
1076 + */
1077 + // TODO specify resolver callback
1078 + callback(err: any, value: R, ...values: R[]): void;
1079 + }
1080 +
1081 + interface Inspection<R> {
1082 + /**
1083 + * See if the underlying promise was fulfilled at the creation time of this inspection object.
1084 + */
1085 + isFulfilled(): boolean;
1086 +
1087 + /**
1088 + * See if the underlying promise was rejected at the creation time of this inspection object.
1089 + */
1090 + isRejected(): boolean;
1091 +
1092 + /**
1093 + * See if the underlying promise was cancelled at the creation time of this inspection object.
1094 + */
1095 + isCancelled(): boolean;
1096 +
1097 + /**
1098 + * See if the underlying promise was defer at the creation time of this inspection object.
1099 + */
1100 + isPending(): boolean;
1101 +
1102 + /**
1103 + * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object.
1104 + *
1105 + * throws `TypeError`
1106 + */
1107 + value(): R;
1108 +
1109 + /**
1110 + * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object.
1111 + *
1112 + * throws `TypeError`
1113 + */
1114 + reason(): any;
1115 + }
1116 +
1117 + /**
1118 + * Returns a new independent copy of the Bluebird library.
1119 + *
1120 + * 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.
1121 + */
1122 + function getNewLibraryCopy(): typeof Bluebird;
1123 +
1124 + /**
1125 + * This is relevant to browser environments with no module loader.
1126 + *
1127 + * Release control of the Promise namespace to whatever it was before this library was loaded.
1128 + * Returns a reference to the library namespace so you can attach it to something else.
1129 + */
1130 + function noConflict(): typeof Bluebird;
1131 +
1132 + /**
1133 + * Changes how bluebird schedules calls a-synchronously.
1134 + *
1135 + * @param scheduler Should be a function that asynchronously schedules
1136 + * the calling of the passed in function
1137 + */
1138 + function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void;
1139 +}
1140 +
1141 +export = Bluebird;
1 +{
2 + "_from": "@types/bluebird@^3.5.19",
3 + "_id": "@types/bluebird@3.5.24",
4 + "_inBundle": false,
5 + "_integrity": "sha512-YeQoDpq4Lm8ppSBqAnAeF/xy1cYp/dMTif2JFcvmAbETMRlvKHT2iLcWu+WyYiJO3b3Ivokwo7EQca/xfLVJmg==",
6 + "_location": "/@types/bluebird",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "@types/bluebird@^3.5.19",
12 + "name": "@types/bluebird",
13 + "escapedName": "@types%2fbluebird",
14 + "scope": "@types",
15 + "rawSpec": "^3.5.19",
16 + "saveSpec": null,
17 + "fetchSpec": "^3.5.19"
18 + },
19 + "_requiredBy": [
20 + "/promise-mysql"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/@types/bluebird/-/bluebird-3.5.24.tgz",
23 + "_shasum": "11f76812531c14f793b8ecbf1de96f672905de8a",
24 + "_spec": "@types/bluebird@^3.5.19",
25 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/promise-mysql",
26 + "bugs": {
27 + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
28 + },
29 + "bundleDependencies": false,
30 + "contributors": [
31 + {
32 + "name": "Leonard Hecker",
33 + "url": "https://github.com/lhecker"
34 + }
35 + ],
36 + "dependencies": {},
37 + "deprecated": false,
38 + "description": "TypeScript definitions for bluebird",
39 + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
40 + "license": "MIT",
41 + "main": "",
42 + "name": "@types/bluebird",
43 + "repository": {
44 + "type": "git",
45 + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
46 + },
47 + "scripts": {},
48 + "typeScriptVersion": "2.8",
49 + "typesPublisherContentHash": "886708ab10a8bb6421a5748563a83e005973395bfeff5765f04a8b35fa01a420",
50 + "version": "3.5.24"
51 +}
1 + MIT License
2 +
3 + Copyright (c) Microsoft Corporation. All rights reserved.
4 +
5 + Permission is hereby granted, free of charge, to any person obtaining a copy
6 + of this software and associated documentation files (the "Software"), to deal
7 + in the Software without restriction, including without limitation the rights
8 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 + copies of the Software, and to permit persons to whom the Software is
10 + furnished to do so, subject to the following conditions:
11 +
12 + The above copyright notice and this permission notice shall be included in all
13 + copies or substantial portions of the Software.
14 +
15 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 + SOFTWARE
1 +# Installation
2 +> `npm install --save @types/mysql`
3 +
4 +# Summary
5 +This package contains type definitions for mysql (https://github.com/mysqljs/mysql).
6 +
7 +# Details
8 +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mysql
9 +
10 +Additional Details
11 + * Last updated: Thu, 31 May 2018 20:09:03 GMT
12 + * Dependencies: stream, tls, node
13 + * Global values: none
14 +
15 +# Credits
16 +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>.
1 +// Type definitions for mysql 2.15
2 +// Project: https://github.com/mysqljs/mysql
3 +// Definitions by: William Johnston <https://github.com/wjohnsto>
4 +// Kacper Polak <https://github.com/kacepe>
5 +// Krittanan Pingclasai <https://github.com/kpping>
6 +// James Munro <https://github.com/jdmunro>
7 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
8 +// TypeScript Version: 2.1
9 +
10 +/// <reference types="node" />
11 +
12 +import stream = require("stream");
13 +import tls = require("tls");
14 +
15 +export interface EscapeFunctions {
16 + escape(value: any, stringifyObjects?: boolean, timeZone?: string): string;
17 +
18 + escapeId(value: string, forbidQualified?: boolean): string;
19 +
20 + format(sql: string, values: any[], stringifyObjects?: boolean, timeZone?: string): string;
21 +}
22 +
23 +// implements EscapeFunctions
24 +export function escape(value: any, stringifyObjects?: boolean, timeZone?: string): string;
25 +
26 +export function escapeId(value: string, forbidQualified?: boolean): string;
27 +
28 +export function format(sql: string, values: any[], stringifyObjects?: boolean, timeZone?: string): string;
29 +
30 +export function createConnection(connectionUri: string | ConnectionConfig): Connection;
31 +
32 +export function createPool(config: PoolConfig | string): Pool;
33 +
34 +export function createPoolCluster(config?: PoolClusterConfig): PoolCluster;
35 +
36 +export function raw(sql: string): () => string;
37 +
38 +export interface Connection extends EscapeFunctions {
39 + config: ConnectionConfig;
40 +
41 + state: 'connected' | 'authenticated' | 'disconnected' | 'protocol_error' | string;
42 +
43 + threadId: number | null;
44 +
45 + createQuery: QueryFunction;
46 +
47 + connect(callback?: (err: MysqlError, ...args: any[]) => void): void;
48 +
49 + connect(options: any, callback?: (err: MysqlError, ...args: any[]) => void): void;
50 +
51 + changeUser(options: ConnectionOptions, callback?: (err: MysqlError) => void): void;
52 + changeUser(callback: (err: MysqlError) => void): void;
53 +
54 + beginTransaction(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
55 +
56 + beginTransaction(callback: (err: MysqlError) => void): void;
57 +
58 + commit(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
59 + commit(callback: (err: MysqlError) => void): void;
60 +
61 + rollback(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
62 + rollback(callback: (err: MysqlError) => void): void;
63 +
64 + query: QueryFunction;
65 +
66 + ping(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
67 + ping(callback: (err: MysqlError) => void): void;
68 +
69 + statistics(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
70 + statistics(callback: (err: MysqlError) => void): void;
71 +
72 + end(callback?: (err: MysqlError, ...args: any[]) => void): void;
73 + end(options: any, callback: (err: MysqlError, ...args: any[]) => void): void;
74 +
75 + destroy(): void;
76 +
77 + pause(): void;
78 +
79 + resume(): void;
80 +
81 + on(ev: 'drain' | 'connect', callback: () => void): Connection;
82 +
83 + on(ev: 'end', callback: (err?: MysqlError) => void): Connection;
84 +
85 + on(ev: 'fields', callback: (fields: any[]) => void): Connection;
86 +
87 + on(ev: 'error', callback: (err: MysqlError) => void): Connection;
88 +
89 + on(ev: 'enqueue', callback: (...args: any[]) => void): Connection;
90 +
91 + on(ev: string, callback: (...args: any[]) => void): this;
92 +}
93 +
94 +export interface PoolConnection extends Connection {
95 + release(): void;
96 +
97 + end(): void;
98 +
99 + destroy(): void;
100 +}
101 +
102 +export interface Pool extends EscapeFunctions {
103 + config: PoolConfig;
104 +
105 + getConnection(callback: (err: MysqlError, connection: PoolConnection) => void): void;
106 +
107 + acquireConnection(connection: PoolConnection, callback: (err: MysqlError, connection: PoolConnection) => void): void;
108 +
109 + releaseConnection(connection: PoolConnection): void;
110 +
111 + end(callback?: (err: MysqlError) => void): void;
112 +
113 + query: QueryFunction;
114 +
115 + on(ev: 'connection' | 'acquire' | 'release', callback: (connection: PoolConnection) => void): Pool;
116 +
117 + on(ev: 'error', callback: (err: MysqlError) => void): Pool;
118 +
119 + on(ev: 'enqueue', callback: (err?: MysqlError) => void): Pool;
120 +
121 + on(ev: string, callback: (...args: any[]) => void): Pool;
122 +}
123 +
124 +export interface PoolCluster {
125 + config: PoolClusterConfig;
126 +
127 + add(config: PoolConfig): void;
128 +
129 + add(id: string, config: PoolConfig): void;
130 +
131 + end(callback?: (err: MysqlError) => void): void;
132 +
133 + of(pattern: string, selector?: string): Pool;
134 + of(pattern: undefined | null | false, selector: string): Pool;
135 +
136 + /**
137 + * remove all pools which match pattern
138 + */
139 + remove(pattern: string): void;
140 +
141 + getConnection(callback: (err: MysqlError, connection: PoolConnection) => void): void;
142 +
143 + getConnection(pattern: string, callback: (err: MysqlError, connection: PoolConnection) => void): void;
144 +
145 + getConnection(pattern: string, selector: string, callback: (err: MysqlError, connection: PoolConnection) => void): void;
146 +
147 + on(ev: string, callback: (...args: any[]) => void): PoolCluster;
148 +
149 + on(ev: 'remove' | 'offline' | 'remove', callback: (nodeId: string) => void): PoolCluster;
150 +}
151 +
152 +// related to Query
153 +export type packetCallback = (packet: any) => void;
154 +
155 +export interface Query {
156 + /**
157 + * Template query
158 + */
159 + sql: string;
160 +
161 + /**
162 + * Values for template query
163 + */
164 + values?: string[];
165 +
166 + /**
167 + * Default true
168 + */
169 + typeCast?: TypeCast;
170 +
171 + /**
172 + * Default false
173 + */
174 + nestedTables: boolean;
175 +
176 + /**
177 + * Emits a query packet to start the query
178 + */
179 + start(): void;
180 +
181 + /**
182 + * Determines the packet class to use given the first byte of the packet.
183 + *
184 + * @param byte The first byte of the packet
185 + * @param parser The packet parser
186 + */
187 + determinePacket(byte: number, parser: any): any;
188 +
189 + OkPacket: packetCallback;
190 + ErrorPacket: packetCallback;
191 + ResultSetHeaderPacket: packetCallback;
192 + FieldPacket: packetCallback;
193 + EofPacket: packetCallback;
194 +
195 + RowDataPacket(packet: any, parser: any, connection: Connection): void;
196 +
197 + /**
198 + * Creates a Readable stream with the given options
199 + *
200 + * @param options The options for the stream. (see readable-stream package)
201 + */
202 + stream(options?: stream.ReadableOptions): stream.Readable;
203 +
204 + on(ev: string, callback: (...args: any[]) => void): Query;
205 +
206 + on(ev: 'result', callback: (row: any, index: number) => void): Query;
207 +
208 + on(ev: 'error', callback: (err: MysqlError) => void): Query;
209 +
210 + on(ev: 'fields', callback: (fields: FieldInfo[], index: number) => void): Query;
211 +
212 + on(ev: 'packet', callback: (packet: any) => void): Query;
213 +
214 + on(ev: 'end', callback: () => void): Query;
215 +}
216 +
217 +export interface GeometryType extends Array<{x: number, y: number} | GeometryType> {
218 + x: number;
219 + y: number;
220 +}
221 +
222 +export type TypeCast = boolean | (
223 + (field: FieldInfo
224 + & { type: string, length: number, string(): string, buffer(): Buffer, geometry(): null | GeometryType},
225 + next: () => void) => any);
226 +
227 +export type queryCallback = (err: MysqlError | null, results?: any, fields?: FieldInfo[]) => void;
228 +
229 +// values can be non [], see custom format (https://github.com/mysqljs/mysql#custom-format)
230 +export interface QueryFunction {
231 + (query: Query): Query;
232 +
233 + (options: string | QueryOptions, callback?: queryCallback): Query;
234 +
235 + (options: string, values: any, callback?: queryCallback): Query;
236 +}
237 +
238 +export interface QueryOptions {
239 + /**
240 + * The SQL for the query
241 + */
242 + sql: string;
243 +
244 + /**
245 + * Values for template query
246 + */
247 + values?: any;
248 +
249 + /**
250 + * Every operation takes an optional inactivity timeout option. This allows you to specify appropriate timeouts for
251 + * operations. It is important to note that these timeouts are not part of the MySQL protocol, and rather timeout
252 + * operations through the client. This means that when a timeout is reached, the connection it occurred on will be
253 + * destroyed and no further operations can be performed.
254 + */
255 + timeout?: number;
256 +
257 + /**
258 + * Either a boolean or string. If true, tables will be nested objects. If string (e.g. '_'), tables will be
259 + * nested as tableName_fieldName
260 + */
261 + nestTables?: any;
262 +
263 + /**
264 + * Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future)
265 + * to disable type casting, but you can currently do so on either the connection or query level. (Default: true)
266 + *
267 + * You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself.
268 + *
269 + * WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once.
270 + *
271 + * field.string()
272 + * field.buffer()
273 + * field.geometry()
274 + *
275 + * are aliases for
276 + *
277 + * parser.parseLengthCodedString()
278 + * parser.parseLengthCodedBuffer()
279 + * parser.parseGeometryValue()
280 + *
281 + * You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast
282 + */
283 + typeCast?: TypeCast;
284 +}
285 +
286 +export interface ConnectionOptions {
287 + /**
288 + * The MySQL user to authenticate as
289 + */
290 + user?: string;
291 +
292 + /**
293 + * The password of that MySQL user
294 + */
295 + password?: string;
296 +
297 + /**
298 + * Name of the database to use for this connection
299 + */
300 + database?: string;
301 +
302 + /**
303 + * The charset for the connection. This is called "collation" in the SQL-level of MySQL (like utf8_general_ci).
304 + * If a SQL-level charset is specified (like utf8mb4) then the default collation for that charset is used.
305 + * (Default: 'UTF8_GENERAL_CI')
306 + */
307 + charset?: string;
308 +
309 + /**
310 + * Number of milliseconds
311 + */
312 + timeout?: number;
313 +}
314 +
315 +export interface ConnectionConfig extends ConnectionOptions {
316 + /**
317 + * The hostname of the database you are connecting to. (Default: localhost)
318 + */
319 + host?: string;
320 +
321 + /**
322 + * The port number to connect to. (Default: 3306)
323 + */
324 + port?: number;
325 +
326 + /**
327 + * The source IP address to use for TCP connection
328 + */
329 + localAddress?: string;
330 +
331 + /**
332 + * The path to a unix domain socket to connect to. When used host and port are ignored
333 + */
334 + socketPath?: string;
335 +
336 + /**
337 + * The timezone used to store local dates. (Default: 'local')
338 + */
339 + timezone?: string;
340 +
341 + /**
342 + * The milliseconds before a timeout occurs during the initial connection to the MySQL server. (Default: 10 seconds)
343 + */
344 + connectTimeout?: number;
345 +
346 + /**
347 + * Stringify objects instead of converting to values. (Default: 'false')
348 + */
349 + stringifyObjects?: boolean;
350 +
351 + /**
352 + * Allow connecting to MySQL instances that ask for the old (insecure) authentication method. (Default: false)
353 + */
354 + insecureAuth?: boolean;
355 +
356 + /**
357 + * Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future)
358 + * to disable type casting, but you can currently do so on either the connection or query level. (Default: true)
359 + *
360 + * You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself.
361 + *
362 + * WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once.
363 + *
364 + * field.string()
365 + * field.buffer()
366 + * field.geometry()
367 + *
368 + * are aliases for
369 + *
370 + * parser.parseLengthCodedString()
371 + * parser.parseLengthCodedBuffer()
372 + * parser.parseGeometryValue()
373 + *
374 + * You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast
375 + */
376 + typeCast?: TypeCast;
377 +
378 + /**
379 + * A custom query format function
380 + */
381 + queryFormat?(query: string, values: any): void;
382 +
383 + /**
384 + * When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option
385 + * (Default: false)
386 + */
387 + supportBigNumbers?: boolean;
388 +
389 + /**
390 + * Enabling both supportBigNumbers and bigNumberStrings forces big numbers (BIGINT and DECIMAL columns) to be
391 + * always returned as JavaScript String objects (Default: false). Enabling supportBigNumbers but leaving
392 + * bigNumberStrings disabled will return big numbers as String objects only when they cannot be accurately
393 + * represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5)
394 + * (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects.
395 + * This option is ignored if supportBigNumbers is disabled.
396 + */
397 + bigNumberStrings?: boolean;
398 +
399 + /**
400 + * Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript
401 + * Date objects. Can be true/false or an array of type names to keep as strings. (Default: false)
402 + */
403 + dateStrings?: boolean | Array<'TIMESTAMP' | 'DATETIME' | 'DATE'>;
404 +
405 + /**
406 + * This will print all incoming and outgoing packets on stdout.
407 + * You can also restrict debugging to packet types by passing an array of types (strings) to debug;
408 + *
409 + * (Default: false)
410 + */
411 + debug?: boolean | string[] | Types[];
412 +
413 + /**
414 + * Generates stack traces on errors to include call site of library entrance ("long stack traces"). Slight
415 + * performance penalty for most calls. (Default: true)
416 + */
417 + trace?: boolean;
418 +
419 + /**
420 + * Allow multiple mysql statements per query. Be careful with this, it exposes you to SQL injection attacks. (Default: false)
421 + */
422 + multipleStatements?: boolean;
423 +
424 + /**
425 + * List of connection flags to use other than the default ones. It is also possible to blacklist default ones
426 + */
427 + flags?: string[];
428 +
429 + /**
430 + * object with ssl parameters or a string containing name of ssl profile
431 + */
432 + ssl?: string | (tls.SecureContextOptions & { rejectUnauthorized?: boolean });
433 +}
434 +
435 +export interface PoolConfig extends ConnectionConfig {
436 + /**
437 + * The milliseconds before a timeout occurs during the connection acquisition. This is slightly different from connectTimeout,
438 + * because acquiring a pool connection does not always involve making a connection. (Default: 10 seconds)
439 + */
440 + acquireTimeout?: number;
441 +
442 + /**
443 + * Determines the pool's action when no connections are available and the limit has been reached. If true, the pool will queue
444 + * the connection request and call it when one becomes available. If false, the pool will immediately call back with an error.
445 + * (Default: true)
446 + */
447 + waitForConnections?: boolean;
448 +
449 + /**
450 + * The maximum number of connections to create at once. (Default: 10)
451 + */
452 + connectionLimit?: number;
453 +
454 + /**
455 + * The maximum number of connection requests the pool will queue before returning an error from getConnection. If set to 0, there
456 + * is no limit to the number of queued connection requests. (Default: 0)
457 + */
458 + queueLimit?: number;
459 +}
460 +
461 +export interface PoolClusterConfig {
462 + /**
463 + * If true, PoolCluster will attempt to reconnect when connection fails. (Default: true)
464 + */
465 + canRetry?: boolean;
466 +
467 + /**
468 + * If connection fails, node's errorCount increases. When errorCount is greater than removeNodeErrorCount,
469 + * remove a node in the PoolCluster. (Default: 5)
470 + */
471 + removeNodeErrorCount?: number;
472 +
473 + /**
474 + * If connection fails, specifies the number of milliseconds before another connection attempt will be made.
475 + * If set to 0, then node will be removed instead and never re-used. (Default: 0)
476 + */
477 + restoreNodeTimeout?: number;
478 +
479 + /**
480 + * The default selector. (Default: RR)
481 + * RR: Select one alternately. (Round-Robin)
482 + * RANDOM: Select the node by random function.
483 + * ORDER: Select the first node available unconditionally.
484 + */
485 + defaultSelector?: string;
486 +}
487 +
488 +export interface MysqlError extends Error {
489 + /**
490 + * Either a MySQL server error (e.g. 'ER_ACCESS_DENIED_ERROR'),
491 + * a node.js error (e.g. 'ECONNREFUSED') or an internal error
492 + * (e.g. 'PROTOCOL_CONNECTION_LOST').
493 + */
494 + code: string;
495 +
496 + /**
497 + * The error number for the error code
498 + */
499 + errno: number;
500 +
501 + /**
502 + * The sql state marker
503 + */
504 + sqlStateMarker?: string;
505 +
506 + /**
507 + * The sql state
508 + */
509 + sqlState?: string;
510 +
511 + /**
512 + * The field count
513 + */
514 + fieldCount?: number;
515 +
516 + /**
517 + * The stack trace for the error
518 + */
519 + stack?: string;
520 +
521 + /**
522 + * Boolean, indicating if this error is terminal to the connection object.
523 + */
524 + fatal: boolean;
525 +
526 + /**
527 + * SQL of failed query
528 + */
529 + sql?: string;
530 +
531 + /**
532 + * Error message from MySQL
533 + */
534 + sqlMessage?: string;
535 +}
536 +
537 +export const enum Types {
538 + DECIMAL = 0x00, // aka DECIMAL (http://dev.mysql.com/doc/refman/5.0/en/precision-math-decimal-changes.html)
539 + TINY = 0x01, // aka TINYINT, 1 byte
540 + SHORT = 0x02, // aka SMALLINT, 2 bytes
541 + LONG = 0x03, // aka INT, 4 bytes
542 + FLOAT = 0x04, // aka FLOAT, 4-8 bytes
543 + DOUBLE = 0x05, // aka DOUBLE, 8 bytes
544 + NULL = 0x06, // NULL (used for prepared statements, I think)
545 + TIMESTAMP = 0x07, // aka TIMESTAMP
546 + LONGLONG = 0x08, // aka BIGINT, 8 bytes
547 + INT24 = 0x09, // aka MEDIUMINT, 3 bytes
548 + DATE = 0x0a, // aka DATE
549 + TIME = 0x0b, // aka TIME
550 + DATETIME = 0x0c, // aka DATETIME
551 + YEAR = 0x0d, // aka YEAR, 1 byte (don't ask)
552 + NEWDATE = 0x0e, // aka ?
553 + VARCHAR = 0x0f, // aka VARCHAR (?)
554 + BIT = 0x10, // aka BIT, 1-8 byte
555 + TIMESTAMP2 = 0x11, // aka TIMESTAMP with fractional seconds
556 + DATETIME2 = 0x12, // aka DATETIME with fractional seconds
557 + TIME2 = 0x13, // aka TIME with fractional seconds
558 + JSON = 0xf5, // aka JSON
559 + NEWDECIMAL = 0xf6, // aka DECIMAL
560 + ENUM = 0xf7, // aka ENUM
561 + SET = 0xf8, // aka SET
562 + TINY_BLOB = 0xf9, // aka TINYBLOB, TINYTEXT
563 + MEDIUM_BLOB = 0xfa, // aka MEDIUMBLOB, MEDIUMTEXT
564 + LONG_BLOB = 0xfb, // aka LONGBLOG, LONGTEXT
565 + BLOB = 0xfc, // aka BLOB, TEXT
566 + VAR_STRING = 0xfd, // aka VARCHAR, VARBINARY
567 + STRING = 0xfe, // aka CHAR, BINARY
568 + GEOMETRY = 0xff, // aka GEOMETRY
569 +}
570 +
571 +export interface FieldInfo {
572 + catalog: string;
573 + db: string;
574 + table: string;
575 + orgTable: string;
576 + name: string;
577 + orgName: string;
578 + charsetNr: number;
579 + length: number;
580 + type: Types;
581 + flags: number;
582 + decimals: number;
583 + default?: string;
584 + zeroFill: boolean;
585 + protocol41: boolean;
586 +}
1 +{
2 + "_from": "@types/mysql@^2.15.2",
3 + "_id": "@types/mysql@2.15.5",
4 + "_inBundle": false,
5 + "_integrity": "sha512-4QAISTUGZbcFh7bqdndo08xRdES5OTU+JODy8VCZbe1yiXyGjqw1H83G43XjQ3IbC10wn9xlGd44A5RXJwNh0Q==",
6 + "_location": "/@types/mysql",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "@types/mysql@^2.15.2",
12 + "name": "@types/mysql",
13 + "escapedName": "@types%2fmysql",
14 + "scope": "@types",
15 + "rawSpec": "^2.15.2",
16 + "saveSpec": null,
17 + "fetchSpec": "^2.15.2"
18 + },
19 + "_requiredBy": [
20 + "/promise-mysql"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/@types/mysql/-/mysql-2.15.5.tgz",
23 + "_shasum": "6d75afb5cc018c9d66b2f37a046924e397f85430",
24 + "_spec": "@types/mysql@^2.15.2",
25 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/promise-mysql",
26 + "bugs": {
27 + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
28 + },
29 + "bundleDependencies": false,
30 + "contributors": [
31 + {
32 + "name": "William Johnston",
33 + "url": "https://github.com/wjohnsto"
34 + },
35 + {
36 + "name": "Kacper Polak",
37 + "url": "https://github.com/kacepe"
38 + },
39 + {
40 + "name": "Krittanan Pingclasai",
41 + "url": "https://github.com/kpping"
42 + },
43 + {
44 + "name": "James Munro",
45 + "url": "https://github.com/jdmunro"
46 + }
47 + ],
48 + "dependencies": {
49 + "@types/node": "*"
50 + },
51 + "deprecated": false,
52 + "description": "TypeScript definitions for mysql",
53 + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
54 + "license": "MIT",
55 + "main": "",
56 + "name": "@types/mysql",
57 + "repository": {
58 + "type": "git",
59 + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
60 + },
61 + "scripts": {},
62 + "typeScriptVersion": "2.1",
63 + "typesPublisherContentHash": "5ab0640250fb34af9e11026236c9009f506a78be9ddd17745a348947c3766d6f",
64 + "version": "2.15.5"
65 +}
1 + MIT License
2 +
3 + Copyright (c) Microsoft Corporation. All rights reserved.
4 +
5 + Permission is hereby granted, free of charge, to any person obtaining a copy
6 + of this software and associated documentation files (the "Software"), to deal
7 + in the Software without restriction, including without limitation the rights
8 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 + copies of the Software, and to permit persons to whom the Software is
10 + furnished to do so, subject to the following conditions:
11 +
12 + The above copyright notice and this permission notice shall be included in all
13 + copies or substantial portions of the Software.
14 +
15 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 + SOFTWARE
1 +# Installation
2 +> `npm install --save @types/node`
3 +
4 +# Summary
5 +This package contains type definitions for Node.js (http://nodejs.org/).
6 +
7 +# Details
8 +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node
9 +
10 +Additional Details
11 + * Last updated: Thu, 13 Dec 2018 19:22:44 GMT
12 + * Dependencies: none
13 + * Global values: Buffer, NodeJS, SlowBuffer, Symbol, __dirname, __filename, clearImmediate, clearInterval, clearTimeout, console, exports, global, module, process, require, setImmediate, setInterval, setTimeout
14 +
15 +# Credits
16 +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>, Bruno Scheufler <https://github.com/brunoscheufler>, Chigozirim C. <https://github.com/smac89>, Christian Vaagland Tellnes <https://github.com/tellnes>, 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>.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
1 +{
2 + "_from": "@types/node@*",
3 + "_id": "@types/node@10.12.15",
4 + "_inBundle": false,
5 + "_integrity": "sha512-9kROxduaN98QghwwHmxXO2Xz3MaWf+I1sLVAA6KJDF5xix+IyXVhds0MAfdNwtcpSrzhaTsNB0/jnL86fgUhqA==",
6 + "_location": "/@types/node",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "@types/node@*",
12 + "name": "@types/node",
13 + "escapedName": "@types%2fnode",
14 + "scope": "@types",
15 + "rawSpec": "*",
16 + "saveSpec": null,
17 + "fetchSpec": "*"
18 + },
19 + "_requiredBy": [
20 + "/@types/mysql"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.15.tgz",
23 + "_shasum": "20e85651b62fd86656e57c9c9bc771ab1570bc59",
24 + "_spec": "@types/node@*",
25 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/@types/mysql",
26 + "bugs": {
27 + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
28 + },
29 + "bundleDependencies": false,
30 + "contributors": [
31 + {
32 + "name": "Microsoft TypeScript",
33 + "url": "https://github.com/Microsoft"
34 + },
35 + {
36 + "name": "DefinitelyTyped",
37 + "url": "https://github.com/DefinitelyTyped"
38 + },
39 + {
40 + "name": "Alberto Schiabel",
41 + "url": "https://github.com/jkomyno"
42 + },
43 + {
44 + "name": "Alexander T.",
45 + "url": "https://github.com/a-tarasyuk"
46 + },
47 + {
48 + "name": "Alvis HT Tang",
49 + "url": "https://github.com/alvis"
50 + },
51 + {
52 + "name": "Andrew Makarov",
53 + "url": "https://github.com/r3nya"
54 + },
55 + {
56 + "name": "Bruno Scheufler",
57 + "url": "https://github.com/brunoscheufler"
58 + },
59 + {
60 + "name": "Chigozirim C.",
61 + "url": "https://github.com/smac89"
62 + },
63 + {
64 + "name": "Christian Vaagland Tellnes",
65 + "url": "https://github.com/tellnes"
66 + },
67 + {
68 + "name": "Deividas Bakanas",
69 + "url": "https://github.com/DeividasBakanas"
70 + },
71 + {
72 + "name": "Eugene Y. Q. Shen",
73 + "url": "https://github.com/eyqs"
74 + },
75 + {
76 + "name": "Flarna",
77 + "url": "https://github.com/Flarna"
78 + },
79 + {
80 + "name": "Hannes Magnusson",
81 + "url": "https://github.com/Hannes-Magnusson-CK"
82 + },
83 + {
84 + "name": "Hoàng Văn Khải",
85 + "url": "https://github.com/KSXGitHub"
86 + },
87 + {
88 + "name": "Huw",
89 + "url": "https://github.com/hoo29"
90 + },
91 + {
92 + "name": "Kelvin Jin",
93 + "url": "https://github.com/kjin"
94 + },
95 + {
96 + "name": "Klaus Meinhardt",
97 + "url": "https://github.com/ajafff"
98 + },
99 + {
100 + "name": "Lishude",
101 + "url": "https://github.com/islishude"
102 + },
103 + {
104 + "name": "Mariusz Wiktorczyk",
105 + "url": "https://github.com/mwiktorczyk"
106 + },
107 + {
108 + "name": "Matthieu Sieben",
109 + "url": "https://github.com/matthieusieben"
110 + },
111 + {
112 + "name": "Mohsen Azimi",
113 + "url": "https://github.com/mohsen1"
114 + },
115 + {
116 + "name": "Nicolas Even",
117 + "url": "https://github.com/n-e"
118 + },
119 + {
120 + "name": "Nicolas Voigt",
121 + "url": "https://github.com/octo-sniffle"
122 + },
123 + {
124 + "name": "Parambir Singh",
125 + "url": "https://github.com/parambirs"
126 + },
127 + {
128 + "name": "Sebastian Silbermann",
129 + "url": "https://github.com/eps1lon"
130 + },
131 + {
132 + "name": "Simon Schick",
133 + "url": "https://github.com/SimonSchick"
134 + },
135 + {
136 + "name": "Thomas den Hollander",
137 + "url": "https://github.com/ThomasdenH"
138 + },
139 + {
140 + "name": "Wilco Bakker",
141 + "url": "https://github.com/WilcoBakker"
142 + },
143 + {
144 + "name": "wwwy3y3",
145 + "url": "https://github.com/wwwy3y3"
146 + },
147 + {
148 + "name": "Zane Hannan AU",
149 + "url": "https://github.com/ZaneHannanAU"
150 + },
151 + {
152 + "name": "Jeremie Rodriguez",
153 + "url": "https://github.com/jeremiergz"
154 + },
155 + {
156 + "name": "Samuel Ainsworth",
157 + "url": "https://github.com/samuela"
158 + }
159 + ],
160 + "dependencies": {},
161 + "deprecated": false,
162 + "description": "TypeScript definitions for Node.js",
163 + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
164 + "license": "MIT",
165 + "main": "",
166 + "name": "@types/node",
167 + "repository": {
168 + "type": "git",
169 + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
170 + },
171 + "scripts": {},
172 + "typeScriptVersion": "2.0",
173 + "types": "index",
174 + "typesPublisherContentHash": "3cb7c377b3501067ecca235d531f2eaf3e308568e8195e87dd75e5215e13e117",
175 + "version": "10.12.15"
176 +}
1 +The MIT Licence.
2 +
3 +Copyright (c) 2017 Michael Mclaughlin
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining
6 +a copy of this software and associated documentation files (the
7 +'Software'), to deal in the Software without restriction, including
8 +without limitation the rights to use, copy, modify, merge, publish,
9 +distribute, sublicense, and/or sell copies of the Software, and to
10 +permit persons to whom the Software is furnished to do so, subject to
11 +the following conditions:
12 +
13 +The above copyright notice and this permission notice shall be
14 +included in all copies or substantial portions of the Software.
15 +
16 +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
17 +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 +
1 +![bignumber.js](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/bignumberjs.png)
2 +
3 +A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic.
4 +
5 +[![Build Status](https://travis-ci.org/MikeMcl/bignumber.js.svg)](https://travis-ci.org/MikeMcl/bignumber.js)
6 +
7 +<br />
8 +
9 +## Features
10 +
11 + - Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal
12 + - 8 KB minified and gzipped
13 + - Simple API but full-featured
14 + - Works with numbers with or without fraction digits in bases from 2 to 64 inclusive
15 + - Replicates the `toExponential`, `toFixed`, `toPrecision` and `toString` methods of JavaScript's Number type
16 + - Includes a `toFraction` and a correctly-rounded `squareRoot` method
17 + - Supports cryptographically-secure pseudo-random number generation
18 + - No dependencies
19 + - Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only
20 + - Comprehensive [documentation](http://mikemcl.github.io/bignumber.js/) and test set
21 +
22 +![API](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/API.png)
23 +
24 +If a smaller and simpler library is required see [big.js](https://github.com/MikeMcl/big.js/).
25 +It's less than half the size but only works with decimal numbers and only has half the methods.
26 +It also does not allow `NaN` or `Infinity`, or have the configuration options of this library.
27 +
28 +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.
29 +
30 +## Load
31 +
32 +The library is the single JavaScript file *bignumber.js* (or minified, *bignumber.min.js*).
33 +
34 +```html
35 +<script src='relative/path/to/bignumber.js'></script>
36 +```
37 +
38 +For [Node.js](http://nodejs.org), the library is available from the [npm](https://npmjs.org/) registry
39 +
40 + $ npm install bignumber.js
41 +
42 +```javascript
43 +var BigNumber = require('bignumber.js');
44 +```
45 +
46 +To load with AMD loader libraries such as [requireJS](http://requirejs.org/):
47 +
48 +```javascript
49 +require(['path/to/bignumber'], function(BigNumber) {
50 + // Use BigNumber here in local scope. No global BigNumber.
51 +});
52 +```
53 +
54 +## Use
55 +
56 +*In all examples below, `var`, semicolons and `toString` calls are not shown.
57 +If a commented-out value is in quotes it means `toString` has been called on the preceding expression.*
58 +
59 +The library exports a single function: `BigNumber`, the constructor of BigNumber instances.
60 +
61 +It accepts a value of type number *(up to 15 significant digits only)*, string or BigNumber object,
62 +
63 +```javascript
64 +x = new BigNumber(123.4567)
65 +y = new BigNumber('123456.7e-3')
66 +z = new BigNumber(x)
67 +x.equals(y) && y.equals(z) && x.equals(z) // true
68 +```
69 +
70 +
71 +and a base from 2 to 64 inclusive can be specified.
72 +
73 +```javascript
74 +x = new BigNumber(1011, 2) // "11"
75 +y = new BigNumber('zz.9', 36) // "1295.25"
76 +z = x.plus(y) // "1306.25"
77 +```
78 +
79 +A BigNumber is immutable in the sense that it is not changed by its methods.
80 +
81 +```javascript
82 +0.3 - 0.1 // 0.19999999999999998
83 +x = new BigNumber(0.3)
84 +x.minus(0.1) // "0.2"
85 +x // "0.3"
86 +```
87 +
88 +The methods that return a BigNumber can be chained.
89 +
90 +```javascript
91 +x.dividedBy(y).plus(z).times(9).floor()
92 +x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').ceil()
93 +```
94 +
95 +Many method names have a shorter alias.
96 +
97 +```javascript
98 +x.squareRoot().dividedBy(y).toPower(3).equals(x.sqrt().div(y).pow(3)) // true
99 +x.cmp(y.mod(z).neg()) == 1 && x.comparedTo(y.modulo(z).negated()) == 1 // true
100 +```
101 +
102 +Like JavaScript's number type, there are `toExponential`, `toFixed` and `toPrecision` methods
103 +
104 +```javascript
105 +x = new BigNumber(255.5)
106 +x.toExponential(5) // "2.55500e+2"
107 +x.toFixed(5) // "255.50000"
108 +x.toPrecision(5) // "255.50"
109 +x.toNumber() // 255.5
110 +```
111 +
112 + and a base can be specified for `toString`.
113 +
114 + ```javascript
115 + x.toString(16) // "ff.8"
116 + ```
117 +
118 +There is also a `toFormat` method which may be useful for internationalisation
119 +
120 +```javascript
121 +y = new BigNumber('1234567.898765')
122 +y.toFormat(2) // "1,234,567.90"
123 +```
124 +
125 +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.
126 +
127 +The other arithmetic operations always give the exact result.
128 +
129 +```javascript
130 +BigNumber.config({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 })
131 +
132 +x = new BigNumber(2);
133 +y = new BigNumber(3);
134 +z = x.div(y) // "0.6666666667"
135 +z.sqrt() // "0.8164965809"
136 +z.pow(-3) // "3.3749999995"
137 +z.toString(2) // "0.1010101011"
138 +z.times(z) // "0.44444444448888888889"
139 +z.times(z).round(10) // "0.4444444445"
140 +```
141 +
142 +There is a `toFraction` method with an optional *maximum denominator* argument
143 +
144 +```javascript
145 +y = new BigNumber(355)
146 +pi = y.dividedBy(113) // "3.1415929204"
147 +pi.toFraction() // [ "7853982301", "2500000000" ]
148 +pi.toFraction(1000) // [ "355", "113" ]
149 +```
150 +
151 +and `isNaN` and `isFinite` methods, as `NaN` and `Infinity` are valid `BigNumber` values.
152 +
153 +```javascript
154 +x = new BigNumber(NaN) // "NaN"
155 +y = new BigNumber(Infinity) // "Infinity"
156 +x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true
157 +```
158 +
159 +The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign.
160 +
161 +
162 +```javascript
163 +x = new BigNumber(-123.456);
164 +x.c // [ 123, 45600000000000 ] coefficient (i.e. significand)
165 +x.e // 2 exponent
166 +x.s // -1 sign
167 +```
168 +
169 +
170 +Multiple BigNumber constructors can be created, each with their own independent configuration which applies to all BigNumber's created from it.
171 +
172 +```javascript
173 +// Set DECIMAL_PLACES for the original BigNumber constructor
174 +BigNumber.config({ DECIMAL_PLACES: 10 })
175 +
176 +// Create another BigNumber constructor, optionally passing in a configuration object
177 +BN = BigNumber.another({ DECIMAL_PLACES: 5 })
178 +
179 +x = new BigNumber(1)
180 +y = new BN(1)
181 +
182 +x.div(3) // '0.3333333333'
183 +y.div(3) // '0.33333'
184 +```
185 +
186 +For futher information see the [API](http://mikemcl.github.io/bignumber.js/) reference in the *doc* directory.
187 +
188 +## Test
189 +
190 +The *test* directory contains the test scripts for each method.
191 +
192 +The tests can be run with Node or a browser. For Node use
193 +
194 + $ npm test
195 +
196 +or
197 +
198 + $ node test/every-test
199 +
200 +To test a single method, e.g.
201 +
202 + $ node test/toFraction
203 +
204 +For the browser, see *every-test.html* and *single-test.html* in the *test/browser* directory.
205 +
206 +*bignumber-vs-number.html* enables some of the methods of bignumber.js to be compared with those of JavaScript's number type.
207 +
208 +## Versions
209 +
210 +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.
211 +
212 +## Performance
213 +
214 +See the [README](https://github.com/MikeMcl/bignumber.js/tree/master/perf) in the *perf* directory.
215 +
216 +## Build
217 +
218 +For Node, if [uglify-js](https://github.com/mishoo/UglifyJS2) is installed
219 +
220 + npm install uglify-js -g
221 +
222 +then
223 +
224 + npm run build
225 +
226 +will create *bignumber.min.js*.
227 +
228 +A source map will also be created in the root directory.
229 +
230 +## Feedback
231 +
232 +Open an issue, or email
233 +
234 +Michael
235 +
236 +<a href="mailto:M8ch88l@gmail.com">M8ch88l@gmail.com</a>
237 +
238 +## Licence
239 +
240 +MIT.
241 +
242 +See [LICENCE](https://github.com/MikeMcl/bignumber.js/blob/master/LICENCE).
243 +
244 +## Change Log
245 +
246 +
247 +#### 4.1.0
248 +* 26/09/2017
249 +* Remove node 0.6 from *.travis.yml*.
250 +* Add *bignumber.mjs*.
251 +
252 +#### 4.0.4
253 +* 03/09/2017
254 +* Add missing aliases to *bignumber.d.ts*.
255 +
256 +#### 4.0.3
257 +* 30/08/2017
258 +* Add types: *bignumber.d.ts*.
259 +
260 +#### 4.0.2
261 +* 03/05/2017
262 +* #120 Workaround Safari/Webkit bug.
263 +
264 +#### 4.0.1
265 +* 05/04/2017
266 +* #121 BigNumber.default to BigNumber['default'].
267 +
268 +#### 4.0.0
269 +* 09/01/2017
270 +* Replace BigNumber.isBigNumber method with isBigNumber prototype property.
271 +
272 +#### 3.1.2
273 +* 08/01/2017
274 +* Minor documentation edit.
275 +
276 +#### 3.1.1
277 +* 08/01/2017
278 +* Uncomment `isBigNumber` tests.
279 +* Ignore dot files.
280 +
281 +#### 3.1.0
282 +* 08/01/2017
283 +* Add `isBigNumber` method.
284 +
285 +#### 3.0.2
286 +* 08/01/2017
287 +* Bugfix: Possible incorrect value of `ERRORS` after a `BigNumber.another` call (due to `parseNumeric` declaration in outer scope).
288 +
289 +#### 3.0.1
290 +* 23/11/2016
291 +* Apply fix for old ipads with `%` issue, see #57 and #102.
292 +* Correct error message.
293 +
294 +#### 3.0.0
295 +* 09/11/2016
296 +* Remove `require('crypto')` - leave it to the user.
297 +* Add `BigNumber.set` as `BigNumber.config` alias.
298 +* Default `POW_PRECISION` to `0`.
299 +
300 +#### 2.4.0
301 +* 14/07/2016
302 +* #97 Add exports to support ES6 imports.
303 +
304 +#### 2.3.0
305 +* 07/03/2016
306 +* #86 Add modulus parameter to `toPower`.
307 +
308 +#### 2.2.0
309 +* 03/03/2016
310 +* #91 Permit larger JS integers.
311 +
312 +#### 2.1.4
313 +* 15/12/2015
314 +* Correct UMD.
315 +
316 +#### 2.1.3
317 +* 13/12/2015
318 +* Refactor re global object and crypto availability when bundling.
319 +
320 +#### 2.1.2
321 +* 10/12/2015
322 +* Bugfix: `window.crypto` not assigned to `crypto`.
323 +
324 +#### 2.1.1
325 +* 09/12/2015
326 +* Prevent code bundler from adding `crypto` shim.
327 +
328 +#### 2.1.0
329 +* 26/10/2015
330 +* For `valueOf` and `toJSON`, include the minus sign with negative zero.
331 +
332 +#### 2.0.8
333 +* 2/10/2015
334 +* Internal round function bugfix.
335 +
336 +#### 2.0.6
337 +* 31/03/2015
338 +* Add bower.json. Tweak division after in-depth review.
339 +
340 +#### 2.0.5
341 +* 25/03/2015
342 +* Amend README. Remove bitcoin address.
343 +
344 +#### 2.0.4
345 +* 25/03/2015
346 +* Critical bugfix #58: division.
347 +
348 +#### 2.0.3
349 +* 18/02/2015
350 +* Amend README. Add source map.
351 +
352 +#### 2.0.2
353 +* 18/02/2015
354 +* Correct links.
355 +
356 +#### 2.0.1
357 +* 18/02/2015
358 +* Add `max`, `min`, `precision`, `random`, `shift`, `toDigits` and `truncated` methods.
359 +* Add the short-forms: `add`, `mul`, `sd`, `sub` and `trunc`.
360 +* Add an `another` method to enable multiple independent constructors to be created.
361 +* Add support for the base 2, 8 and 16 prefixes `0b`, `0o` and `0x`.
362 +* Enable a rounding mode to be specified as a second parameter to `toExponential`, `toFixed`, `toFormat` and `toPrecision`.
363 +* Add a `CRYPTO` configuration property so cryptographically-secure pseudo-random number generation can be specified.
364 +* Add a `MODULO_MODE` configuration property to enable the rounding mode used by the `modulo` operation to be specified.
365 +* Add a `POW_PRECISION` configuration property to enable the number of significant digits calculated by the power operation to be limited.
366 +* Improve code quality.
367 +* Improve documentation.
368 +
369 +#### 2.0.0
370 +* 29/12/2014
371 +* Add `dividedToIntegerBy`, `isInteger` and `toFormat` methods.
372 +* Remove the following short-forms: `isF`, `isZ`, `toE`, `toF`, `toFr`, `toN`, `toP`, `toS`.
373 +* Store a BigNumber's coefficient in base 1e14, rather than base 10.
374 +* Add fast path for integers to BigNumber constructor.
375 +* Incorporate the library into the online documentation.
376 +
377 +#### 1.5.0
378 +* 13/11/2014
379 +* Add `toJSON` and `decimalPlaces` methods.
380 +
381 +#### 1.4.1
382 +* 08/06/2014
383 +* Amend README.
384 +
385 +#### 1.4.0
386 +* 08/05/2014
387 +* Add `toNumber`.
388 +
389 +#### 1.3.0
390 +* 08/11/2013
391 +* Ensure correct rounding of `sqrt` in all, rather than almost all, cases.
392 +* Maximum radix to 64.
393 +
394 +#### 1.2.1
395 +* 17/10/2013
396 +* Sign of zero when x < 0 and x + (-x) = 0.
397 +
398 +#### 1.2.0
399 +* 19/9/2013
400 +* Throw Error objects for stack.
401 +
402 +#### 1.1.1
403 +* 22/8/2013
404 +* Show original value in constructor error message.
405 +
406 +#### 1.1.0
407 +* 1/8/2013
408 +* Allow numbers with trailing radix point.
409 +
410 +#### 1.0.1
411 +* Bugfix: error messages with incorrect method name
412 +
413 +#### 1.0.0
414 +* 8/11/2012
415 +* Initial release
1 +// Type definitions for Bignumber.js
2 +// Project: bignumber.js
3 +// Definitions by: Felix Becker https://github.com/felixfbecker
4 +
5 +export interface Format {
6 + /** the decimal separator */
7 + decimalSeparator?: string;
8 + /** the grouping separator of the integer part */
9 + groupSeparator?: string;
10 + /** the primary grouping size of the integer part */
11 + groupSize?: number;
12 + /** the secondary grouping size of the integer part */
13 + secondaryGroupSize?: number;
14 + /** the grouping separator of the fraction part */
15 + fractionGroupSeparator?: string;
16 + /** the grouping size of the fraction part */
17 + fractionGroupSize?: number;
18 +}
19 +
20 +export interface Configuration {
21 +
22 + /**
23 + * integer, `0` to `1e+9` inclusive
24 + *
25 + * The maximum number of decimal places of the results of operations involving division, i.e. division, square root
26 + * and base conversion operations, and power operations with negative exponents.
27 + *
28 + * ```ts
29 + * BigNumber.config({ DECIMAL_PLACES: 5 })
30 + * BigNumber.config(5) // equivalent
31 + * ```
32 + * @default 20
33 + */
34 + DECIMAL_PLACES?: number;
35 +
36 + /**
37 + * The rounding mode used in the above operations and the default rounding mode of round, toExponential, toFixed,
38 + * toFormat and toPrecision. The modes are available as enumerated properties of the BigNumber constructor.
39 + * @default [[RoundingMode.ROUND_HALF_UP]]
40 + */
41 + ROUNDING_MODE?: RoundingMode;
42 +
43 + /**
44 + * - `number`: integer, magnitude `0` to `1e+9` inclusive
45 + * - `number[]`: [ integer `-1e+9` to `0` inclusive, integer `0` to `1e+9` inclusive ]
46 + *
47 + * The exponent value(s) at which `toString` returns exponential notation.
48 + *
49 + * If a single number is assigned, the value
50 + * is the exponent magnitude.
51 + *
52 + * If an array of two numbers is assigned then the first number is the negative exponent
53 + * value at and beneath which exponential notation is used, and the second number is the positive exponent value at
54 + * and above which the same.
55 + *
56 + * For example, to emulate JavaScript numbers in terms of the exponent values at which
57 + * they begin to use exponential notation, use [-7, 20].
58 + *
59 + * ```ts
60 + * BigNumber.config({ EXPONENTIAL_AT: 2 })
61 + * new BigNumber(12.3) // '12.3' e is only 1
62 + * new BigNumber(123) // '1.23e+2'
63 + * new BigNumber(0.123) // '0.123' e is only -1
64 + * new BigNumber(0.0123) // '1.23e-2'
65 + *
66 + * BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
67 + * new BigNumber(123456789) // '123456789' e is only 8
68 + * new BigNumber(0.000000123) // '1.23e-7'
69 + *
70 + * // Almost never return exponential notation:
71 + * BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
72 + *
73 + * // Always return exponential notation:
74 + * BigNumber.config({ EXPONENTIAL_AT: 0 })
75 + * ```
76 + * Regardless of the value of `EXPONENTIAL_AT`, the `toFixed` method will always return a value in normal notation
77 + * and the `toExponential` method will always return a value in exponential form.
78 + *
79 + * Calling `toString` with a base argument, e.g. `toString(10)`, will also always return normal notation.
80 + *
81 + * @default `[-7, 20]`
82 + */
83 + EXPONENTIAL_AT?: number | [number, number];
84 +
85 + /**
86 + * - number: integer, magnitude `1` to `1e+9` inclusive
87 + * - number[]: [ integer `-1e+9` to `-1` inclusive, integer `1` to `1e+9` inclusive ]
88 + *
89 + * The exponent value(s) beyond which overflow to `Infinity` and underflow to zero occurs.
90 + *
91 + * If a single number is
92 + * assigned, it is the maximum exponent magnitude: values wth a positive exponent of greater magnitude become
93 + * Infinity and those with a negative exponent of greater magnitude become zero.
94 + *
95 + * If an array of two numbers is
96 + * assigned then the first number is the negative exponent limit and the second number is the positive exponent
97 + * limit.
98 + *
99 + * For example, to emulate JavaScript numbers in terms of the exponent values at which they become zero and
100 + * Infinity, use [-324, 308].
101 + *
102 + * ```ts
103 + * BigNumber.config({ RANGE: 500 })
104 + * BigNumber.config().RANGE // [ -500, 500 ]
105 + * new BigNumber('9.999e499') // '9.999e+499'
106 + * new BigNumber('1e500') // 'Infinity'
107 + * new BigNumber('1e-499') // '1e-499'
108 + * new BigNumber('1e-500') // '0'
109 + * BigNumber.config({ RANGE: [-3, 4] })
110 + * new BigNumber(99999) // '99999' e is only 4
111 + * new BigNumber(100000) // 'Infinity' e is 5
112 + * new BigNumber(0.001) // '0.01' e is only -3
113 + * new BigNumber(0.0001) // '0' e is -4
114 + * ```
115 + *
116 + * The largest possible magnitude of a finite BigNumber is `9.999...e+1000000000`.
117 + *
118 + * The smallest possible magnitude of a non-zero BigNumber is `1e-1000000000`.
119 + *
120 + * @default `[-1e+9, 1e+9]`
121 + */
122 + RANGE?: number | [number, number];
123 +
124 + /**
125 + *
126 + * The value that determines whether BigNumber Errors are thrown. If ERRORS is false, no errors will be thrown.
127 + * `true`, `false`, `0` or `1`.
128 + * ```ts
129 + * BigNumber.config({ ERRORS: false })
130 + * ```
131 + *
132 + * @default `true`
133 + */
134 + ERRORS?: boolean | number;
135 +
136 + /**
137 + * `true`, `false`, `0` or `1`.
138 + *
139 + * The value that determines whether cryptographically-secure pseudo-random number generation is used.
140 + *
141 + * If `CRYPTO` is set to `true` then the random method will generate random digits using `crypto.getRandomValues` in
142 + * browsers that support it, or `crypto.randomBytes` if using a version of Node.js that supports it.
143 + *
144 + * If neither function is supported by the host environment then attempting to set `CRYPTO` to `true` will fail, and
145 + * if [[Configuration.ERRORS]] is `true` an exception will be thrown.
146 + *
147 + * If `CRYPTO` is `false` then the source of randomness used will be `Math.random` (which is assumed to generate at
148 + * least 30 bits of randomness).
149 + *
150 + * See [[BigNumber.random]].
151 + *
152 + * ```ts
153 + * BigNumber.config({ CRYPTO: true })
154 + * BigNumber.config().CRYPTO // true
155 + * BigNumber.random() // 0.54340758610486147524
156 + * ```
157 + *
158 + * @default `false`
159 + */
160 + CRYPTO?: boolean | number;
161 +
162 + /**
163 + * The modulo mode used when calculating the modulus: `a mod n`.
164 + *
165 + * The quotient, `q = a / n`, is calculated according to
166 + * the [[Configuration.ROUNDING_MODE]] that corresponds to the chosen MODULO_MODE.
167 + *
168 + * The remainder, r, is calculated as: `r = a - n * q`.
169 + *
170 + * The modes that are most commonly used for the modulus/remainder operation are shown in the following table.
171 + * Although the other rounding modes can be used, they may not give useful results.
172 + *
173 + * Property | Value | Description
174 + * -------------------|:-----:|---------------------------------------------------------------------------------------
175 + * `ROUND_UP` | 0 | The remainder is positive if the dividend is negative, otherwise it is negative.
176 + * `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 `%`.
177 + * `ROUND_FLOOR` | 3 | The remainder has the same sign as the divisor.
178 + * | | This matches Python's % operator.
179 + * `ROUND_HALF_EVEN` | 6 | The IEEE 754 remainder function.
180 + * `EUCLID` | 9 | The remainder is always positive. Euclidian division: `q = sign(n) * floor(a / abs(n))`
181 + *
182 + * The rounding/modulo modes are available as enumerated properties of the BigNumber constructor.
183 + *
184 + * See [[BigNumber.modulo]]
185 + *
186 + * ```ts
187 + * BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
188 + * BigNumber.config({ MODULO_MODE: 9 }) // equivalent
189 + * ```
190 + *
191 + * @default [[RoundingMode.ROUND_DOWN]]
192 + */
193 + MODULO_MODE?: RoundingMode;
194 +
195 + /**
196 + * integer, `0` to `1e+9` inclusive.
197 + *
198 + * The maximum number of significant digits of the result of the power operation (unless a modulus is specified).
199 + *
200 + * If set to 0, the number of signifcant digits will not be limited.
201 + *
202 + * See [[BigNumber.toPower]]
203 + *
204 + * ```ts
205 + * BigNumber.config({ POW_PRECISION: 100 })
206 + * ```
207 + *
208 + * @default 100
209 + */
210 + POW_PRECISION?: number;
211 +
212 + /**
213 + * The FORMAT object configures the format of the string returned by the `toFormat` method. The example below shows
214 + * the properties of the FORMAT object that are recognised, and their default values. Unlike the other configuration
215 + * properties, the values of the properties of the FORMAT object will not be checked for validity. The existing
216 + * FORMAT object will simply be replaced by the object that is passed in. Note that all the properties shown below
217 + * do not have to be included.
218 + *
219 + * See `toFormat` for examples of usage.
220 + *
221 + * ```ts
222 + * BigNumber.config({
223 + * FORMAT: {
224 + * // the decimal separator
225 + * decimalSeparator: '.',
226 + * // the grouping separator of the integer part
227 + * groupSeparator: ',',
228 + * // the primary grouping size of the integer part
229 + * groupSize: 3,
230 + * // the secondary grouping size of the integer part
231 + * secondaryGroupSize: 0,
232 + * // the grouping separator of the fraction part
233 + * fractionGroupSeparator: ' ',
234 + * // the grouping size of the fraction part
235 + * fractionGroupSize: 0
236 + * }
237 + * });
238 + * ```
239 + */
240 + FORMAT?: Format;
241 +}
242 +
243 +/**
244 + * The library's enumerated rounding modes are stored as properties of the constructor.
245 + * (They are not referenced internally by the library itself.)
246 + * Rounding modes 0 to 6 (inclusive) are the same as those of Java's BigDecimal class.
247 + */
248 +declare enum RoundingMode {
249 + /** Rounds away from zero */
250 + ROUND_UP = 0,
251 + /** Rounds towards zero */
252 + ROUND_DOWN = 1,
253 + /** Rounds towards Infinity */
254 + ROUND_CEIL = 2,
255 + /** Rounds towards -Infinity */
256 + ROUND_FLOOR = 3,
257 + /**
258 + * Rounds towards nearest neighbour. If equidistant, rounds away from zero
259 + */
260 + ROUND_HALF_UP = 4,
261 + /**
262 + * Rounds towards nearest neighbour. If equidistant, rounds towards zero
263 + */
264 + ROUND_HALF_DOWN = 5,
265 + /**
266 + * Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour
267 + */
268 + ROUND_HALF_EVEN = 6,
269 + /**
270 + * Rounds towards nearest neighbour. If equidistant, rounds towards `Infinity`
271 + */
272 + ROUND_HALF_CEIL = 7,
273 + /**
274 + * Rounds towards nearest neighbour. If equidistant, rounds towards `-Infinity`
275 + */
276 + ROUND_HALF_FLOOR = 8,
277 + /**
278 + * The remainder is always positive. Euclidian division: `q = sign(n) * floor(a / abs(n))`
279 + */
280 + EUCLID = 9
281 +}
282 +
283 +export class BigNumber {
284 +
285 + /** Rounds away from zero */
286 + static ROUND_UP: RoundingMode;
287 +
288 + /** Rounds towards zero */
289 + static ROUND_DOWN: RoundingMode;
290 +
291 + /** Rounds towards Infinity */
292 + static ROUND_CEIL: RoundingMode;
293 +
294 + /** Rounds towards -Infinity */
295 + static ROUND_FLOOR: RoundingMode;
296 +
297 + /**
298 + * Rounds towards nearest neighbour. If equidistant, rounds away from zero
299 + */
300 + static ROUND_HALF_UP: RoundingMode;
301 +
302 + /**
303 + * Rounds towards nearest neighbour. If equidistant, rounds towards zero
304 + */
305 + static ROUND_HALF_DOWN: RoundingMode;
306 +
307 + /**
308 + * Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour
309 + */
310 + static ROUND_HALF_EVEN: RoundingMode;
311 +
312 + /**
313 + * Rounds towards nearest neighbour. If equidistant, rounds towards `Infinity`
314 + */
315 + static ROUND_HALF_CEIL: RoundingMode;
316 +
317 + /**
318 + * Rounds towards nearest neighbour. If equidistant, rounds towards `-Infinity`
319 + */
320 + static ROUND_HALF_FLOOR: RoundingMode;
321 +
322 + /**
323 + * The remainder is always positive. Euclidian division: `q = sign(n) * floor(a / abs(n))`
324 + */
325 + static EUCLID: RoundingMode;
326 +
327 + /**
328 + * Returns a new independent BigNumber constructor with configuration as described by `obj` (see `config`), or with
329 + * the default configuration if `obj` is `null` or `undefined`.
330 + *
331 + * ```ts
332 + * BigNumber.config({ DECIMAL_PLACES: 5 })
333 + * BN = BigNumber.another({ DECIMAL_PLACES: 9 })
334 + *
335 + * x = new BigNumber(1)
336 + * y = new BN(1)
337 + *
338 + * x.div(3) // 0.33333
339 + * y.div(3) // 0.333333333
340 + *
341 + * // BN = BigNumber.another({ DECIMAL_PLACES: 9 }) is equivalent to:
342 + * BN = BigNumber.another()
343 + * BN.config({ DECIMAL_PLACES: 9 })
344 + * ```
345 + */
346 + static another(config?: Configuration): typeof BigNumber;
347 +
348 + /**
349 + * Configures the 'global' settings for this particular BigNumber constructor. Returns an object with the above
350 + * properties and their current values. If the value to be assigned to any of the above properties is `null` or
351 + * `undefined` it is ignored. See Errors for the treatment of invalid values.
352 + */
353 + static config(config?: Configuration): Configuration;
354 +
355 + /**
356 + * Configures the 'global' settings for this particular BigNumber constructor. Returns an object with the above
357 + * properties and their current values. If the value to be assigned to any of the above properties is `null` or
358 + * `undefined` it is ignored. See Errors for the treatment of invalid values.
359 + */
360 + static config(
361 + decimalPlaces?: number,
362 + roundingMode?: RoundingMode,
363 + exponentialAt?: number | [number, number],
364 + range?: number | [number, number],
365 + errors?: boolean | number,
366 + crypto?: boolean | number,
367 + moduloMode?: RoundingMode,
368 + powPrecision?: number,
369 + format?: Format
370 + ): Configuration;
371 +
372 + /**
373 + * Returns a BigNumber whose value is the maximum of `arg1`, `arg2`,... . The argument to this method can also be an
374 + * array of values. The return value is always exact and unrounded.
375 + *
376 + * ```ts
377 + * x = new BigNumber('3257869345.0378653')
378 + * BigNumber.max(4e9, x, '123456789.9') // '4000000000'
379 + *
380 + * arr = [12, '13', new BigNumber(14)]
381 + * BigNumber.max(arr) // '14'
382 + * ```
383 + */
384 + static max(...args: Array<number | string | BigNumber>): BigNumber;
385 + static max(args: Array<number | string | BigNumber>): BigNumber;
386 +
387 + /**
388 + * See BigNumber for further parameter details. Returns a BigNumber whose value is the minimum of arg1, arg2,... .
389 + * The argument to this method can also be an array of values. The return value is always exact and unrounded.
390 + *
391 + * ```ts
392 + * x = new BigNumber('3257869345.0378653')
393 + * BigNumber.min(4e9, x, '123456789.9') // '123456789.9'
394 + *
395 + * arr = [2, new BigNumber(-14), '-15.9999', -12]
396 + * BigNumber.min(arr) // '-15.9999'
397 + * ```
398 + */
399 + static min(...args: Array<number | string | BigNumber>): BigNumber;
400 + static min(args: Array<number | string | BigNumber>): BigNumber;
401 +
402 + /**
403 + * Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and less than 1.
404 + *
405 + * The return value
406 + * will have dp decimal places (or less if trailing zeros are produced). If dp is omitted then the number of decimal
407 + * places will default to the current `DECIMAL_PLACES` setting.
408 + *
409 + * Depending on the value of this BigNumber constructor's
410 + * `CRYPTO` setting and the support for the crypto object in the host environment, the random digits of the return
411 + * value are generated by either `Math.random` (fastest), `crypto.getRandomValues` (Web Cryptography API in recent
412 + * browsers) or `crypto.randomBytes` (Node.js).
413 + *
414 + * If `CRYPTO` is true, i.e. one of the crypto methods is to be used, the
415 + * value of a returned BigNumber should be cryptographically-secure and statistically indistinguishable from a
416 + * random value.
417 + *
418 + * ```ts
419 + * BigNumber.config({ DECIMAL_PLACES: 10 })
420 + * BigNumber.random() // '0.4117936847'
421 + * BigNumber.random(20) // '0.78193327636914089009'
422 + * ```
423 + *
424 + * @param dp integer, `0` to `1e+9` inclusive
425 + */
426 + static random(dp?: number): BigNumber;
427 +
428 + /**
429 + * Coefficient: Array of base `1e14` numbers or `null`
430 + * @readonly
431 + */
432 + c: number[];
433 +
434 + /**
435 + * Exponent: Integer, `-1000000000` to `1000000000` inclusive or `null`
436 + * @readonly
437 + */
438 + e: number;
439 +
440 + /**
441 + * Sign: `-1`, `1` or `null`
442 + * @readonly
443 + */
444 + s: number;
445 +
446 + /**
447 + * Returns a new instance of a BigNumber object. If a base is specified, the value is rounded according to the
448 + * current [[Configuration.DECIMAL_PLACES]] and [[Configuration.ROUNDING_MODE]] configuration. See Errors for the treatment of an invalid value or base.
449 + *
450 + * ```ts
451 + * x = new BigNumber(9) // '9'
452 + * y = new BigNumber(x) // '9'
453 + *
454 + * // 'new' is optional if ERRORS is false
455 + * BigNumber(435.345) // '435.345'
456 + *
457 + * new BigNumber('5032485723458348569331745.33434346346912144534543')
458 + * new BigNumber('4.321e+4') // '43210'
459 + * new BigNumber('-735.0918e-430') // '-7.350918e-428'
460 + * new BigNumber(Infinity) // 'Infinity'
461 + * new BigNumber(NaN) // 'NaN'
462 + * new BigNumber('.5') // '0.5'
463 + * new BigNumber('+2') // '2'
464 + * new BigNumber(-10110100.1, 2) // '-180.5'
465 + * new BigNumber(-0b10110100.1) // '-180.5'
466 + * new BigNumber('123412421.234324', 5) // '607236.557696'
467 + * new BigNumber('ff.8', 16) // '255.5'
468 + * new BigNumber('0xff.8') // '255.5'
469 + * ```
470 + *
471 + * The following throws `not a base 2 number` if [[Configuration.ERRORS]] is true, otherwise it returns a BigNumber with value `NaN`.
472 + *
473 + * ```ts
474 + * new BigNumber(9, 2)
475 + * ```
476 + *
477 + * The following throws `number type has more than 15 significant digits` if [[Configuration.ERRORS]] is true, otherwise it returns a BigNumber with value `96517860459076820`.
478 + *
479 + * ```ts
480 + * new BigNumber(96517860459076817.4395)
481 + * ```
482 + *
483 + * The following throws `not a number` if [[Configuration.ERRORS]] is true, otherwise it returns a BigNumber with value `NaN`.
484 + *
485 + * ```ts
486 + * new BigNumber('blurgh')
487 + * ```
488 + *
489 + * A value is only rounded by the constructor if a base is specified.
490 + *
491 + * ```ts
492 + * BigNumber.config({ DECIMAL_PLACES: 5 })
493 + * new BigNumber(1.23456789) // '1.23456789'
494 + * new BigNumber(1.23456789, 10) // '1.23457'
495 + * ```
496 + *
497 + * @param value A numeric value.
498 + *
499 + * Legitimate values include `±0`, `±Infinity` and `NaN`.
500 + *
501 + * Values of type `number` with more than 15 significant digits are considered invalid (if [[Configuration.ERRORS]]
502 + * is `true`) as calling `toString` or `valueOf` on such numbers may not result in the intended value.
503 + *
504 + * There is no limit to the number of digits of a value of type `string` (other than that of JavaScript's maximum
505 + * array size).
506 + *
507 + * Decimal string values may be in exponential, as well as normal (fixed-point) notation. Non-decimal values must be
508 + * in normal notation. String values in hexadecimal literal form, e.g. `'0xff'`, are valid, as are string values
509 + * with the octal and binary prefixs `'0o'` and `'0b'`.
510 + *
511 + * String values in octal literal form without the prefix will be interpreted as decimals, e.g. `'011'` is
512 + * interpreted as 11, not 9.
513 + *
514 + * Values in any base may have fraction digits.
515 + *
516 + * For bases from 10 to 36, lower and/or upper case letters can be used to represent values from 10 to 35.
517 + *
518 + * For bases above 36, a-z represents values from 10 to 35, A-Z from 36 to 61, and $ and _ represent 62 and 63
519 + * respectively (this can be changed by editing the ALPHABET variable near the top of the source file).
520 + *
521 + * @param base integer, 2 to 64 inclusive
522 + *
523 + * The base of value. If base is omitted, or is `null` or `undefined`, base 10 is assumed.
524 + */
525 + constructor(value: number | string | BigNumber, base?: number);
526 +
527 + /**
528 + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this BigNumber. The
529 + * return value is always exact and unrounded.
530 + * ```ts
531 + * x = new BigNumber(-0.8)
532 + * y = x.absoluteValue() // '0.8'
533 + * z = y.abs() // '0.8'
534 + * ```
535 + * @alias [[BigNumber.abs]]
536 + */
537 + absoluteValue(): BigNumber;
538 +
539 + /**
540 + * See [[BigNumber.absoluteValue]]
541 + */
542 + abs(): BigNumber;
543 +
544 + /**
545 + * See [[plus]]
546 + */
547 + add(n: number | string | BigNumber, base?: number): BigNumber;
548 +
549 + /**
550 + * Returns a BigNumber whose value is the value of this BigNumber rounded to a whole number in the direction of
551 + * positive `Infinity`.
552 + *
553 + * ```ts
554 + * x = new BigNumber(1.3)
555 + * x.ceil() // '2'
556 + * y = new BigNumber(-1.8)
557 + * y.ceil() // '-1'
558 + * ```
559 + */
560 + ceil(): BigNumber;
561 +
562 + /**
563 + * Returns | |
564 + * :-------:|---------------------------------------------------------------|
565 + * 1 | If the value of this BigNumber is greater than the value of n
566 + * -1 | If the value of this BigNumber is less than the value of n
567 + * 0 | If this BigNumber and n have the same value
568 + * null | If the value of either this BigNumber or n is NaN
569 + *
570 + * ```ts
571 + * x = new BigNumber(Infinity)
572 + * y = new BigNumber(5)
573 + * x.comparedTo(y) // 1
574 + * x.comparedTo(x.minus(1)) // 0
575 + * y.cmp(NaN) // null
576 + * y.cmp('110', 2) // -1
577 + * ```
578 + *
579 + * @alias [[cmp]]
580 + */
581 + comparedTo(n: number | string | BigNumber, base?: number): number;
582 +
583 + /**
584 + * See [[comparedTo]]
585 + */
586 + cmp(n: number | string | BigNumber, base?: number): number;
587 +
588 + /**
589 + * Return the number of decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is
590 + * `±Infinity` or `NaN`.
591 + *
592 + * ```ts
593 + * x = new BigNumber(123.45)
594 + * x.decimalPlaces() // 2
595 + * y = new BigNumber('9.9e-101')
596 + * y.dp() // 102
597 + * ```
598 + *
599 + * @alias [[dp]]
600 + */
601 + decimalPlaces(): number;
602 +
603 + /**
604 + * See [[decimalPlaces]]
605 + */
606 + dp(): number;
607 +
608 + /**
609 + * Returns a BigNumber whose value is the value of this BigNumber divided by n, rounded according to the current
610 + * DECIMAL_PLACES and ROUNDING_MODE configuration.
611 + *
612 + * ```ts
613 + * x = new BigNumber(355)
614 + * y = new BigNumber(113)
615 + * x.dividedBy(y) // '3.14159292035398230088'
616 + * x.div(5) // '71'
617 + * x.div(47, 16) // '5'
618 + * ```
619 + *
620 + * @alias [[div]]
621 + */
622 + dividedBy(n: number | string | BigNumber, base?: number): BigNumber;
623 +
624 + /**
625 + * See [[dividedBy]]
626 + */
627 + div(n: number | string | BigNumber, base?: number): BigNumber;
628 +
629 + /**
630 + * Return a BigNumber whose value is the integer part of dividing the value of this BigNumber by n.
631 + *
632 + * ```ts
633 + * x = new BigNumber(5)
634 + * y = new BigNumber(3)
635 + * x.dividedToIntegerBy(y) // '1'
636 + * x.divToInt(0.7) // '7'
637 + * x.divToInt('0.f', 16) // '5'
638 + * ```
639 + *
640 + * @alias [[divToInt]]
641 + */
642 + dividedToIntegerBy(n: number | string | BigNumber, base?: number): BigNumber;
643 +
644 + /**
645 + * See [[dividedToIntegerBy]]
646 + */
647 + divToInt(n: number | string | BigNumber, base?: number): BigNumber;
648 +
649 + /**
650 + * Returns true if the value of this BigNumber equals the value of `n`, otherwise returns `false`. As with JavaScript,
651 + * `NaN` does not equal `NaN`.
652 + *
653 + * Note: This method uses the [[comparedTo]] internally.
654 + *
655 + * ```ts
656 + * 0 === 1e-324 // true
657 + * x = new BigNumber(0)
658 + * x.equals('1e-324') // false
659 + * BigNumber(-0).eq(x) // true ( -0 === 0 )
660 + * BigNumber(255).eq('ff', 16) // true
661 + *
662 + * y = new BigNumber(NaN)
663 + * y.equals(NaN) // false
664 + * ```
665 + *
666 + * @alias [[eq]]
667 + */
668 + equals(n: number | string | BigNumber, base?: number): boolean;
669 +
670 + /**
671 + * See [[equals]]
672 + */
673 + eq(n: number | string | BigNumber, base?: number): boolean;
674 +
675 + /**
676 + * Returns a BigNumber whose value is the value of this BigNumber rounded to a whole number in the direction of
677 + * negative `Infinity`.
678 + *
679 + * ```ts
680 + * x = new BigNumber(1.8)
681 + * x.floor() // '1'
682 + * y = new BigNumber(-1.3)
683 + * y.floor() // '-2'
684 + * ```
685 + */
686 + floor(): BigNumber;
687 +
688 + /**
689 + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise returns `false`.
690 + *
691 + * Note: This method uses the comparedTo method internally.
692 + *
693 + * ```ts
694 + * 0.1 > (0.3 - 0.2) // true
695 + * x = new BigNumber(0.1)
696 + * x.greaterThan(BigNumber(0.3).minus(0.2)) // false
697 + * BigNumber(0).gt(x) // false
698 + * BigNumber(11, 3).gt(11.1, 2) // true
699 + * ```
700 + *
701 + * @alias [[gt]]
702 + */
703 + greaterThan(n: number | string | BigNumber, base?: number): boolean;
704 +
705 + /**
706 + * See [[greaterThan]]
707 + */
708 + gt(n: number | string | BigNumber, base?: number): boolean;
709 +
710 + /**
711 + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, otherwise returns `false`.
712 + *
713 + * Note: This method uses the comparedTo method internally.
714 + *
715 + * @alias [[gte]]
716 + */
717 + greaterThanOrEqualTo(n: number | string | BigNumber, base?: number): boolean;
718 +
719 + /**
720 + * See [[greaterThanOrEqualTo]]
721 + */
722 + gte(n: number | string | BigNumber, base?: number): boolean;
723 +
724 + /**
725 + * Returns true if the value of this BigNumber is a finite number, otherwise returns false. The only possible
726 + * non-finite values of a BigNumber are `NaN`, `Infinity` and `-Infinity`.
727 + *
728 + * Note: The native method `isFinite()` can be used if `n <= Number.MAX_VALUE`.
729 + */
730 + isFinite(): boolean;
731 +
732 + /**
733 + * Returns true if the value of this BigNumber is a whole number, otherwise returns false.
734 + * @alias [[isInt]]
735 + */
736 + isInteger(): boolean;
737 +
738 + /**
739 + * See [[isInteger]]
740 + */
741 + isInt(): boolean;
742 +
743 + /**
744 + * Returns `true` if the value of this BigNumber is `NaN`, otherwise returns `false`.
745 + *
746 + * Note: The native method isNaN() can also be used.
747 + */
748 + isNaN(): boolean;
749 +
750 + /**
751 + * Returns true if the value of this BigNumber is negative, otherwise returns false.
752 + *
753 + * Note: `n < 0` can be used if `n <= * -Number.MIN_VALUE`.
754 + *
755 + * @alias [[isNeg]]
756 + */
757 + isNegative(): boolean;
758 +
759 + /**
760 + * See [[isNegative]]
761 + */
762 + isNeg(): boolean;
763 +
764 + /**
765 + * Returns true if the value of this BigNumber is zero or minus zero, otherwise returns false.
766 + *
767 + * Note: `n == 0` can be used if `n >= Number.MIN_VALUE`.
768 + */
769 + isZero(): boolean;
770 +
771 + /**
772 + * Returns true if the value of this BigNumber is less than the value of n, otherwise returns false.
773 + *
774 + * Note: This method uses [[comparedTo]] internally.
775 + *
776 + * @alias [[lt]]
777 + */
778 + lessThan(n: number | string | BigNumber, base?: number): boolean;
779 +
780 + /**
781 + * See [[lessThan]]
782 + */
783 + lt(n: number | string | BigNumber, base?: number): boolean;
784 +
785 + /**
786 + * Returns true if the value of this BigNumber is less than or equal the value of n, otherwise returns false.
787 + *
788 + * Note: This method uses [[comparedTo]] internally.
789 + */
790 + lessThanOrEqualTo(n: number | string | BigNumber, base?: number): boolean;
791 +
792 + /**
793 + * See [[lessThanOrEqualTo]]
794 + */
795 + lte(n: number | string | BigNumber, base?: number): boolean;
796 +
797 + /**
798 + * Returns a BigNumber whose value is the value of this BigNumber minus `n`.
799 + *
800 + * The return value is always exact and unrounded.
801 + *
802 + * @alias [[sub]]
803 + */
804 + minus(n: number | string | BigNumber, base?: number): BigNumber;
805 +
806 + /**
807 + * Returns a BigNumber whose value is the value of this BigNumber modulo n, i.e. the integer remainder of dividing
808 + * this BigNumber by n.
809 + *
810 + * The value returned, and in particular its sign, is dependent on the value of the [[Configuration.MODULO_MODE]]
811 + * setting of this BigNumber constructor. If it is `1` (default value), the result will have the same sign as this
812 + * BigNumber, and it will match that of Javascript's `%` operator (within the limits of double precision) and
813 + * BigDecimal's remainder method.
814 + *
815 + * The return value is always exact and unrounded.
816 + *
817 + * ```ts
818 + * 1 % 0.9 // 0.09999999999999998
819 + * x = new BigNumber(1)
820 + * x.modulo(0.9) // '0.1'
821 + * y = new BigNumber(33)
822 + * y.mod('a', 33) // '3'
823 + * ```
824 + *
825 + * @alias [[mod]]
826 + */
827 + modulo(n: number | string | BigNumber, base?: number): BigNumber;
828 +
829 + /**
830 + * See [[modulo]]
831 + */
832 + mod(n: number | string | BigNumber, base?: number): BigNumber;
833 +
834 + /**
835 + * See [[times]]
836 + */
837 + mul(n: number | string | BigNumber, base?: number): BigNumber;
838 +
839 + /**
840 + * Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by -1.
841 + *
842 + * ```ts
843 + * x = new BigNumber(1.8)
844 + * x.negated() // '-1.8'
845 + * y = new BigNumber(-1.3)
846 + * y.neg() // '1.3'
847 + * ```
848 + *
849 + * @alias [[neg]]
850 + */
851 + negated(): BigNumber;
852 +
853 + /**
854 + * See [[negated]]
855 + */
856 + neg(): BigNumber;
857 +
858 + /**
859 + * Returns a BigNumber whose value is the value of this BigNumber plus `n`.
860 + *
861 + * The return value is always exact and unrounded.
862 + *
863 + * @alias [[add]]
864 + */
865 + plus(n: number | string | BigNumber, base?: number): BigNumber;
866 +
867 + /**
868 + * If z is true or 1 then any trailing zeros of the integer part of a number are counted as significant digits,
869 + * otherwise they are not.
870 + *
871 + * @param z true, false, 0 or 1
872 + * @alias [[sd]]
873 + */
874 + precision(z?: boolean | number): number;
875 +
876 + /**
877 + * See [[precision]]
878 + */
879 + sd(z?: boolean | number): number;
880 +
881 + /**
882 + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode rm to a maximum of dp
883 + * decimal places.
884 + *
885 + * - if dp is omitted, or is null or undefined, the return value is n rounded to a whole number.
886 + * - if rm is omitted, or is null or undefined, ROUNDING_MODE is used.
887 + *
888 + * ```ts
889 + * x = 1234.56
890 + * Math.round(x) // 1235
891 + * y = new BigNumber(x)
892 + * y.round() // '1235'
893 + * y.round(1) // '1234.6'
894 + * y.round(2) // '1234.56'
895 + * y.round(10) // '1234.56'
896 + * y.round(0, 1) // '1234'
897 + * y.round(0, 6) // '1235'
898 + * y.round(1, 1) // '1234.5'
899 + * y.round(1, BigNumber.ROUND_HALF_EVEN) // '1234.6'
900 + * y // '1234.56'
901 + * ```
902 + *
903 + * @param dp integer, 0 to 1e+9 inclusive
904 + * @param rm integer, 0 to 8 inclusive
905 + */
906 + round(dp?: number, rm?: number): BigNumber;
907 +
908 + /**
909 + * Returns a BigNumber whose value is the value of this BigNumber shifted n places.
910 + *
911 + * 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
912 + * n is positive. The return value is always exact and unrounded.
913 + *
914 + * @param n integer, -9007199254740991 to 9007199254740991 inclusive
915 + */
916 + shift(n: number): BigNumber;
917 +
918 + /**
919 + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded according to the
920 + * current DECIMAL_PLACES and ROUNDING_MODE configuration.
921 + *
922 + * The return value will be correctly rounded, i.e. rounded
923 + * as if the result was first calculated to an infinite number of correct digits before rounding.
924 + *
925 + * @alias [[sqrt]]
926 + */
927 + squareRoot(): BigNumber;
928 +
929 + /**
930 + * See [[squareRoot]]
931 + */
932 + sqrt(): BigNumber;
933 +
934 + /**
935 + * See [[minus]]
936 + */
937 + sub(n: number | string | BigNumber, base?: number): BigNumber;
938 +
939 + /**
940 + * Returns a BigNumber whose value is the value of this BigNumber times n.
941 + *
942 + * The return value is always exact and unrounded.
943 + *
944 + * @alias [[mul]]
945 + */
946 + times(n: number | string | BigNumber, base?: number): BigNumber;
947 +
948 + /**
949 + * Returns a BigNumber whose value is the value of this BigNumber rounded to sd significant digits using rounding mode rm.
950 + *
951 + * If sd is omitted or is null or undefined, the return value will not be rounded.
952 + *
953 + * If rm is omitted or is null or undefined, ROUNDING_MODE will be used.
954 + *
955 + * ```ts
956 + * BigNumber.config({ precision: 5, rounding: 4 })
957 + * x = new BigNumber(9876.54321)
958 + *
959 + * x.toDigits() // '9876.5'
960 + * x.toDigits(6) // '9876.54'
961 + * x.toDigits(6, BigNumber.ROUND_UP) // '9876.55'
962 + * x.toDigits(2) // '9900'
963 + * x.toDigits(2, 1) // '9800'
964 + * x // '9876.54321'
965 + * ```
966 + *
967 + * @param sd integer, 1 to 1e+9 inclusive
968 + * @param rm integer, 0 to 8 inclusive
969 + */
970 + toDigits(sd?: number, rm?: number): BigNumber;
971 +
972 + /**
973 + * Returns a string representing the value of this BigNumber in exponential notation rounded using rounding mode rm
974 + * to dp decimal places, i.e with one digit before the decimal point and dp digits after it.
975 + *
976 + * If the value of this BigNumber in exponential notation has fewer than dp fraction digits, the return value will
977 + * be appended with zeros accordingly.
978 + *
979 + * If dp is omitted, or is null or undefined, the number of digits after the decimal point defaults to the minimum
980 + * number of digits necessary to represent the value exactly.
981 + *
982 + * If rm is omitted or is null or undefined, ROUNDING_MODE is used.
983 + *
984 + * ```ts
985 + * x = 45.6
986 + * y = new BigNumber(x)
987 + * x.toExponential() // '4.56e+1'
988 + * y.toExponential() // '4.56e+1'
989 + * x.toExponential(0) // '5e+1'
990 + * y.toExponential(0) // '5e+1'
991 + * x.toExponential(1) // '4.6e+1'
992 + * y.toExponential(1) // '4.6e+1'
993 + * y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN)
994 + * x.toExponential(3) // '4.560e+1'
995 + * y.toExponential(3) // '4.560e+1'
996 + * ```
997 + *
998 + * @param dp integer, 0 to 1e+9 inclusive
999 + * @param rm integer, 0 to 8 inclusive
1000 + */
1001 + toExponential(dp?: number, rm?: number): string;
1002 +
1003 + /**
1004 + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation rounded to dp decimal
1005 + * places using rounding mode `rm`.
1006 + *
1007 + * If the value of this BigNumber in normal notation has fewer than `dp` fraction digits, the return value will be
1008 + * appended with zeros accordingly.
1009 + *
1010 + * Unlike `Number.prototype.toFixed`, which returns exponential notation if a number is greater or equal to 10<sup>21</sup>, this
1011 + * method will always return normal notation.
1012 + *
1013 + * If dp is omitted or is `null` or `undefined`, the return value will be unrounded and in normal notation. This is also
1014 + * unlike `Number.prototype.toFixed`, which returns the value to zero decimal places.
1015 + *
1016 + * It is useful when fixed-point notation is required and the current `EXPONENTIAL_AT` setting causes toString to
1017 + * return exponential notation.
1018 + *
1019 + * If `rm` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used.
1020 + *
1021 + * ```ts
1022 + * x = 3.456
1023 + * y = new BigNumber(x)
1024 + * x.toFixed() // '3'
1025 + * y.toFixed() // '3.456'
1026 + * y.toFixed(0) // '3'
1027 + * x.toFixed(2) // '3.46'
1028 + * y.toFixed(2) // '3.46'
1029 + * y.toFixed(2, 1) // '3.45' (ROUND_DOWN)
1030 + * x.toFixed(5) // '3.45600'
1031 + * y.toFixed(5) // '3.45600'
1032 + * ```
1033 + *
1034 + * @param dp integer, 0 to 1e+9 inclusive
1035 + * @param rm integer, 0 to 8 inclusive
1036 + */
1037 + toFixed(dp?: number, rm?: number): string;
1038 +
1039 + /**
1040 + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation rounded to dp decimal
1041 + * places using rounding mode `rm`, and formatted according to the properties of the FORMAT object.
1042 + *
1043 + * See the examples below for the properties of the `FORMAT` object, their types and their usage.
1044 + *
1045 + * If `dp` is omitted or is `null` or `undefined`, then the return value is not rounded to a fixed number of decimal
1046 + * places.
1047 + *
1048 + * If `rm` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used.
1049 + *
1050 + * ```ts
1051 + * format = {
1052 + * decimalSeparator: '.',
1053 + * groupSeparator: ',',
1054 + * groupSize: 3,
1055 + * secondaryGroupSize: 0,
1056 + * fractionGroupSeparator: ' ',
1057 + * fractionGroupSize: 0
1058 + * }
1059 + * BigNumber.config({ FORMAT: format })
1060 + *
1061 + * x = new BigNumber('123456789.123456789')
1062 + * x.toFormat() // '123,456,789.123456789'
1063 + * x.toFormat(1) // '123,456,789.1'
1064 + *
1065 + * // If a reference to the object assigned to FORMAT has been retained,
1066 + * // the format properties can be changed directly
1067 + * format.groupSeparator = ' '
1068 + * format.fractionGroupSize = 5
1069 + * x.toFormat() // '123 456 789.12345 6789'
1070 + *
1071 + * BigNumber.config({
1072 + * FORMAT: {
1073 + * decimalSeparator = ',',
1074 + * groupSeparator = '.',
1075 + * groupSize = 3,
1076 + * secondaryGroupSize = 2
1077 + * }
1078 + * })
1079 + *
1080 + * x.toFormat(6) // '12.34.56.789,123'
1081 + * ```
1082 + *
1083 + * @param dp integer, 0 to 1e+9 inclusive
1084 + * @param rm integer, 0 to 8 inclusive
1085 + */
1086 + toFormat(dp?: number, rm?: number): string;
1087 +
1088 + /**
1089 + * Returns a string array representing the value of this BigNumber as a simple fraction with an integer numerator
1090 + * and an integer denominator. The denominator will be a positive non-zero value less than or equal to max.
1091 + *
1092 + * If a maximum denominator, max, is not specified, or is null or undefined, the denominator will be the lowest
1093 + * value necessary to represent the number exactly.
1094 + *
1095 + * ```ts
1096 + * x = new BigNumber(1.75)
1097 + * x.toFraction() // '7, 4'
1098 + *
1099 + * pi = new BigNumber('3.14159265358')
1100 + * pi.toFraction() // '157079632679,50000000000'
1101 + * pi.toFraction(100000) // '312689, 99532'
1102 + * pi.toFraction(10000) // '355, 113'
1103 + * pi.toFraction(100) // '311, 99'
1104 + * pi.toFraction(10) // '22, 7'
1105 + * pi.toFraction(1) // '3, 1'
1106 + * ```
1107 + *
1108 + * @param max integer >= `1` and < `Infinity`
1109 + */
1110 + toFraction(max?: number | string | BigNumber): [string, string];
1111 +
1112 + /**
1113 + * Same as [[valueOf]]
1114 + *
1115 + * ```ts
1116 + * x = new BigNumber('177.7e+457')
1117 + * y = new BigNumber(235.4325)
1118 + * z = new BigNumber('0.0098074')
1119 + *
1120 + * // Serialize an array of three BigNumbers
1121 + * str = JSON.stringify( [x, y, z] )
1122 + * // "["1.777e+459","235.4325","0.0098074"]"
1123 + *
1124 + * // Return an array of three BigNumbers
1125 + * JSON.parse(str, function (key, val) {
1126 + * return key === '' ? val : new BigNumber(val)
1127 + * })
1128 + * ```
1129 + */
1130 + toJSON(): string;
1131 +
1132 + /**
1133 + * Returns the value of this BigNumber as a JavaScript number primitive.
1134 + *
1135 + * Type coercion with, for example, the unary plus operator will also work, except that a BigNumber with the value
1136 + * minus zero will be converted to positive zero.
1137 + *
1138 + * ```ts
1139 + * x = new BigNumber(456.789)
1140 + * x.toNumber() // 456.789
1141 + * +x // 456.789
1142 + *
1143 + * y = new BigNumber('45987349857634085409857349856430985')
1144 + * y.toNumber() // 4.598734985763409e+34
1145 + *
1146 + * z = new BigNumber(-0)
1147 + * 1 / +z // Infinity
1148 + * 1 / z.toNumber() // -Infinity
1149 + * ```
1150 + */
1151 + toNumber(): number;
1152 +
1153 + /**
1154 + * Returns a BigNumber whose value is the value of this BigNumber raised to the power `n`, and optionally modulo `a`
1155 + * modulus `m`.
1156 + *
1157 + * If `n` is negative the result is rounded according to the current [[Configuration.DECIMAL_PLACES]] and
1158 + * [[Configuration.ROUNDING_MODE]] configuration.
1159 + *
1160 + * If `n` is not an integer or is out of range:
1161 + * - If `ERRORS` is `true` a BigNumber Error is thrown,
1162 + * - else if `n` is greater than `9007199254740991`, it is interpreted as `Infinity`;
1163 + * - else if n is less than `-9007199254740991`, it is interpreted as `-Infinity`;
1164 + * - else if `n` is otherwise a number, it is truncated to an integer;
1165 + * - else it is interpreted as `NaN`.
1166 + *
1167 + * As the number of digits of the result of the power operation can grow so large so quickly, e.g.
1168 + * 123.456<sup>10000</sup> has over 50000 digits, the number of significant digits calculated is limited to the
1169 + * value of the [[Configuration.POW_PRECISION]] setting (default value: `100`) unless a modulus `m` is specified.
1170 + *
1171 + * Set [[Configuration.POW_PRECISION]] to `0` for an unlimited number of significant digits to be calculated (this
1172 + * will cause the method to slow dramatically for larger exponents).
1173 + *
1174 + * Negative exponents will be calculated to the number of decimal places specified by
1175 + * [[Configuration.DECIMAL_PLACES]] (but not to more than [[Configuration.POW_PRECISION]] significant digits).
1176 + *
1177 + * If `m` is specified and the value of `m`, `n` and this BigNumber are positive integers, then a fast modular
1178 + * exponentiation algorithm is used, otherwise if any of the values is not a positive integer the operation will
1179 + * simply be performed as `x.toPower(n).modulo(m)` with a `POW_PRECISION` of `0`.
1180 + *
1181 + * ```ts
1182 + * Math.pow(0.7, 2) // 0.48999999999999994
1183 + * x = new BigNumber(0.7)
1184 + * x.toPower(2) // '0.49'
1185 + * BigNumber(3).pow(-2) // '0.11111111111111111111'
1186 + * ```
1187 + *
1188 + * @param n integer, -9007199254740991 to 9007199254740991 inclusive
1189 + * @alias [[pow]]
1190 + */
1191 + toPower(n: number, m?: number | string | BigNumber): BigNumber;
1192 +
1193 + /**
1194 + * See [[toPower]]
1195 + */
1196 + pow(n: number, m?: number | string | BigNumber): BigNumber;
1197 +
1198 + /**
1199 + * Returns a string representing the value of this BigNumber rounded to `sd` significant digits using rounding mode
1200 + * rm.
1201 + *
1202 + * - If `sd` is less than the number of digits necessary to represent the integer part of the value in normal
1203 + * (fixed-point) notation, then exponential notation is used.
1204 + * - If `sd` is omitted, or is `null` or `undefined`, then the return value is the same as `n.toString()`.
1205 + * - If `rm` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used.
1206 + *
1207 + * ```ts
1208 + * x = 45.6
1209 + * y = new BigNumber(x)
1210 + * x.toPrecision() // '45.6'
1211 + * y.toPrecision() // '45.6'
1212 + * x.toPrecision(1) // '5e+1'
1213 + * y.toPrecision(1) // '5e+1'
1214 + * y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP)
1215 + * y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN)
1216 + * x.toPrecision(5) // '45.600'
1217 + * y.toPrecision(5) // '45.600'
1218 + * ```
1219 + *
1220 + * @param sd integer, 1 to 1e+9 inclusive
1221 + * @param rm integer, 0 to 8 inclusive
1222 + */
1223 + toPrecision(sd?: number, rm?: number): string;
1224 +
1225 + /**
1226 + * Returns a string representing the value of this BigNumber in the specified base, or base 10 if base is omitted or
1227 + * is `null` or `undefined`.
1228 + *
1229 + * For bases above 10, values from 10 to 35 are represented by a-z (as with `Number.prototype.toString`), 36 to 61 by
1230 + * A-Z, and 62 and 63 by `$` and `_` respectively.
1231 + *
1232 + * If a base is specified the value is rounded according to the current `DECIMAL_PLACES` and `ROUNDING_MODE`
1233 + * configuration.
1234 + *
1235 + * If a base is not specified, and this BigNumber has a positive exponent that is equal to or greater than the
1236 + * positive component of the current `EXPONENTIAL_AT` setting, or a negative exponent equal to or less than the
1237 + * negative component of the setting, then exponential notation is returned.
1238 + *
1239 + * If base is `null` or `undefined` it is ignored.
1240 + *
1241 + * ```ts
1242 + * x = new BigNumber(750000)
1243 + * x.toString() // '750000'
1244 + * BigNumber.config({ EXPONENTIAL_AT: 5 })
1245 + * x.toString() // '7.5e+5'
1246 + *
1247 + * y = new BigNumber(362.875)
1248 + * y.toString(2) // '101101010.111'
1249 + * y.toString(9) // '442.77777777777777777778'
1250 + * y.toString(32) // 'ba.s'
1251 + *
1252 + * BigNumber.config({ DECIMAL_PLACES: 4 });
1253 + * z = new BigNumber('1.23456789')
1254 + * z.toString() // '1.23456789'
1255 + * z.toString(10) // '1.2346'
1256 + * ```
1257 + *
1258 + * @param base integer, 2 to 64 inclusive
1259 + */
1260 + toString(base?: number): string;
1261 +
1262 + /**
1263 + * Returns a BigNumber whose value is the value of this BigNumber truncated to a whole number.
1264 + *
1265 + * ```ts
1266 + * x = new BigNumber(123.456)
1267 + * x.truncated() // '123'
1268 + * y = new BigNumber(-12.3)
1269 + * y.trunc() // '-12'
1270 + * ```
1271 + *
1272 + * @alias [[trunc]]
1273 + */
1274 + truncated(): BigNumber;
1275 +
1276 + /**
1277 + * See [[truncated]]
1278 + */
1279 + trunc(): BigNumber;
1280 +
1281 + /**
1282 + * As [[toString]], but does not accept a base argument and includes the minus sign for negative zero.`
1283 + *
1284 + * ```ts
1285 + * x = new BigNumber('-0')
1286 + * x.toString() // '0'
1287 + * x.valueOf() // '-0'
1288 + * y = new BigNumber('1.777e+457')
1289 + * y.valueOf() // '1.777e+457'
1290 + * ```
1291 + */
1292 + valueOf(): string;
1293 +}
1294 +
1295 +export default BigNumber;
This diff could not be displayed because it is too large.
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 ...\ No newline at end of file
1 +/* bignumber.js v4.1.0 https://github.com/MikeMcl/bignumber.js/LICENCE */
2 +!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);
3 +//# sourceMappingURL=bignumber.js.map
...\ No newline at end of file ...\ No newline at end of file
1 +/*
2 + *
3 + * bignumber.js v4.1.0
4 + * A JavaScript library for arbitrary-precision arithmetic.
5 + * https://github.com/MikeMcl/bignumber.js
6 + * Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
7 + * MIT Expat Licence
8 + *
9 + */
10 +
11 +
12 +var BigNumber,
13 + isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
14 + mathceil = Math.ceil,
15 + mathfloor = Math.floor,
16 + notBool = ' not a boolean or binary digit',
17 + roundingMode = 'rounding mode',
18 + tooManyDigits = 'number type has more than 15 significant digits',
19 + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
20 + BASE = 1e14,
21 + LOG_BASE = 14,
22 + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
23 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1
24 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
25 + SQRT_BASE = 1e7,
26 +
27 + /*
28 + * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
29 + * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
30 + * exception is thrown (if ERRORS is true).
31 + */
32 + MAX = 1E9; // 0 to MAX_INT32
33 +
34 +
35 +/*
36 + * Create and return a BigNumber constructor.
37 + */
38 +function constructorFactory(config) {
39 + var div, parseNumeric,
40 +
41 + // id tracks the caller function, so its name can be included in error messages.
42 + id = 0,
43 + P = BigNumber.prototype,
44 + ONE = new BigNumber(1),
45 +
46 +
47 +/*************************************** EDITABLE DEFAULTS ****************************************/
48 +
49 +
50 + /*
51 + * The default values below must be integers within the inclusive ranges stated.
52 + * The values can also be changed at run-time using BigNumber.config.
53 + */
54 +
55 + // The maximum number of decimal places for operations involving division.
56 + DECIMAL_PLACES = 20, // 0 to MAX
57 +
58 + /*
59 + * The rounding mode used when rounding to the above decimal places, and when using
60 + * toExponential, toFixed, toFormat and toPrecision, and round (default value).
61 + * UP 0 Away from zero.
62 + * DOWN 1 Towards zero.
63 + * CEIL 2 Towards +Infinity.
64 + * FLOOR 3 Towards -Infinity.
65 + * HALF_UP 4 Towards nearest neighbour. If equidistant, up.
66 + * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
67 + * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
68 + * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
69 + * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
70 + */
71 + ROUNDING_MODE = 4, // 0 to 8
72 +
73 + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
74 +
75 + // The exponent value at and beneath which toString returns exponential notation.
76 + // Number type: -7
77 + TO_EXP_NEG = -7, // 0 to -MAX
78 +
79 + // The exponent value at and above which toString returns exponential notation.
80 + // Number type: 21
81 + TO_EXP_POS = 21, // 0 to MAX
82 +
83 + // RANGE : [MIN_EXP, MAX_EXP]
84 +
85 + // The minimum exponent value, beneath which underflow to zero occurs.
86 + // Number type: -324 (5e-324)
87 + MIN_EXP = -1e7, // -1 to -MAX
88 +
89 + // The maximum exponent value, above which overflow to Infinity occurs.
90 + // Number type: 308 (1.7976931348623157e+308)
91 + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
92 + MAX_EXP = 1e7, // 1 to MAX
93 +
94 + // Whether BigNumber Errors are ever thrown.
95 + ERRORS = true, // true or false
96 +
97 + // Change to intValidatorNoErrors if ERRORS is false.
98 + isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
99 +
100 + // Whether to use cryptographically-secure random number generation, if available.
101 + CRYPTO = false, // true or false
102 +
103 + /*
104 + * The modulo mode used when calculating the modulus: a mod n.
105 + * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
106 + * The remainder (r) is calculated as: r = a - n * q.
107 + *
108 + * UP 0 The remainder is positive if the dividend is negative, else is negative.
109 + * DOWN 1 The remainder has the same sign as the dividend.
110 + * This modulo mode is commonly known as 'truncated division' and is
111 + * equivalent to (a % n) in JavaScript.
112 + * FLOOR 3 The remainder has the same sign as the divisor (Python %).
113 + * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
114 + * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
115 + * The remainder is always positive.
116 + *
117 + * The truncated division, floored division, Euclidian division and IEEE 754 remainder
118 + * modes are commonly used for the modulus operation.
119 + * Although the other rounding modes can also be used, they may not give useful results.
120 + */
121 + MODULO_MODE = 1, // 0 to 9
122 +
123 + // The maximum number of significant digits of the result of the toPower operation.
124 + // If POW_PRECISION is 0, there will be unlimited significant digits.
125 + POW_PRECISION = 0, // 0 to MAX
126 +
127 + // The format specification used by the BigNumber.prototype.toFormat method.
128 + FORMAT = {
129 + decimalSeparator: '.',
130 + groupSeparator: ',',
131 + groupSize: 3,
132 + secondaryGroupSize: 0,
133 + fractionGroupSeparator: '\xA0', // non-breaking space
134 + fractionGroupSize: 0
135 + };
136 +
137 +
138 +/**************************************************************************************************/
139 +
140 +
141 + // CONSTRUCTOR
142 +
143 +
144 + /*
145 + * The BigNumber constructor and exported function.
146 + * Create and return a new instance of a BigNumber object.
147 + *
148 + * n {number|string|BigNumber} A numeric value.
149 + * [b] {number} The base of n. Integer, 2 to 64 inclusive.
150 + */
151 + function BigNumber( n, b ) {
152 + var c, e, i, num, len, str,
153 + x = this;
154 +
155 + // Enable constructor usage without new.
156 + if ( !( x instanceof BigNumber ) ) {
157 +
158 + // 'BigNumber() constructor call without new: {n}'
159 + if (ERRORS) raise( 26, 'constructor call without new', n );
160 + return new BigNumber( n, b );
161 + }
162 +
163 + // 'new BigNumber() base not an integer: {b}'
164 + // 'new BigNumber() base out of range: {b}'
165 + if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
166 +
167 + // Duplicate.
168 + if ( n instanceof BigNumber ) {
169 + x.s = n.s;
170 + x.e = n.e;
171 + x.c = ( n = n.c ) ? n.slice() : n;
172 + id = 0;
173 + return;
174 + }
175 +
176 + if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
177 + x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
178 +
179 + // Fast path for integers.
180 + if ( n === ~~n ) {
181 + for ( e = 0, i = n; i >= 10; i /= 10, e++ );
182 + x.e = e;
183 + x.c = [n];
184 + id = 0;
185 + return;
186 + }
187 +
188 + str = n + '';
189 + } else {
190 + if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
191 + x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
192 + }
193 + } else {
194 + b = b | 0;
195 + str = n + '';
196 +
197 + // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
198 + // Allow exponential notation to be used with base 10 argument.
199 + if ( b == 10 ) {
200 + x = new BigNumber( n instanceof BigNumber ? n : str );
201 + return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
202 + }
203 +
204 + // Avoid potential interpretation of Infinity and NaN as base 44+ values.
205 + // Any number in exponential form will fail due to the [Ee][+-].
206 + if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
207 + !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
208 + '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
209 + return parseNumeric( x, str, num, b );
210 + }
211 +
212 + if (num) {
213 + x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
214 +
215 + if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
216 +
217 + // 'new BigNumber() number type has more than 15 significant digits: {n}'
218 + raise( id, tooManyDigits, n );
219 + }
220 +
221 + // Prevent later check for length on converted number.
222 + num = false;
223 + } else {
224 + x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
225 + }
226 +
227 + str = convertBase( str, 10, b, x.s );
228 + }
229 +
230 + // Decimal point?
231 + if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
232 +
233 + // Exponential form?
234 + if ( ( i = str.search( /e/i ) ) > 0 ) {
235 +
236 + // Determine exponent.
237 + if ( e < 0 ) e = i;
238 + e += +str.slice( i + 1 );
239 + str = str.substring( 0, i );
240 + } else if ( e < 0 ) {
241 +
242 + // Integer.
243 + e = str.length;
244 + }
245 +
246 + // Determine leading zeros.
247 + for ( i = 0; str.charCodeAt(i) === 48; i++ );
248 +
249 + // Determine trailing zeros.
250 + for ( len = str.length; str.charCodeAt(--len) === 48; );
251 + str = str.slice( i, len + 1 );
252 +
253 + if (str) {
254 + len = str.length;
255 +
256 + // Disallow numbers with over 15 significant digits if number type.
257 + // 'new BigNumber() number type has more than 15 significant digits: {n}'
258 + if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
259 + raise( id, tooManyDigits, x.s * n );
260 + }
261 +
262 + e = e - i - 1;
263 +
264 + // Overflow?
265 + if ( e > MAX_EXP ) {
266 +
267 + // Infinity.
268 + x.c = x.e = null;
269 +
270 + // Underflow?
271 + } else if ( e < MIN_EXP ) {
272 +
273 + // Zero.
274 + x.c = [ x.e = 0 ];
275 + } else {
276 + x.e = e;
277 + x.c = [];
278 +
279 + // Transform base
280 +
281 + // e is the base 10 exponent.
282 + // i is where to slice str to get the first element of the coefficient array.
283 + i = ( e + 1 ) % LOG_BASE;
284 + if ( e < 0 ) i += LOG_BASE;
285 +
286 + if ( i < len ) {
287 + if (i) x.c.push( +str.slice( 0, i ) );
288 +
289 + for ( len -= LOG_BASE; i < len; ) {
290 + x.c.push( +str.slice( i, i += LOG_BASE ) );
291 + }
292 +
293 + str = str.slice(i);
294 + i = LOG_BASE - str.length;
295 + } else {
296 + i -= len;
297 + }
298 +
299 + for ( ; i--; str += '0' );
300 + x.c.push( +str );
301 + }
302 + } else {
303 +
304 + // Zero.
305 + x.c = [ x.e = 0 ];
306 + }
307 +
308 + id = 0;
309 + }
310 +
311 +
312 + // CONSTRUCTOR PROPERTIES
313 +
314 +
315 + BigNumber.another = constructorFactory;
316 +
317 + BigNumber.ROUND_UP = 0;
318 + BigNumber.ROUND_DOWN = 1;
319 + BigNumber.ROUND_CEIL = 2;
320 + BigNumber.ROUND_FLOOR = 3;
321 + BigNumber.ROUND_HALF_UP = 4;
322 + BigNumber.ROUND_HALF_DOWN = 5;
323 + BigNumber.ROUND_HALF_EVEN = 6;
324 + BigNumber.ROUND_HALF_CEIL = 7;
325 + BigNumber.ROUND_HALF_FLOOR = 8;
326 + BigNumber.EUCLID = 9;
327 +
328 +
329 + /*
330 + * Configure infrequently-changing library-wide settings.
331 + *
332 + * Accept an object or an argument list, with one or many of the following properties or
333 + * parameters respectively:
334 + *
335 + * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
336 + * ROUNDING_MODE {number} Integer, 0 to 8 inclusive
337 + * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
338 + * [integer -MAX to 0 incl., 0 to MAX incl.]
339 + * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
340 + * [integer -MAX to -1 incl., integer 1 to MAX incl.]
341 + * ERRORS {boolean|number} true, false, 1 or 0
342 + * CRYPTO {boolean|number} true, false, 1 or 0
343 + * MODULO_MODE {number} 0 to 9 inclusive
344 + * POW_PRECISION {number} 0 to MAX inclusive
345 + * FORMAT {object} See BigNumber.prototype.toFormat
346 + * decimalSeparator {string}
347 + * groupSeparator {string}
348 + * groupSize {number}
349 + * secondaryGroupSize {number}
350 + * fractionGroupSeparator {string}
351 + * fractionGroupSize {number}
352 + *
353 + * (The values assigned to the above FORMAT object properties are not checked for validity.)
354 + *
355 + * E.g.
356 + * BigNumber.config(20, 4) is equivalent to
357 + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
358 + *
359 + * Ignore properties/parameters set to null or undefined.
360 + * Return an object with the properties current values.
361 + */
362 + BigNumber.config = BigNumber.set = function () {
363 + var v, p,
364 + i = 0,
365 + r = {},
366 + a = arguments,
367 + o = a[0],
368 + has = o && typeof o == 'object'
369 + ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
370 + : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
371 +
372 + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
373 + // 'config() DECIMAL_PLACES not an integer: {v}'
374 + // 'config() DECIMAL_PLACES out of range: {v}'
375 + if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
376 + DECIMAL_PLACES = v | 0;
377 + }
378 + r[p] = DECIMAL_PLACES;
379 +
380 + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
381 + // 'config() ROUNDING_MODE not an integer: {v}'
382 + // 'config() ROUNDING_MODE out of range: {v}'
383 + if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
384 + ROUNDING_MODE = v | 0;
385 + }
386 + r[p] = ROUNDING_MODE;
387 +
388 + // EXPONENTIAL_AT {number|number[]}
389 + // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
390 + // 'config() EXPONENTIAL_AT not an integer: {v}'
391 + // 'config() EXPONENTIAL_AT out of range: {v}'
392 + if ( has( p = 'EXPONENTIAL_AT' ) ) {
393 +
394 + if ( isArray(v) ) {
395 + if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
396 + TO_EXP_NEG = v[0] | 0;
397 + TO_EXP_POS = v[1] | 0;
398 + }
399 + } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
400 + TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
401 + }
402 + }
403 + r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
404 +
405 + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
406 + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
407 + // 'config() RANGE not an integer: {v}'
408 + // 'config() RANGE cannot be zero: {v}'
409 + // 'config() RANGE out of range: {v}'
410 + if ( has( p = 'RANGE' ) ) {
411 +
412 + if ( isArray(v) ) {
413 + if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
414 + MIN_EXP = v[0] | 0;
415 + MAX_EXP = v[1] | 0;
416 + }
417 + } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
418 + if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
419 + else if (ERRORS) raise( 2, p + ' cannot be zero', v );
420 + }
421 + }
422 + r[p] = [ MIN_EXP, MAX_EXP ];
423 +
424 + // ERRORS {boolean|number} true, false, 1 or 0.
425 + // 'config() ERRORS not a boolean or binary digit: {v}'
426 + if ( has( p = 'ERRORS' ) ) {
427 +
428 + if ( v === !!v || v === 1 || v === 0 ) {
429 + id = 0;
430 + isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
431 + } else if (ERRORS) {
432 + raise( 2, p + notBool, v );
433 + }
434 + }
435 + r[p] = ERRORS;
436 +
437 + // CRYPTO {boolean|number} true, false, 1 or 0.
438 + // 'config() CRYPTO not a boolean or binary digit: {v}'
439 + // 'config() crypto unavailable: {crypto}'
440 + if ( has( p = 'CRYPTO' ) ) {
441 +
442 + if ( v === true || v === false || v === 1 || v === 0 ) {
443 + if (v) {
444 + v = typeof crypto == 'undefined';
445 + if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
446 + CRYPTO = true;
447 + } else if (ERRORS) {
448 + raise( 2, 'crypto unavailable', v ? void 0 : crypto );
449 + } else {
450 + CRYPTO = false;
451 + }
452 + } else {
453 + CRYPTO = false;
454 + }
455 + } else if (ERRORS) {
456 + raise( 2, p + notBool, v );
457 + }
458 + }
459 + r[p] = CRYPTO;
460 +
461 + // MODULO_MODE {number} Integer, 0 to 9 inclusive.
462 + // 'config() MODULO_MODE not an integer: {v}'
463 + // 'config() MODULO_MODE out of range: {v}'
464 + if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
465 + MODULO_MODE = v | 0;
466 + }
467 + r[p] = MODULO_MODE;
468 +
469 + // POW_PRECISION {number} Integer, 0 to MAX inclusive.
470 + // 'config() POW_PRECISION not an integer: {v}'
471 + // 'config() POW_PRECISION out of range: {v}'
472 + if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
473 + POW_PRECISION = v | 0;
474 + }
475 + r[p] = POW_PRECISION;
476 +
477 + // FORMAT {object}
478 + // 'config() FORMAT not an object: {v}'
479 + if ( has( p = 'FORMAT' ) ) {
480 +
481 + if ( typeof v == 'object' ) {
482 + FORMAT = v;
483 + } else if (ERRORS) {
484 + raise( 2, p + ' not an object', v );
485 + }
486 + }
487 + r[p] = FORMAT;
488 +
489 + return r;
490 + };
491 +
492 +
493 + /*
494 + * Return a new BigNumber whose value is the maximum of the arguments.
495 + *
496 + * arguments {number|string|BigNumber}
497 + */
498 + BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
499 +
500 +
501 + /*
502 + * Return a new BigNumber whose value is the minimum of the arguments.
503 + *
504 + * arguments {number|string|BigNumber}
505 + */
506 + BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
507 +
508 +
509 + /*
510 + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
511 + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
512 + * zeros are produced).
513 + *
514 + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
515 + *
516 + * 'random() decimal places not an integer: {dp}'
517 + * 'random() decimal places out of range: {dp}'
518 + * 'random() crypto unavailable: {crypto}'
519 + */
520 + BigNumber.random = (function () {
521 + var pow2_53 = 0x20000000000000;
522 +
523 + // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
524 + // Check if Math.random() produces more than 32 bits of randomness.
525 + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
526 + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
527 + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
528 + ? function () { return mathfloor( Math.random() * pow2_53 ); }
529 + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
530 + (Math.random() * 0x800000 | 0); };
531 +
532 + return function (dp) {
533 + var a, b, e, k, v,
534 + i = 0,
535 + c = [],
536 + rand = new BigNumber(ONE);
537 +
538 + dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
539 + k = mathceil( dp / LOG_BASE );
540 +
541 + if (CRYPTO) {
542 +
543 + // Browsers supporting crypto.getRandomValues.
544 + if (crypto.getRandomValues) {
545 +
546 + a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
547 +
548 + for ( ; i < k; ) {
549 +
550 + // 53 bits:
551 + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
552 + // 11111 11111111 11111111 11111111 11100000 00000000 00000000
553 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
554 + // 11111 11111111 11111111
555 + // 0x20000 is 2^21.
556 + v = a[i] * 0x20000 + (a[i + 1] >>> 11);
557 +
558 + // Rejection sampling:
559 + // 0 <= v < 9007199254740992
560 + // Probability that v >= 9e15, is
561 + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
562 + if ( v >= 9e15 ) {
563 + b = crypto.getRandomValues( new Uint32Array(2) );
564 + a[i] = b[0];
565 + a[i + 1] = b[1];
566 + } else {
567 +
568 + // 0 <= v <= 8999999999999999
569 + // 0 <= (v % 1e14) <= 99999999999999
570 + c.push( v % 1e14 );
571 + i += 2;
572 + }
573 + }
574 + i = k / 2;
575 +
576 + // Node.js supporting crypto.randomBytes.
577 + } else if (crypto.randomBytes) {
578 +
579 + // buffer
580 + a = crypto.randomBytes( k *= 7 );
581 +
582 + for ( ; i < k; ) {
583 +
584 + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
585 + // 0x100000000 is 2^32, 0x1000000 is 2^24
586 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111
587 + // 0 <= v < 9007199254740992
588 + v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
589 + ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
590 + ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
591 +
592 + if ( v >= 9e15 ) {
593 + crypto.randomBytes(7).copy( a, i );
594 + } else {
595 +
596 + // 0 <= (v % 1e14) <= 99999999999999
597 + c.push( v % 1e14 );
598 + i += 7;
599 + }
600 + }
601 + i = k / 7;
602 + } else {
603 + CRYPTO = false;
604 + if (ERRORS) raise( 14, 'crypto unavailable', crypto );
605 + }
606 + }
607 +
608 + // Use Math.random.
609 + if (!CRYPTO) {
610 +
611 + for ( ; i < k; ) {
612 + v = random53bitInt();
613 + if ( v < 9e15 ) c[i++] = v % 1e14;
614 + }
615 + }
616 +
617 + k = c[--i];
618 + dp %= LOG_BASE;
619 +
620 + // Convert trailing digits to zeros according to dp.
621 + if ( k && dp ) {
622 + v = POWS_TEN[LOG_BASE - dp];
623 + c[i] = mathfloor( k / v ) * v;
624 + }
625 +
626 + // Remove trailing elements which are zero.
627 + for ( ; c[i] === 0; c.pop(), i-- );
628 +
629 + // Zero?
630 + if ( i < 0 ) {
631 + c = [ e = 0 ];
632 + } else {
633 +
634 + // Remove leading elements which are zero and adjust exponent accordingly.
635 + for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
636 +
637 + // Count the digits of the first element of c to determine leading zeros, and...
638 + for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
639 +
640 + // adjust the exponent accordingly.
641 + if ( i < LOG_BASE ) e -= LOG_BASE - i;
642 + }
643 +
644 + rand.e = e;
645 + rand.c = c;
646 + return rand;
647 + };
648 + })();
649 +
650 +
651 + // PRIVATE FUNCTIONS
652 +
653 +
654 + // Convert a numeric string of baseIn to a numeric string of baseOut.
655 + function convertBase( str, baseOut, baseIn, sign ) {
656 + var d, e, k, r, x, xc, y,
657 + i = str.indexOf( '.' ),
658 + dp = DECIMAL_PLACES,
659 + rm = ROUNDING_MODE;
660 +
661 + if ( baseIn < 37 ) str = str.toLowerCase();
662 +
663 + // Non-integer.
664 + if ( i >= 0 ) {
665 + k = POW_PRECISION;
666 +
667 + // Unlimited precision.
668 + POW_PRECISION = 0;
669 + str = str.replace( '.', '' );
670 + y = new BigNumber(baseIn);
671 + x = y.pow( str.length - i );
672 + POW_PRECISION = k;
673 +
674 + // Convert str as if an integer, then restore the fraction part by dividing the
675 + // result by its base raised to a power.
676 + y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
677 + y.e = y.c.length;
678 + }
679 +
680 + // Convert the number as integer.
681 + xc = toBaseOut( str, baseIn, baseOut );
682 + e = k = xc.length;
683 +
684 + // Remove trailing zeros.
685 + for ( ; xc[--k] == 0; xc.pop() );
686 + if ( !xc[0] ) return '0';
687 +
688 + if ( i < 0 ) {
689 + --e;
690 + } else {
691 + x.c = xc;
692 + x.e = e;
693 +
694 + // sign is needed for correct rounding.
695 + x.s = sign;
696 + x = div( x, y, dp, rm, baseOut );
697 + xc = x.c;
698 + r = x.r;
699 + e = x.e;
700 + }
701 +
702 + d = e + dp + 1;
703 +
704 + // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
705 + i = xc[d];
706 + k = baseOut / 2;
707 + r = r || d < 0 || xc[d + 1] != null;
708 +
709 + r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
710 + : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
711 + rm == ( x.s < 0 ? 8 : 7 ) );
712 +
713 + if ( d < 1 || !xc[0] ) {
714 +
715 + // 1^-dp or 0.
716 + str = r ? toFixedPoint( '1', -dp ) : '0';
717 + } else {
718 + xc.length = d;
719 +
720 + if (r) {
721 +
722 + // Rounding up may mean the previous digit has to be rounded up and so on.
723 + for ( --baseOut; ++xc[--d] > baseOut; ) {
724 + xc[d] = 0;
725 +
726 + if ( !d ) {
727 + ++e;
728 + xc = [1].concat(xc);
729 + }
730 + }
731 + }
732 +
733 + // Determine trailing zeros.
734 + for ( k = xc.length; !xc[--k]; );
735 +
736 + // E.g. [4, 11, 15] becomes 4bf.
737 + for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
738 + str = toFixedPoint( str, e );
739 + }
740 +
741 + // The caller will add the sign.
742 + return str;
743 + }
744 +
745 +
746 + // Perform division in the specified base. Called by div and convertBase.
747 + div = (function () {
748 +
749 + // Assume non-zero x and k.
750 + function multiply( x, k, base ) {
751 + var m, temp, xlo, xhi,
752 + carry = 0,
753 + i = x.length,
754 + klo = k % SQRT_BASE,
755 + khi = k / SQRT_BASE | 0;
756 +
757 + for ( x = x.slice(); i--; ) {
758 + xlo = x[i] % SQRT_BASE;
759 + xhi = x[i] / SQRT_BASE | 0;
760 + m = khi * xlo + xhi * klo;
761 + temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
762 + carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
763 + x[i] = temp % base;
764 + }
765 +
766 + if (carry) x = [carry].concat(x);
767 +
768 + return x;
769 + }
770 +
771 + function compare( a, b, aL, bL ) {
772 + var i, cmp;
773 +
774 + if ( aL != bL ) {
775 + cmp = aL > bL ? 1 : -1;
776 + } else {
777 +
778 + for ( i = cmp = 0; i < aL; i++ ) {
779 +
780 + if ( a[i] != b[i] ) {
781 + cmp = a[i] > b[i] ? 1 : -1;
782 + break;
783 + }
784 + }
785 + }
786 + return cmp;
787 + }
788 +
789 + function subtract( a, b, aL, base ) {
790 + var i = 0;
791 +
792 + // Subtract b from a.
793 + for ( ; aL--; ) {
794 + a[aL] -= i;
795 + i = a[aL] < b[aL] ? 1 : 0;
796 + a[aL] = i * base + a[aL] - b[aL];
797 + }
798 +
799 + // Remove leading zeros.
800 + for ( ; !a[0] && a.length > 1; a.splice(0, 1) );
801 + }
802 +
803 + // x: dividend, y: divisor.
804 + return function ( x, y, dp, rm, base ) {
805 + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
806 + yL, yz,
807 + s = x.s == y.s ? 1 : -1,
808 + xc = x.c,
809 + yc = y.c;
810 +
811 + // Either NaN, Infinity or 0?
812 + if ( !xc || !xc[0] || !yc || !yc[0] ) {
813 +
814 + return new BigNumber(
815 +
816 + // Return NaN if either NaN, or both Infinity or 0.
817 + !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
818 +
819 + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
820 + xc && xc[0] == 0 || !yc ? s * 0 : s / 0
821 + );
822 + }
823 +
824 + q = new BigNumber(s);
825 + qc = q.c = [];
826 + e = x.e - y.e;
827 + s = dp + e + 1;
828 +
829 + if ( !base ) {
830 + base = BASE;
831 + e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
832 + s = s / LOG_BASE | 0;
833 + }
834 +
835 + // Result exponent may be one less then the current value of e.
836 + // The coefficients of the BigNumbers from convertBase may have trailing zeros.
837 + for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
838 + if ( yc[i] > ( xc[i] || 0 ) ) e--;
839 +
840 + if ( s < 0 ) {
841 + qc.push(1);
842 + more = true;
843 + } else {
844 + xL = xc.length;
845 + yL = yc.length;
846 + i = 0;
847 + s += 2;
848 +
849 + // Normalise xc and yc so highest order digit of yc is >= base / 2.
850 +
851 + n = mathfloor( base / ( yc[0] + 1 ) );
852 +
853 + // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
854 + // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
855 + if ( n > 1 ) {
856 + yc = multiply( yc, n, base );
857 + xc = multiply( xc, n, base );
858 + yL = yc.length;
859 + xL = xc.length;
860 + }
861 +
862 + xi = yL;
863 + rem = xc.slice( 0, yL );
864 + remL = rem.length;
865 +
866 + // Add zeros to make remainder as long as divisor.
867 + for ( ; remL < yL; rem[remL++] = 0 );
868 + yz = yc.slice();
869 + yz = [0].concat(yz);
870 + yc0 = yc[0];
871 + if ( yc[1] >= base / 2 ) yc0++;
872 + // Not necessary, but to prevent trial digit n > base, when using base 3.
873 + // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
874 +
875 + do {
876 + n = 0;
877 +
878 + // Compare divisor and remainder.
879 + cmp = compare( yc, rem, yL, remL );
880 +
881 + // If divisor < remainder.
882 + if ( cmp < 0 ) {
883 +
884 + // Calculate trial digit, n.
885 +
886 + rem0 = rem[0];
887 + if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
888 +
889 + // n is how many times the divisor goes into the current remainder.
890 + n = mathfloor( rem0 / yc0 );
891 +
892 + // Algorithm:
893 + // 1. product = divisor * trial digit (n)
894 + // 2. if product > remainder: product -= divisor, n--
895 + // 3. remainder -= product
896 + // 4. if product was < remainder at 2:
897 + // 5. compare new remainder and divisor
898 + // 6. If remainder > divisor: remainder -= divisor, n++
899 +
900 + if ( n > 1 ) {
901 +
902 + // n may be > base only when base is 3.
903 + if (n >= base) n = base - 1;
904 +
905 + // product = divisor * trial digit.
906 + prod = multiply( yc, n, base );
907 + prodL = prod.length;
908 + remL = rem.length;
909 +
910 + // Compare product and remainder.
911 + // If product > remainder.
912 + // Trial digit n too high.
913 + // n is 1 too high about 5% of the time, and is not known to have
914 + // ever been more than 1 too high.
915 + while ( compare( prod, rem, prodL, remL ) == 1 ) {
916 + n--;
917 +
918 + // Subtract divisor from product.
919 + subtract( prod, yL < prodL ? yz : yc, prodL, base );
920 + prodL = prod.length;
921 + cmp = 1;
922 + }
923 + } else {
924 +
925 + // n is 0 or 1, cmp is -1.
926 + // If n is 0, there is no need to compare yc and rem again below,
927 + // so change cmp to 1 to avoid it.
928 + // If n is 1, leave cmp as -1, so yc and rem are compared again.
929 + if ( n == 0 ) {
930 +
931 + // divisor < remainder, so n must be at least 1.
932 + cmp = n = 1;
933 + }
934 +
935 + // product = divisor
936 + prod = yc.slice();
937 + prodL = prod.length;
938 + }
939 +
940 + if ( prodL < remL ) prod = [0].concat(prod);
941 +
942 + // Subtract product from remainder.
943 + subtract( rem, prod, remL, base );
944 + remL = rem.length;
945 +
946 + // If product was < remainder.
947 + if ( cmp == -1 ) {
948 +
949 + // Compare divisor and new remainder.
950 + // If divisor < new remainder, subtract divisor from remainder.
951 + // Trial digit n too low.
952 + // n is 1 too low about 5% of the time, and very rarely 2 too low.
953 + while ( compare( yc, rem, yL, remL ) < 1 ) {
954 + n++;
955 +
956 + // Subtract divisor from remainder.
957 + subtract( rem, yL < remL ? yz : yc, remL, base );
958 + remL = rem.length;
959 + }
960 + }
961 + } else if ( cmp === 0 ) {
962 + n++;
963 + rem = [0];
964 + } // else cmp === 1 and n will be 0
965 +
966 + // Add the next digit, n, to the result array.
967 + qc[i++] = n;
968 +
969 + // Update the remainder.
970 + if ( rem[0] ) {
971 + rem[remL++] = xc[xi] || 0;
972 + } else {
973 + rem = [ xc[xi] ];
974 + remL = 1;
975 + }
976 + } while ( ( xi++ < xL || rem[0] != null ) && s-- );
977 +
978 + more = rem[0] != null;
979 +
980 + // Leading zero?
981 + if ( !qc[0] ) qc.splice(0, 1);
982 + }
983 +
984 + if ( base == BASE ) {
985 +
986 + // To calculate q.e, first get the number of digits of qc[0].
987 + for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
988 + round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
989 +
990 + // Caller is convertBase.
991 + } else {
992 + q.e = e;
993 + q.r = +more;
994 + }
995 +
996 + return q;
997 + };
998 + })();
999 +
1000 +
1001 + /*
1002 + * Return a string representing the value of BigNumber n in fixed-point or exponential
1003 + * notation rounded to the specified decimal places or significant digits.
1004 + *
1005 + * n is a BigNumber.
1006 + * i is the index of the last digit required (i.e. the digit that may be rounded up).
1007 + * rm is the rounding mode.
1008 + * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
1009 + */
1010 + function format( n, i, rm, caller ) {
1011 + var c0, e, ne, len, str;
1012 +
1013 + rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
1014 + ? rm | 0 : ROUNDING_MODE;
1015 +
1016 + if ( !n.c ) return n.toString();
1017 + c0 = n.c[0];
1018 + ne = n.e;
1019 +
1020 + if ( i == null ) {
1021 + str = coeffToString( n.c );
1022 + str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
1023 + ? toExponential( str, ne )
1024 + : toFixedPoint( str, ne );
1025 + } else {
1026 + n = round( new BigNumber(n), i, rm );
1027 +
1028 + // n.e may have changed if the value was rounded up.
1029 + e = n.e;
1030 +
1031 + str = coeffToString( n.c );
1032 + len = str.length;
1033 +
1034 + // toPrecision returns exponential notation if the number of significant digits
1035 + // specified is less than the number of digits necessary to represent the integer
1036 + // part of the value in fixed-point notation.
1037 +
1038 + // Exponential notation.
1039 + if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
1040 +
1041 + // Append zeros?
1042 + for ( ; len < i; str += '0', len++ );
1043 + str = toExponential( str, e );
1044 +
1045 + // Fixed-point notation.
1046 + } else {
1047 + i -= ne;
1048 + str = toFixedPoint( str, e );
1049 +
1050 + // Append zeros?
1051 + if ( e + 1 > len ) {
1052 + if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
1053 + } else {
1054 + i += e - len;
1055 + if ( i > 0 ) {
1056 + if ( e + 1 == len ) str += '.';
1057 + for ( ; i--; str += '0' );
1058 + }
1059 + }
1060 + }
1061 + }
1062 +
1063 + return n.s < 0 && c0 ? '-' + str : str;
1064 + }
1065 +
1066 +
1067 + // Handle BigNumber.max and BigNumber.min.
1068 + function maxOrMin( args, method ) {
1069 + var m, n,
1070 + i = 0;
1071 +
1072 + if ( isArray( args[0] ) ) args = args[0];
1073 + m = new BigNumber( args[0] );
1074 +
1075 + for ( ; ++i < args.length; ) {
1076 + n = new BigNumber( args[i] );
1077 +
1078 + // If any number is NaN, return NaN.
1079 + if ( !n.s ) {
1080 + m = n;
1081 + break;
1082 + } else if ( method.call( m, n ) ) {
1083 + m = n;
1084 + }
1085 + }
1086 +
1087 + return m;
1088 + }
1089 +
1090 +
1091 + /*
1092 + * Return true if n is an integer in range, otherwise throw.
1093 + * Use for argument validation when ERRORS is true.
1094 + */
1095 + function intValidatorWithErrors( n, min, max, caller, name ) {
1096 + if ( n < min || n > max || n != truncate(n) ) {
1097 + raise( caller, ( name || 'decimal places' ) +
1098 + ( n < min || n > max ? ' out of range' : ' not an integer' ), n );
1099 + }
1100 +
1101 + return true;
1102 + }
1103 +
1104 +
1105 + /*
1106 + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
1107 + * Called by minus, plus and times.
1108 + */
1109 + function normalise( n, c, e ) {
1110 + var i = 1,
1111 + j = c.length;
1112 +
1113 + // Remove trailing zeros.
1114 + for ( ; !c[--j]; c.pop() );
1115 +
1116 + // Calculate the base 10 exponent. First get the number of digits of c[0].
1117 + for ( j = c[0]; j >= 10; j /= 10, i++ );
1118 +
1119 + // Overflow?
1120 + if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
1121 +
1122 + // Infinity.
1123 + n.c = n.e = null;
1124 +
1125 + // Underflow?
1126 + } else if ( e < MIN_EXP ) {
1127 +
1128 + // Zero.
1129 + n.c = [ n.e = 0 ];
1130 + } else {
1131 + n.e = e;
1132 + n.c = c;
1133 + }
1134 +
1135 + return n;
1136 + }
1137 +
1138 +
1139 + // Handle values that fail the validity test in BigNumber.
1140 + parseNumeric = (function () {
1141 + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
1142 + dotAfter = /^([^.]+)\.$/,
1143 + dotBefore = /^\.([^.]+)$/,
1144 + isInfinityOrNaN = /^-?(Infinity|NaN)$/,
1145 + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
1146 +
1147 + return function ( x, str, num, b ) {
1148 + var base,
1149 + s = num ? str : str.replace( whitespaceOrPlus, '' );
1150 +
1151 + // No exception on ±Infinity or NaN.
1152 + if ( isInfinityOrNaN.test(s) ) {
1153 + x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
1154 + } else {
1155 + if ( !num ) {
1156 +
1157 + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
1158 + s = s.replace( basePrefix, function ( m, p1, p2 ) {
1159 + base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
1160 + return !b || b == base ? p1 : m;
1161 + });
1162 +
1163 + if (b) {
1164 + base = b;
1165 +
1166 + // E.g. '1.' to '1', '.1' to '0.1'
1167 + s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
1168 + }
1169 +
1170 + if ( str != s ) return new BigNumber( s, base );
1171 + }
1172 +
1173 + // 'new BigNumber() not a number: {n}'
1174 + // 'new BigNumber() not a base {b} number: {n}'
1175 + if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
1176 + x.s = null;
1177 + }
1178 +
1179 + x.c = x.e = null;
1180 + id = 0;
1181 + }
1182 + })();
1183 +
1184 +
1185 + // Throw a BigNumber Error.
1186 + function raise( caller, msg, val ) {
1187 + var error = new Error( [
1188 + 'new BigNumber', // 0
1189 + 'cmp', // 1
1190 + 'config', // 2
1191 + 'div', // 3
1192 + 'divToInt', // 4
1193 + 'eq', // 5
1194 + 'gt', // 6
1195 + 'gte', // 7
1196 + 'lt', // 8
1197 + 'lte', // 9
1198 + 'minus', // 10
1199 + 'mod', // 11
1200 + 'plus', // 12
1201 + 'precision', // 13
1202 + 'random', // 14
1203 + 'round', // 15
1204 + 'shift', // 16
1205 + 'times', // 17
1206 + 'toDigits', // 18
1207 + 'toExponential', // 19
1208 + 'toFixed', // 20
1209 + 'toFormat', // 21
1210 + 'toFraction', // 22
1211 + 'pow', // 23
1212 + 'toPrecision', // 24
1213 + 'toString', // 25
1214 + 'BigNumber' // 26
1215 + ][caller] + '() ' + msg + ': ' + val );
1216 +
1217 + error.name = 'BigNumber Error';
1218 + id = 0;
1219 + throw error;
1220 + }
1221 +
1222 +
1223 + /*
1224 + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
1225 + * If r is truthy, it is known that there are more digits after the rounding digit.
1226 + */
1227 + function round( x, sd, rm, r ) {
1228 + var d, i, j, k, n, ni, rd,
1229 + xc = x.c,
1230 + pows10 = POWS_TEN;
1231 +
1232 + // if x is not Infinity or NaN...
1233 + if (xc) {
1234 +
1235 + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
1236 + // n is a base 1e14 number, the value of the element of array x.c containing rd.
1237 + // ni is the index of n within x.c.
1238 + // d is the number of digits of n.
1239 + // i is the index of rd within n including leading zeros.
1240 + // j is the actual index of rd within n (if < 0, rd is a leading zero).
1241 + out: {
1242 +
1243 + // Get the number of digits of the first element of xc.
1244 + for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
1245 + i = sd - d;
1246 +
1247 + // If the rounding digit is in the first element of xc...
1248 + if ( i < 0 ) {
1249 + i += LOG_BASE;
1250 + j = sd;
1251 + n = xc[ ni = 0 ];
1252 +
1253 + // Get the rounding digit at index j of n.
1254 + rd = n / pows10[ d - j - 1 ] % 10 | 0;
1255 + } else {
1256 + ni = mathceil( ( i + 1 ) / LOG_BASE );
1257 +
1258 + if ( ni >= xc.length ) {
1259 +
1260 + if (r) {
1261 +
1262 + // Needed by sqrt.
1263 + for ( ; xc.length <= ni; xc.push(0) );
1264 + n = rd = 0;
1265 + d = 1;
1266 + i %= LOG_BASE;
1267 + j = i - LOG_BASE + 1;
1268 + } else {
1269 + break out;
1270 + }
1271 + } else {
1272 + n = k = xc[ni];
1273 +
1274 + // Get the number of digits of n.
1275 + for ( d = 1; k >= 10; k /= 10, d++ );
1276 +
1277 + // Get the index of rd within n.
1278 + i %= LOG_BASE;
1279 +
1280 + // Get the index of rd within n, adjusted for leading zeros.
1281 + // The number of leading zeros of n is given by LOG_BASE - d.
1282 + j = i - LOG_BASE + d;
1283 +
1284 + // Get the rounding digit at index j of n.
1285 + rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
1286 + }
1287 + }
1288 +
1289 + r = r || sd < 0 ||
1290 +
1291 + // Are there any non-zero digits after the rounding digit?
1292 + // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
1293 + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
1294 + xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
1295 +
1296 + r = rm < 4
1297 + ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
1298 + : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
1299 +
1300 + // Check whether the digit to the left of the rounding digit is odd.
1301 + ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
1302 + rm == ( x.s < 0 ? 8 : 7 ) );
1303 +
1304 + if ( sd < 1 || !xc[0] ) {
1305 + xc.length = 0;
1306 +
1307 + if (r) {
1308 +
1309 + // Convert sd to decimal places.
1310 + sd -= x.e + 1;
1311 +
1312 + // 1, 0.1, 0.01, 0.001, 0.0001 etc.
1313 + xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
1314 + x.e = -sd || 0;
1315 + } else {
1316 +
1317 + // Zero.
1318 + xc[0] = x.e = 0;
1319 + }
1320 +
1321 + return x;
1322 + }
1323 +
1324 + // Remove excess digits.
1325 + if ( i == 0 ) {
1326 + xc.length = ni;
1327 + k = 1;
1328 + ni--;
1329 + } else {
1330 + xc.length = ni + 1;
1331 + k = pows10[ LOG_BASE - i ];
1332 +
1333 + // E.g. 56700 becomes 56000 if 7 is the rounding digit.
1334 + // j > 0 means i > number of leading zeros of n.
1335 + xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
1336 + }
1337 +
1338 + // Round up?
1339 + if (r) {
1340 +
1341 + for ( ; ; ) {
1342 +
1343 + // If the digit to be rounded up is in the first element of xc...
1344 + if ( ni == 0 ) {
1345 +
1346 + // i will be the length of xc[0] before k is added.
1347 + for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
1348 + j = xc[0] += k;
1349 + for ( k = 1; j >= 10; j /= 10, k++ );
1350 +
1351 + // if i != k the length has increased.
1352 + if ( i != k ) {
1353 + x.e++;
1354 + if ( xc[0] == BASE ) xc[0] = 1;
1355 + }
1356 +
1357 + break;
1358 + } else {
1359 + xc[ni] += k;
1360 + if ( xc[ni] != BASE ) break;
1361 + xc[ni--] = 0;
1362 + k = 1;
1363 + }
1364 + }
1365 + }
1366 +
1367 + // Remove trailing zeros.
1368 + for ( i = xc.length; xc[--i] === 0; xc.pop() );
1369 + }
1370 +
1371 + // Overflow? Infinity.
1372 + if ( x.e > MAX_EXP ) {
1373 + x.c = x.e = null;
1374 +
1375 + // Underflow? Zero.
1376 + } else if ( x.e < MIN_EXP ) {
1377 + x.c = [ x.e = 0 ];
1378 + }
1379 + }
1380 +
1381 + return x;
1382 + }
1383 +
1384 +
1385 + // PROTOTYPE/INSTANCE METHODS
1386 +
1387 +
1388 + /*
1389 + * Return a new BigNumber whose value is the absolute value of this BigNumber.
1390 + */
1391 + P.absoluteValue = P.abs = function () {
1392 + var x = new BigNumber(this);
1393 + if ( x.s < 0 ) x.s = 1;
1394 + return x;
1395 + };
1396 +
1397 +
1398 + /*
1399 + * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
1400 + * number in the direction of Infinity.
1401 + */
1402 + P.ceil = function () {
1403 + return round( new BigNumber(this), this.e + 1, 2 );
1404 + };
1405 +
1406 +
1407 + /*
1408 + * Return
1409 + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
1410 + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
1411 + * 0 if they have the same value,
1412 + * or null if the value of either is NaN.
1413 + */
1414 + P.comparedTo = P.cmp = function ( y, b ) {
1415 + id = 1;
1416 + return compare( this, new BigNumber( y, b ) );
1417 + };
1418 +
1419 +
1420 + /*
1421 + * Return the number of decimal places of the value of this BigNumber, or null if the value
1422 + * of this BigNumber is ±Infinity or NaN.
1423 + */
1424 + P.decimalPlaces = P.dp = function () {
1425 + var n, v,
1426 + c = this.c;
1427 +
1428 + if ( !c ) return null;
1429 + n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
1430 +
1431 + // Subtract the number of trailing zeros of the last number.
1432 + if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
1433 + if ( n < 0 ) n = 0;
1434 +
1435 + return n;
1436 + };
1437 +
1438 +
1439 + /*
1440 + * n / 0 = I
1441 + * n / N = N
1442 + * n / I = 0
1443 + * 0 / n = 0
1444 + * 0 / 0 = N
1445 + * 0 / N = N
1446 + * 0 / I = 0
1447 + * N / n = N
1448 + * N / 0 = N
1449 + * N / N = N
1450 + * N / I = N
1451 + * I / n = I
1452 + * I / 0 = I
1453 + * I / N = N
1454 + * I / I = N
1455 + *
1456 + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
1457 + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
1458 + */
1459 + P.dividedBy = P.div = function ( y, b ) {
1460 + id = 3;
1461 + return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
1462 + };
1463 +
1464 +
1465 + /*
1466 + * Return a new BigNumber whose value is the integer part of dividing the value of this
1467 + * BigNumber by the value of BigNumber(y, b).
1468 + */
1469 + P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
1470 + id = 4;
1471 + return div( this, new BigNumber( y, b ), 0, 1 );
1472 + };
1473 +
1474 +
1475 + /*
1476 + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
1477 + * otherwise returns false.
1478 + */
1479 + P.equals = P.eq = function ( y, b ) {
1480 + id = 5;
1481 + return compare( this, new BigNumber( y, b ) ) === 0;
1482 + };
1483 +
1484 +
1485 + /*
1486 + * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
1487 + * number in the direction of -Infinity.
1488 + */
1489 + P.floor = function () {
1490 + return round( new BigNumber(this), this.e + 1, 3 );
1491 + };
1492 +
1493 +
1494 + /*
1495 + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
1496 + * otherwise returns false.
1497 + */
1498 + P.greaterThan = P.gt = function ( y, b ) {
1499 + id = 6;
1500 + return compare( this, new BigNumber( y, b ) ) > 0;
1501 + };
1502 +
1503 +
1504 + /*
1505 + * Return true if the value of this BigNumber is greater than or equal to the value of
1506 + * BigNumber(y, b), otherwise returns false.
1507 + */
1508 + P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
1509 + id = 7;
1510 + return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
1511 +
1512 + };
1513 +
1514 +
1515 + /*
1516 + * Return true if the value of this BigNumber is a finite number, otherwise returns false.
1517 + */
1518 + P.isFinite = function () {
1519 + return !!this.c;
1520 + };
1521 +
1522 +
1523 + /*
1524 + * Return true if the value of this BigNumber is an integer, otherwise return false.
1525 + */
1526 + P.isInteger = P.isInt = function () {
1527 + return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
1528 + };
1529 +
1530 +
1531 + /*
1532 + * Return true if the value of this BigNumber is NaN, otherwise returns false.
1533 + */
1534 + P.isNaN = function () {
1535 + return !this.s;
1536 + };
1537 +
1538 +
1539 + /*
1540 + * Return true if the value of this BigNumber is negative, otherwise returns false.
1541 + */
1542 + P.isNegative = P.isNeg = function () {
1543 + return this.s < 0;
1544 + };
1545 +
1546 +
1547 + /*
1548 + * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
1549 + */
1550 + P.isZero = function () {
1551 + return !!this.c && this.c[0] == 0;
1552 + };
1553 +
1554 +
1555 + /*
1556 + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
1557 + * otherwise returns false.
1558 + */
1559 + P.lessThan = P.lt = function ( y, b ) {
1560 + id = 8;
1561 + return compare( this, new BigNumber( y, b ) ) < 0;
1562 + };
1563 +
1564 +
1565 + /*
1566 + * Return true if the value of this BigNumber is less than or equal to the value of
1567 + * BigNumber(y, b), otherwise returns false.
1568 + */
1569 + P.lessThanOrEqualTo = P.lte = function ( y, b ) {
1570 + id = 9;
1571 + return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
1572 + };
1573 +
1574 +
1575 + /*
1576 + * n - 0 = n
1577 + * n - N = N
1578 + * n - I = -I
1579 + * 0 - n = -n
1580 + * 0 - 0 = 0
1581 + * 0 - N = N
1582 + * 0 - I = -I
1583 + * N - n = N
1584 + * N - 0 = N
1585 + * N - N = N
1586 + * N - I = N
1587 + * I - n = I
1588 + * I - 0 = I
1589 + * I - N = N
1590 + * I - I = N
1591 + *
1592 + * Return a new BigNumber whose value is the value of this BigNumber minus the value of
1593 + * BigNumber(y, b).
1594 + */
1595 + P.minus = P.sub = function ( y, b ) {
1596 + var i, j, t, xLTy,
1597 + x = this,
1598 + a = x.s;
1599 +
1600 + id = 10;
1601 + y = new BigNumber( y, b );
1602 + b = y.s;
1603 +
1604 + // Either NaN?
1605 + if ( !a || !b ) return new BigNumber(NaN);
1606 +
1607 + // Signs differ?
1608 + if ( a != b ) {
1609 + y.s = -b;
1610 + return x.plus(y);
1611 + }
1612 +
1613 + var xe = x.e / LOG_BASE,
1614 + ye = y.e / LOG_BASE,
1615 + xc = x.c,
1616 + yc = y.c;
1617 +
1618 + if ( !xe || !ye ) {
1619 +
1620 + // Either Infinity?
1621 + if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
1622 +
1623 + // Either zero?
1624 + if ( !xc[0] || !yc[0] ) {
1625 +
1626 + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
1627 + return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
1628 +
1629 + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
1630 + ROUNDING_MODE == 3 ? -0 : 0 );
1631 + }
1632 + }
1633 +
1634 + xe = bitFloor(xe);
1635 + ye = bitFloor(ye);
1636 + xc = xc.slice();
1637 +
1638 + // Determine which is the bigger number.
1639 + if ( a = xe - ye ) {
1640 +
1641 + if ( xLTy = a < 0 ) {
1642 + a = -a;
1643 + t = xc;
1644 + } else {
1645 + ye = xe;
1646 + t = yc;
1647 + }
1648 +
1649 + t.reverse();
1650 +
1651 + // Prepend zeros to equalise exponents.
1652 + for ( b = a; b--; t.push(0) );
1653 + t.reverse();
1654 + } else {
1655 +
1656 + // Exponents equal. Check digit by digit.
1657 + j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
1658 +
1659 + for ( a = b = 0; b < j; b++ ) {
1660 +
1661 + if ( xc[b] != yc[b] ) {
1662 + xLTy = xc[b] < yc[b];
1663 + break;
1664 + }
1665 + }
1666 + }
1667 +
1668 + // x < y? Point xc to the array of the bigger number.
1669 + if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
1670 +
1671 + b = ( j = yc.length ) - ( i = xc.length );
1672 +
1673 + // Append zeros to xc if shorter.
1674 + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
1675 + if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
1676 + b = BASE - 1;
1677 +
1678 + // Subtract yc from xc.
1679 + for ( ; j > a; ) {
1680 +
1681 + if ( xc[--j] < yc[j] ) {
1682 + for ( i = j; i && !xc[--i]; xc[i] = b );
1683 + --xc[i];
1684 + xc[j] += BASE;
1685 + }
1686 +
1687 + xc[j] -= yc[j];
1688 + }
1689 +
1690 + // Remove leading zeros and adjust exponent accordingly.
1691 + for ( ; xc[0] == 0; xc.splice(0, 1), --ye );
1692 +
1693 + // Zero?
1694 + if ( !xc[0] ) {
1695 +
1696 + // Following IEEE 754 (2008) 6.3,
1697 + // n - n = +0 but n - n = -0 when rounding towards -Infinity.
1698 + y.s = ROUNDING_MODE == 3 ? -1 : 1;
1699 + y.c = [ y.e = 0 ];
1700 + return y;
1701 + }
1702 +
1703 + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
1704 + // for finite x and y.
1705 + return normalise( y, xc, ye );
1706 + };
1707 +
1708 +
1709 + /*
1710 + * n % 0 = N
1711 + * n % N = N
1712 + * n % I = n
1713 + * 0 % n = 0
1714 + * -0 % n = -0
1715 + * 0 % 0 = N
1716 + * 0 % N = N
1717 + * 0 % I = 0
1718 + * N % n = N
1719 + * N % 0 = N
1720 + * N % N = N
1721 + * N % I = N
1722 + * I % n = N
1723 + * I % 0 = N
1724 + * I % N = N
1725 + * I % I = N
1726 + *
1727 + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
1728 + * BigNumber(y, b). The result depends on the value of MODULO_MODE.
1729 + */
1730 + P.modulo = P.mod = function ( y, b ) {
1731 + var q, s,
1732 + x = this;
1733 +
1734 + id = 11;
1735 + y = new BigNumber( y, b );
1736 +
1737 + // Return NaN if x is Infinity or NaN, or y is NaN or zero.
1738 + if ( !x.c || !y.s || y.c && !y.c[0] ) {
1739 + return new BigNumber(NaN);
1740 +
1741 + // Return x if y is Infinity or x is zero.
1742 + } else if ( !y.c || x.c && !x.c[0] ) {
1743 + return new BigNumber(x);
1744 + }
1745 +
1746 + if ( MODULO_MODE == 9 ) {
1747 +
1748 + // Euclidian division: q = sign(y) * floor(x / abs(y))
1749 + // r = x - qy where 0 <= r < abs(y)
1750 + s = y.s;
1751 + y.s = 1;
1752 + q = div( x, y, 0, 3 );
1753 + y.s = s;
1754 + q.s *= s;
1755 + } else {
1756 + q = div( x, y, 0, MODULO_MODE );
1757 + }
1758 +
1759 + return x.minus( q.times(y) );
1760 + };
1761 +
1762 +
1763 + /*
1764 + * Return a new BigNumber whose value is the value of this BigNumber negated,
1765 + * i.e. multiplied by -1.
1766 + */
1767 + P.negated = P.neg = function () {
1768 + var x = new BigNumber(this);
1769 + x.s = -x.s || null;
1770 + return x;
1771 + };
1772 +
1773 +
1774 + /*
1775 + * n + 0 = n
1776 + * n + N = N
1777 + * n + I = I
1778 + * 0 + n = n
1779 + * 0 + 0 = 0
1780 + * 0 + N = N
1781 + * 0 + I = I
1782 + * N + n = N
1783 + * N + 0 = N
1784 + * N + N = N
1785 + * N + I = N
1786 + * I + n = I
1787 + * I + 0 = I
1788 + * I + N = N
1789 + * I + I = I
1790 + *
1791 + * Return a new BigNumber whose value is the value of this BigNumber plus the value of
1792 + * BigNumber(y, b).
1793 + */
1794 + P.plus = P.add = function ( y, b ) {
1795 + var t,
1796 + x = this,
1797 + a = x.s;
1798 +
1799 + id = 12;
1800 + y = new BigNumber( y, b );
1801 + b = y.s;
1802 +
1803 + // Either NaN?
1804 + if ( !a || !b ) return new BigNumber(NaN);
1805 +
1806 + // Signs differ?
1807 + if ( a != b ) {
1808 + y.s = -b;
1809 + return x.minus(y);
1810 + }
1811 +
1812 + var xe = x.e / LOG_BASE,
1813 + ye = y.e / LOG_BASE,
1814 + xc = x.c,
1815 + yc = y.c;
1816 +
1817 + if ( !xe || !ye ) {
1818 +
1819 + // Return ±Infinity if either ±Infinity.
1820 + if ( !xc || !yc ) return new BigNumber( a / 0 );
1821 +
1822 + // Either zero?
1823 + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
1824 + if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
1825 + }
1826 +
1827 + xe = bitFloor(xe);
1828 + ye = bitFloor(ye);
1829 + xc = xc.slice();
1830 +
1831 + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
1832 + if ( a = xe - ye ) {
1833 + if ( a > 0 ) {
1834 + ye = xe;
1835 + t = yc;
1836 + } else {
1837 + a = -a;
1838 + t = xc;
1839 + }
1840 +
1841 + t.reverse();
1842 + for ( ; a--; t.push(0) );
1843 + t.reverse();
1844 + }
1845 +
1846 + a = xc.length;
1847 + b = yc.length;
1848 +
1849 + // Point xc to the longer array, and b to the shorter length.
1850 + if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
1851 +
1852 + // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
1853 + for ( a = 0; b; ) {
1854 + a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
1855 + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
1856 + }
1857 +
1858 + if (a) {
1859 + xc = [a].concat(xc);
1860 + ++ye;
1861 + }
1862 +
1863 + // No need to check for zero, as +x + +y != 0 && -x + -y != 0
1864 + // ye = MAX_EXP + 1 possible
1865 + return normalise( y, xc, ye );
1866 + };
1867 +
1868 +
1869 + /*
1870 + * Return the number of significant digits of the value of this BigNumber.
1871 + *
1872 + * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
1873 + */
1874 + P.precision = P.sd = function (z) {
1875 + var n, v,
1876 + x = this,
1877 + c = x.c;
1878 +
1879 + // 'precision() argument not a boolean or binary digit: {z}'
1880 + if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
1881 + if (ERRORS) raise( 13, 'argument' + notBool, z );
1882 + if ( z != !!z ) z = null;
1883 + }
1884 +
1885 + if ( !c ) return null;
1886 + v = c.length - 1;
1887 + n = v * LOG_BASE + 1;
1888 +
1889 + if ( v = c[v] ) {
1890 +
1891 + // Subtract the number of trailing zeros of the last element.
1892 + for ( ; v % 10 == 0; v /= 10, n-- );
1893 +
1894 + // Add the number of digits of the first element.
1895 + for ( v = c[0]; v >= 10; v /= 10, n++ );
1896 + }
1897 +
1898 + if ( z && x.e + 1 > n ) n = x.e + 1;
1899 +
1900 + return n;
1901 + };
1902 +
1903 +
1904 + /*
1905 + * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
1906 + * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
1907 + * omitted.
1908 + *
1909 + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
1910 + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
1911 + *
1912 + * 'round() decimal places out of range: {dp}'
1913 + * 'round() decimal places not an integer: {dp}'
1914 + * 'round() rounding mode not an integer: {rm}'
1915 + * 'round() rounding mode out of range: {rm}'
1916 + */
1917 + P.round = function ( dp, rm ) {
1918 + var n = new BigNumber(this);
1919 +
1920 + if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
1921 + round( n, ~~dp + this.e + 1, rm == null ||
1922 + !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
1923 + }
1924 +
1925 + return n;
1926 + };
1927 +
1928 +
1929 + /*
1930 + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
1931 + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
1932 + *
1933 + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
1934 + *
1935 + * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
1936 + * otherwise.
1937 + *
1938 + * 'shift() argument not an integer: {k}'
1939 + * 'shift() argument out of range: {k}'
1940 + */
1941 + P.shift = function (k) {
1942 + var n = this;
1943 + return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
1944 +
1945 + // k < 1e+21, or truncate(k) will produce exponential notation.
1946 + ? n.times( '1e' + truncate(k) )
1947 + : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
1948 + ? n.s * ( k < 0 ? 0 : 1 / 0 )
1949 + : n );
1950 + };
1951 +
1952 +
1953 + /*
1954 + * sqrt(-n) = N
1955 + * sqrt( N) = N
1956 + * sqrt(-I) = N
1957 + * sqrt( I) = I
1958 + * sqrt( 0) = 0
1959 + * sqrt(-0) = -0
1960 + *
1961 + * Return a new BigNumber whose value is the square root of the value of this BigNumber,
1962 + * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
1963 + */
1964 + P.squareRoot = P.sqrt = function () {
1965 + var m, n, r, rep, t,
1966 + x = this,
1967 + c = x.c,
1968 + s = x.s,
1969 + e = x.e,
1970 + dp = DECIMAL_PLACES + 4,
1971 + half = new BigNumber('0.5');
1972 +
1973 + // Negative/NaN/Infinity/zero?
1974 + if ( s !== 1 || !c || !c[0] ) {
1975 + return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
1976 + }
1977 +
1978 + // Initial estimate.
1979 + s = Math.sqrt( +x );
1980 +
1981 + // Math.sqrt underflow/overflow?
1982 + // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
1983 + if ( s == 0 || s == 1 / 0 ) {
1984 + n = coeffToString(c);
1985 + if ( ( n.length + e ) % 2 == 0 ) n += '0';
1986 + s = Math.sqrt(n);
1987 + e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
1988 +
1989 + if ( s == 1 / 0 ) {
1990 + n = '1e' + e;
1991 + } else {
1992 + n = s.toExponential();
1993 + n = n.slice( 0, n.indexOf('e') + 1 ) + e;
1994 + }
1995 +
1996 + r = new BigNumber(n);
1997 + } else {
1998 + r = new BigNumber( s + '' );
1999 + }
2000 +
2001 + // Check for zero.
2002 + // r could be zero if MIN_EXP is changed after the this value was created.
2003 + // This would cause a division by zero (x/t) and hence Infinity below, which would cause
2004 + // coeffToString to throw.
2005 + if ( r.c[0] ) {
2006 + e = r.e;
2007 + s = e + dp;
2008 + if ( s < 3 ) s = 0;
2009 +
2010 + // Newton-Raphson iteration.
2011 + for ( ; ; ) {
2012 + t = r;
2013 + r = half.times( t.plus( div( x, t, dp, 1 ) ) );
2014 +
2015 + if ( coeffToString( t.c ).slice( 0, s ) === ( n =
2016 + coeffToString( r.c ) ).slice( 0, s ) ) {
2017 +
2018 + // The exponent of r may here be one less than the final result exponent,
2019 + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
2020 + // are indexed correctly.
2021 + if ( r.e < e ) --s;
2022 + n = n.slice( s - 3, s + 1 );
2023 +
2024 + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
2025 + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
2026 + // iteration.
2027 + if ( n == '9999' || !rep && n == '4999' ) {
2028 +
2029 + // On the first iteration only, check to see if rounding up gives the
2030 + // exact result as the nines may infinitely repeat.
2031 + if ( !rep ) {
2032 + round( t, t.e + DECIMAL_PLACES + 2, 0 );
2033 +
2034 + if ( t.times(t).eq(x) ) {
2035 + r = t;
2036 + break;
2037 + }
2038 + }
2039 +
2040 + dp += 4;
2041 + s += 4;
2042 + rep = 1;
2043 + } else {
2044 +
2045 + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
2046 + // result. If not, then there are further digits and m will be truthy.
2047 + if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
2048 +
2049 + // Truncate to the first rounding digit.
2050 + round( r, r.e + DECIMAL_PLACES + 2, 1 );
2051 + m = !r.times(r).eq(x);
2052 + }
2053 +
2054 + break;
2055 + }
2056 + }
2057 + }
2058 + }
2059 +
2060 + return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
2061 + };
2062 +
2063 +
2064 + /*
2065 + * n * 0 = 0
2066 + * n * N = N
2067 + * n * I = I
2068 + * 0 * n = 0
2069 + * 0 * 0 = 0
2070 + * 0 * N = N
2071 + * 0 * I = N
2072 + * N * n = N
2073 + * N * 0 = N
2074 + * N * N = N
2075 + * N * I = N
2076 + * I * n = I
2077 + * I * 0 = N
2078 + * I * N = N
2079 + * I * I = I
2080 + *
2081 + * Return a new BigNumber whose value is the value of this BigNumber times the value of
2082 + * BigNumber(y, b).
2083 + */
2084 + P.times = P.mul = function ( y, b ) {
2085 + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
2086 + base, sqrtBase,
2087 + x = this,
2088 + xc = x.c,
2089 + yc = ( id = 17, y = new BigNumber( y, b ) ).c;
2090 +
2091 + // Either NaN, ±Infinity or ±0?
2092 + if ( !xc || !yc || !xc[0] || !yc[0] ) {
2093 +
2094 + // Return NaN if either is NaN, or one is 0 and the other is Infinity.
2095 + if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
2096 + y.c = y.e = y.s = null;
2097 + } else {
2098 + y.s *= x.s;
2099 +
2100 + // Return ±Infinity if either is ±Infinity.
2101 + if ( !xc || !yc ) {
2102 + y.c = y.e = null;
2103 +
2104 + // Return ±0 if either is ±0.
2105 + } else {
2106 + y.c = [0];
2107 + y.e = 0;
2108 + }
2109 + }
2110 +
2111 + return y;
2112 + }
2113 +
2114 + e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
2115 + y.s *= x.s;
2116 + xcL = xc.length;
2117 + ycL = yc.length;
2118 +
2119 + // Ensure xc points to longer array and xcL to its length.
2120 + if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
2121 +
2122 + // Initialise the result array with zeros.
2123 + for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
2124 +
2125 + base = BASE;
2126 + sqrtBase = SQRT_BASE;
2127 +
2128 + for ( i = ycL; --i >= 0; ) {
2129 + c = 0;
2130 + ylo = yc[i] % sqrtBase;
2131 + yhi = yc[i] / sqrtBase | 0;
2132 +
2133 + for ( k = xcL, j = i + k; j > i; ) {
2134 + xlo = xc[--k] % sqrtBase;
2135 + xhi = xc[k] / sqrtBase | 0;
2136 + m = yhi * xlo + xhi * ylo;
2137 + xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
2138 + c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
2139 + zc[j--] = xlo % base;
2140 + }
2141 +
2142 + zc[j] = c;
2143 + }
2144 +
2145 + if (c) {
2146 + ++e;
2147 + } else {
2148 + zc.splice(0, 1);
2149 + }
2150 +
2151 + return normalise( y, zc, e );
2152 + };
2153 +
2154 +
2155 + /*
2156 + * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
2157 + * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
2158 + *
2159 + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
2160 + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
2161 + *
2162 + * 'toDigits() precision out of range: {sd}'
2163 + * 'toDigits() precision not an integer: {sd}'
2164 + * 'toDigits() rounding mode not an integer: {rm}'
2165 + * 'toDigits() rounding mode out of range: {rm}'
2166 + */
2167 + P.toDigits = function ( sd, rm ) {
2168 + var n = new BigNumber(this);
2169 + sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
2170 + rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
2171 + return sd ? round( n, sd, rm ) : n;
2172 + };
2173 +
2174 +
2175 + /*
2176 + * Return a string representing the value of this BigNumber in exponential notation and
2177 + * rounded using ROUNDING_MODE to dp fixed decimal places.
2178 + *
2179 + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
2180 + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
2181 + *
2182 + * 'toExponential() decimal places not an integer: {dp}'
2183 + * 'toExponential() decimal places out of range: {dp}'
2184 + * 'toExponential() rounding mode not an integer: {rm}'
2185 + * 'toExponential() rounding mode out of range: {rm}'
2186 + */
2187 + P.toExponential = function ( dp, rm ) {
2188 + return format( this,
2189 + dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
2190 + };
2191 +
2192 +
2193 + /*
2194 + * Return a string representing the value of this BigNumber in fixed-point notation rounding
2195 + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
2196 + *
2197 + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
2198 + * but e.g. (-0.00001).toFixed(0) is '-0'.
2199 + *
2200 + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
2201 + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
2202 + *
2203 + * 'toFixed() decimal places not an integer: {dp}'
2204 + * 'toFixed() decimal places out of range: {dp}'
2205 + * 'toFixed() rounding mode not an integer: {rm}'
2206 + * 'toFixed() rounding mode out of range: {rm}'
2207 + */
2208 + P.toFixed = function ( dp, rm ) {
2209 + return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
2210 + ? ~~dp + this.e + 1 : null, rm, 20 );
2211 + };
2212 +
2213 +
2214 + /*
2215 + * Return a string representing the value of this BigNumber in fixed-point notation rounded
2216 + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
2217 + * of the FORMAT object (see BigNumber.config).
2218 + *
2219 + * FORMAT = {
2220 + * decimalSeparator : '.',
2221 + * groupSeparator : ',',
2222 + * groupSize : 3,
2223 + * secondaryGroupSize : 0,
2224 + * fractionGroupSeparator : '\xA0', // non-breaking space
2225 + * fractionGroupSize : 0
2226 + * };
2227 + *
2228 + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
2229 + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
2230 + *
2231 + * 'toFormat() decimal places not an integer: {dp}'
2232 + * 'toFormat() decimal places out of range: {dp}'
2233 + * 'toFormat() rounding mode not an integer: {rm}'
2234 + * 'toFormat() rounding mode out of range: {rm}'
2235 + */
2236 + P.toFormat = function ( dp, rm ) {
2237 + var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
2238 + ? ~~dp + this.e + 1 : null, rm, 21 );
2239 +
2240 + if ( this.c ) {
2241 + var i,
2242 + arr = str.split('.'),
2243 + g1 = +FORMAT.groupSize,
2244 + g2 = +FORMAT.secondaryGroupSize,
2245 + groupSeparator = FORMAT.groupSeparator,
2246 + intPart = arr[0],
2247 + fractionPart = arr[1],
2248 + isNeg = this.s < 0,
2249 + intDigits = isNeg ? intPart.slice(1) : intPart,
2250 + len = intDigits.length;
2251 +
2252 + if (g2) i = g1, g1 = g2, g2 = i, len -= i;
2253 +
2254 + if ( g1 > 0 && len > 0 ) {
2255 + i = len % g1 || g1;
2256 + intPart = intDigits.substr( 0, i );
2257 +
2258 + for ( ; i < len; i += g1 ) {
2259 + intPart += groupSeparator + intDigits.substr( i, g1 );
2260 + }
2261 +
2262 + if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
2263 + if (isNeg) intPart = '-' + intPart;
2264 + }
2265 +
2266 + str = fractionPart
2267 + ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
2268 + ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
2269 + '$&' + FORMAT.fractionGroupSeparator )
2270 + : fractionPart )
2271 + : intPart;
2272 + }
2273 +
2274 + return str;
2275 + };
2276 +
2277 +
2278 + /*
2279 + * Return a string array representing the value of this BigNumber as a simple fraction with
2280 + * an integer numerator and an integer denominator. The denominator will be a positive
2281 + * non-zero value less than or equal to the specified maximum denominator. If a maximum
2282 + * denominator is not specified, the denominator will be the lowest value necessary to
2283 + * represent the number exactly.
2284 + *
2285 + * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
2286 + *
2287 + * 'toFraction() max denominator not an integer: {md}'
2288 + * 'toFraction() max denominator out of range: {md}'
2289 + */
2290 + P.toFraction = function (md) {
2291 + var arr, d0, d2, e, exp, n, n0, q, s,
2292 + k = ERRORS,
2293 + x = this,
2294 + xc = x.c,
2295 + d = new BigNumber(ONE),
2296 + n1 = d0 = new BigNumber(ONE),
2297 + d1 = n0 = new BigNumber(ONE);
2298 +
2299 + if ( md != null ) {
2300 + ERRORS = false;
2301 + n = new BigNumber(md);
2302 + ERRORS = k;
2303 +
2304 + if ( !( k = n.isInt() ) || n.lt(ONE) ) {
2305 +
2306 + if (ERRORS) {
2307 + raise( 22,
2308 + 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
2309 + }
2310 +
2311 + // ERRORS is false:
2312 + // If md is a finite non-integer >= 1, round it to an integer and use it.
2313 + md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
2314 + }
2315 + }
2316 +
2317 + if ( !xc ) return x.toString();
2318 + s = coeffToString(xc);
2319 +
2320 + // Determine initial denominator.
2321 + // d is a power of 10 and the minimum max denominator that specifies the value exactly.
2322 + e = d.e = s.length - x.e - 1;
2323 + d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
2324 + md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
2325 +
2326 + exp = MAX_EXP;
2327 + MAX_EXP = 1 / 0;
2328 + n = new BigNumber(s);
2329 +
2330 + // n0 = d1 = 0
2331 + n0.c[0] = 0;
2332 +
2333 + for ( ; ; ) {
2334 + q = div( n, d, 0, 1 );
2335 + d2 = d0.plus( q.times(d1) );
2336 + if ( d2.cmp(md) == 1 ) break;
2337 + d0 = d1;
2338 + d1 = d2;
2339 + n1 = n0.plus( q.times( d2 = n1 ) );
2340 + n0 = d2;
2341 + d = n.minus( q.times( d2 = d ) );
2342 + n = d2;
2343 + }
2344 +
2345 + d2 = div( md.minus(d0), d1, 0, 1 );
2346 + n0 = n0.plus( d2.times(n1) );
2347 + d0 = d0.plus( d2.times(d1) );
2348 + n0.s = n1.s = x.s;
2349 + e *= 2;
2350 +
2351 + // Determine which fraction is closer to x, n0/d0 or n1/d1
2352 + arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
2353 + div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
2354 + ? [ n1.toString(), d1.toString() ]
2355 + : [ n0.toString(), d0.toString() ];
2356 +
2357 + MAX_EXP = exp;
2358 + return arr;
2359 + };
2360 +
2361 +
2362 + /*
2363 + * Return the value of this BigNumber converted to a number primitive.
2364 + */
2365 + P.toNumber = function () {
2366 + return +this;
2367 + };
2368 +
2369 +
2370 + /*
2371 + * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
2372 + * If m is present, return the result modulo m.
2373 + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
2374 + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
2375 + * ROUNDING_MODE.
2376 + *
2377 + * The modular power operation works efficiently when x, n, and m are positive integers,
2378 + * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
2379 + *
2380 + * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
2381 + * [m] {number|string|BigNumber} The modulus.
2382 + *
2383 + * 'pow() exponent not an integer: {n}'
2384 + * 'pow() exponent out of range: {n}'
2385 + *
2386 + * Performs 54 loop iterations for n of 9007199254740991.
2387 + */
2388 + P.toPower = P.pow = function ( n, m ) {
2389 + var k, y, z,
2390 + i = mathfloor( n < 0 ? -n : +n ),
2391 + x = this;
2392 +
2393 + if ( m != null ) {
2394 + id = 23;
2395 + m = new BigNumber(m);
2396 + }
2397 +
2398 + // Pass ±Infinity to Math.pow if exponent is out of range.
2399 + if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
2400 + ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
2401 + parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {
2402 + k = Math.pow( +x, n );
2403 + return new BigNumber( m ? k % m : k );
2404 + }
2405 +
2406 + if (m) {
2407 + if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {
2408 + x = x.mod(m);
2409 + } else {
2410 + z = m;
2411 +
2412 + // Nullify m so only a single mod operation is performed at the end.
2413 + m = null;
2414 + }
2415 + } else if (POW_PRECISION) {
2416 +
2417 + // Truncating each coefficient array to a length of k after each multiplication
2418 + // equates to truncating significant digits to POW_PRECISION + [28, 41],
2419 + // i.e. there will be a minimum of 28 guard digits retained.
2420 + // (Using + 1.5 would give [9, 21] guard digits.)
2421 + k = mathceil( POW_PRECISION / LOG_BASE + 2 );
2422 + }
2423 +
2424 + y = new BigNumber(ONE);
2425 +
2426 + for ( ; ; ) {
2427 + if ( i % 2 ) {
2428 + y = y.times(x);
2429 + if ( !y.c ) break;
2430 + if (k) {
2431 + if ( y.c.length > k ) y.c.length = k;
2432 + } else if (m) {
2433 + y = y.mod(m);
2434 + }
2435 + }
2436 +
2437 + i = mathfloor( i / 2 );
2438 + if ( !i ) break;
2439 + x = x.times(x);
2440 + if (k) {
2441 + if ( x.c && x.c.length > k ) x.c.length = k;
2442 + } else if (m) {
2443 + x = x.mod(m);
2444 + }
2445 + }
2446 +
2447 + if (m) return y;
2448 + if ( n < 0 ) y = ONE.div(y);
2449 +
2450 + return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
2451 + };
2452 +
2453 +
2454 + /*
2455 + * Return a string representing the value of this BigNumber rounded to sd significant digits
2456 + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
2457 + * necessary to represent the integer part of the value in fixed-point notation, then use
2458 + * exponential notation.
2459 + *
2460 + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
2461 + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
2462 + *
2463 + * 'toPrecision() precision not an integer: {sd}'
2464 + * 'toPrecision() precision out of range: {sd}'
2465 + * 'toPrecision() rounding mode not an integer: {rm}'
2466 + * 'toPrecision() rounding mode out of range: {rm}'
2467 + */
2468 + P.toPrecision = function ( sd, rm ) {
2469 + return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
2470 + ? sd | 0 : null, rm, 24 );
2471 + };
2472 +
2473 +
2474 + /*
2475 + * Return a string representing the value of this BigNumber in base b, or base 10 if b is
2476 + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
2477 + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
2478 + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
2479 + * TO_EXP_NEG, return exponential notation.
2480 + *
2481 + * [b] {number} Integer, 2 to 64 inclusive.
2482 + *
2483 + * 'toString() base not an integer: {b}'
2484 + * 'toString() base out of range: {b}'
2485 + */
2486 + P.toString = function (b) {
2487 + var str,
2488 + n = this,
2489 + s = n.s,
2490 + e = n.e;
2491 +
2492 + // Infinity or NaN?
2493 + if ( e === null ) {
2494 +
2495 + if (s) {
2496 + str = 'Infinity';
2497 + if ( s < 0 ) str = '-' + str;
2498 + } else {
2499 + str = 'NaN';
2500 + }
2501 + } else {
2502 + str = coeffToString( n.c );
2503 +
2504 + if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
2505 + str = e <= TO_EXP_NEG || e >= TO_EXP_POS
2506 + ? toExponential( str, e )
2507 + : toFixedPoint( str, e );
2508 + } else {
2509 + str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
2510 + }
2511 +
2512 + if ( s < 0 && n.c[0] ) str = '-' + str;
2513 + }
2514 +
2515 + return str;
2516 + };
2517 +
2518 +
2519 + /*
2520 + * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
2521 + * number.
2522 + */
2523 + P.truncated = P.trunc = function () {
2524 + return round( new BigNumber(this), this.e + 1, 1 );
2525 + };
2526 +
2527 +
2528 + /*
2529 + * Return as toString, but do not accept a base argument, and include the minus sign for
2530 + * negative zero.
2531 + */
2532 + P.valueOf = P.toJSON = function () {
2533 + var str,
2534 + n = this,
2535 + e = n.e;
2536 +
2537 + if ( e === null ) return n.toString();
2538 +
2539 + str = coeffToString( n.c );
2540 +
2541 + str = e <= TO_EXP_NEG || e >= TO_EXP_POS
2542 + ? toExponential( str, e )
2543 + : toFixedPoint( str, e );
2544 +
2545 + return n.s < 0 ? '-' + str : str;
2546 + };
2547 +
2548 +
2549 + P.isBigNumber = true;
2550 +
2551 + if ( config != null ) BigNumber.config(config);
2552 +
2553 + return BigNumber;
2554 +}
2555 +
2556 +
2557 +// PRIVATE HELPER FUNCTIONS
2558 +
2559 +
2560 +function bitFloor(n) {
2561 + var i = n | 0;
2562 + return n > 0 || n === i ? i : i - 1;
2563 +}
2564 +
2565 +
2566 +// Return a coefficient array as a string of base 10 digits.
2567 +function coeffToString(a) {
2568 + var s, z,
2569 + i = 1,
2570 + j = a.length,
2571 + r = a[0] + '';
2572 +
2573 + for ( ; i < j; ) {
2574 + s = a[i++] + '';
2575 + z = LOG_BASE - s.length;
2576 + for ( ; z--; s = '0' + s );
2577 + r += s;
2578 + }
2579 +
2580 + // Determine trailing zeros.
2581 + for ( j = r.length; r.charCodeAt(--j) === 48; );
2582 + return r.slice( 0, j + 1 || 1 );
2583 +}
2584 +
2585 +
2586 +// Compare the value of BigNumbers x and y.
2587 +function compare( x, y ) {
2588 + var a, b,
2589 + xc = x.c,
2590 + yc = y.c,
2591 + i = x.s,
2592 + j = y.s,
2593 + k = x.e,
2594 + l = y.e;
2595 +
2596 + // Either NaN?
2597 + if ( !i || !j ) return null;
2598 +
2599 + a = xc && !xc[0];
2600 + b = yc && !yc[0];
2601 +
2602 + // Either zero?
2603 + if ( a || b ) return a ? b ? 0 : -j : i;
2604 +
2605 + // Signs differ?
2606 + if ( i != j ) return i;
2607 +
2608 + a = i < 0;
2609 + b = k == l;
2610 +
2611 + // Either Infinity?
2612 + if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
2613 +
2614 + // Compare exponents.
2615 + if ( !b ) return k > l ^ a ? 1 : -1;
2616 +
2617 + j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
2618 +
2619 + // Compare digit by digit.
2620 + for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
2621 +
2622 + // Compare lengths.
2623 + return k == l ? 0 : k > l ^ a ? 1 : -1;
2624 +}
2625 +
2626 +
2627 +/*
2628 + * Return true if n is a valid number in range, otherwise false.
2629 + * Use for argument validation when ERRORS is false.
2630 + * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
2631 + */
2632 +function intValidatorNoErrors( n, min, max ) {
2633 + return ( n = truncate(n) ) >= min && n <= max;
2634 +}
2635 +
2636 +
2637 +function isArray(obj) {
2638 + return Object.prototype.toString.call(obj) == '[object Array]';
2639 +}
2640 +
2641 +
2642 +/*
2643 + * Convert string of baseIn to an array of numbers of baseOut.
2644 + * Eg. convertBase('255', 10, 16) returns [15, 15].
2645 + * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
2646 + */
2647 +function toBaseOut( str, baseIn, baseOut ) {
2648 + var j,
2649 + arr = [0],
2650 + arrL,
2651 + i = 0,
2652 + len = str.length;
2653 +
2654 + for ( ; i < len; ) {
2655 + for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
2656 + arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
2657 +
2658 + for ( ; j < arr.length; j++ ) {
2659 +
2660 + if ( arr[j] > baseOut - 1 ) {
2661 + if ( arr[j + 1] == null ) arr[j + 1] = 0;
2662 + arr[j + 1] += arr[j] / baseOut | 0;
2663 + arr[j] %= baseOut;
2664 + }
2665 + }
2666 + }
2667 +
2668 + return arr.reverse();
2669 +}
2670 +
2671 +
2672 +function toExponential( str, e ) {
2673 + return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
2674 + ( e < 0 ? 'e' : 'e+' ) + e;
2675 +}
2676 +
2677 +
2678 +function toFixedPoint( str, e ) {
2679 + var len, z;
2680 +
2681 + // Negative exponent?
2682 + if ( e < 0 ) {
2683 +
2684 + // Prepend zeros.
2685 + for ( z = '0.'; ++e; z += '0' );
2686 + str = z + str;
2687 +
2688 + // Positive exponent
2689 + } else {
2690 + len = str.length;
2691 +
2692 + // Append zeros.
2693 + if ( ++e > len ) {
2694 + for ( z = '0', e -= len; --e; z += '0' );
2695 + str += z;
2696 + } else if ( e < len ) {
2697 + str = str.slice( 0, e ) + '.' + str.slice(e);
2698 + }
2699 + }
2700 +
2701 + return str;
2702 +}
2703 +
2704 +
2705 +function truncate(n) {
2706 + n = parseFloat(n);
2707 + return n < 0 ? mathceil(n) : mathfloor(n);
2708 +}
2709 +
2710 +
2711 +// EXPORT
2712 +
2713 +
2714 +BigNumber = constructorFactory();
2715 +BigNumber['default'] = BigNumber.BigNumber = BigNumber;
2716 +
2717 +export default BigNumber;
1 +{
2 + "name": "bignumber.js",
3 + "main": "bignumber.js",
4 + "version": "4.1.0",
5 + "homepage": "https://github.com/MikeMcl/bignumber.js",
6 + "authors": [
7 + "Michael Mclaughlin <M8ch88l@gmail.com>"
8 + ],
9 + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
10 + "moduleType": [
11 + "amd",
12 + "globals",
13 + "node"
14 + ],
15 + "keywords": [
16 + "arbitrary",
17 + "precision",
18 + "arithmetic",
19 + "big",
20 + "number",
21 + "decimal",
22 + "float",
23 + "biginteger",
24 + "bigdecimal",
25 + "bignumber",
26 + "bigint",
27 + "bignum"
28 + ],
29 + "license": "MIT",
30 + "ignore": [
31 + ".*",
32 + "*.json",
33 + "test"
34 + ]
35 +}
36 +
1 +<!DOCTYPE HTML>
2 +<html>
3 +<head>
4 +<meta charset="utf-8">
5 +<meta http-equiv="X-UA-Compatible" content="IE=edge">
6 +<meta name="Author" content="M Mclaughlin">
7 +<title>bignumber.js API</title>
8 +<style>
9 +html{font-size:100%}
10 +body{background:#fff;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;
11 + line-height:1.65em;min-height:100%;margin:0}
12 +body,i{color:#000}
13 +.nav{background:#fff;position:fixed;top:0;bottom:0;left:0;width:200px;overflow-y:auto;
14 + padding:15px 0 30px 15px}
15 +div.container{width:600px;margin:50px 0 50px 240px}
16 +p{margin:0 0 1em;width:600px}
17 +pre,ul{margin:1em 0}
18 +h1,h2,h3,h4,h5{margin:0;padding:1.5em 0 0}
19 +h1,h2{padding:.75em 0}
20 +h1{font:400 3em Verdana,sans-serif;color:#000;margin-bottom:1em}
21 +h2{font-size:2.25em;color:#ff2a00}
22 +h3{font-size:1.75em;color:#4dc71f}
23 +h4{font-size:1.75em;color:#ff2a00;padding-bottom:.75em}
24 +h5{font-size:1.2em;margin-bottom:.4em}
25 +h6{font-size:1.1em;margin-bottom:0.8em;padding:0.5em 0}
26 +dd{padding-top:.35em}
27 +dt{padding-top:.5em}
28 +b{font-weight:700}
29 +dt b{font-size:1.3em}
30 +a,a:visited{color:#ff2a00;text-decoration:none}
31 +a:active,a:hover{outline:0;text-decoration:underline}
32 +.nav a,.nav b,.nav a:visited{display:block;color:#ff2a00;font-weight:700; margin-top:15px}
33 +.nav b{color:#4dc71f;margin-top:20px;cursor:default;width:auto}
34 +ul{list-style-type:none;padding:0 0 0 20px}
35 +.nav ul{line-height:14px;padding-left:0;margin:5px 0 0}
36 +.nav ul a,.nav ul a:visited,span{display:inline;color:#000;font-family:Verdana,Geneva,sans-serif;
37 + font-size:11px;font-weight:400;margin:0}
38 +.inset,ul.inset{margin-left:20px}
39 +.inset{font-size:.9em}
40 +.nav li{width:auto;margin:0 0 3px}
41 +.alias{font-style:italic;margin-left:20px}
42 +table{border-collapse:collapse;border-spacing:0;border:2px solid #a7dbd8;margin:1.75em 0;padding:0}
43 +td,th{text-align:left;margin:0;padding:2px 5px;border:1px dotted #a7dbd8}
44 +th{border-top:2px solid #a7dbd8;border-bottom:2px solid #a7dbd8;color:#ff2a00}
45 +code,pre{font-family:Consolas, monaco, monospace;font-weight:400}
46 +pre{background:#f5f5f5;white-space:pre-wrap;word-wrap:break-word;border-left:5px solid #abef98;
47 + padding:1px 0 1px 15px;margin:1.2em 0}
48 +code,.nav-title{color:#ff2a00}
49 +.end{margin-bottom:25px}
50 +.centre{text-align:center}
51 +.error-table{font-size:13px;width:100%}
52 +#faq{margin:3em 0 0}
53 +li span{float:right;margin-right:10px;color:#c0c0c0}
54 +#js{font:inherit;color:#4dc71f}
55 +</style>
56 +</head>
57 +<body>
58 +
59 + <div class="nav">
60 +
61 + <a class='nav-title' href="#">API</a>
62 +
63 + <b> CONSTRUCTOR </b>
64 + <ul>
65 + <li><a href="#bignumber">BigNumber</a></li>
66 + </ul>
67 +
68 + <a href="#methods">Methods</a>
69 + <ul>
70 + <li><a href="#another">another</a></li>
71 + <li><a href="#config" >config</a></li>
72 + <li>
73 + <ul class="inset">
74 + <li><a href="#decimal-places">DECIMAL_PLACES</a></li>
75 + <li><a href="#rounding-mode" >ROUNDING_MODE</a></li>
76 + <li><a href="#exponential-at">EXPONENTIAL_AT</a></li>
77 + <li><a href="#range" >RANGE</a></li>
78 + <li><a href="#errors" >ERRORS</a></li>
79 + <li><a href="#crypto" >CRYPTO</a></li>
80 + <li><a href="#modulo-mode" >MODULO_MODE</a></li>
81 + <li><a href="#pow-precision" >POW_PRECISION</a></li>
82 + <li><a href="#format" >FORMAT</a></li>
83 + </ul>
84 + </li>
85 + <li><a href="#max" >max</a></li>
86 + <li><a href="#min" >min</a></li>
87 + <li><a href="#random">random</a></li>
88 + </ul>
89 +
90 + <a href="#constructor-properties">Properties</a>
91 + <ul>
92 + <li><a href="#round-up" >ROUND_UP</a></li>
93 + <li><a href="#round-down" >ROUND_DOWN</a></li>
94 + <li><a href="#round-ceil" >ROUND_CEIL</a></li>
95 + <li><a href="#round-floor" >ROUND_FLOOR</a></li>
96 + <li><a href="#round-half-up" >ROUND_HALF_UP</a></li>
97 + <li><a href="#round-half-down" >ROUND_HALF_DOWN</a></li>
98 + <li><a href="#round-half-even" >ROUND_HALF_EVEN</a></li>
99 + <li><a href="#round-half-ceil" >ROUND_HALF_CEIL</a></li>
100 + <li><a href="#round-half-floor">ROUND_HALF_FLOOR</a></li>
101 + </ul>
102 +
103 + <b> INSTANCE </b>
104 +
105 + <a href="#prototype-methods">Methods</a>
106 + <ul>
107 + <li><a href="#abs" >absoluteValue </a><span>abs</span> </li>
108 + <li><a href="#ceil" >ceil </a> </li>
109 + <li><a href="#cmp" >comparedTo </a><span>cmp</span> </li>
110 + <li><a href="#dp" >decimalPlaces </a><span>dp</span> </li>
111 + <li><a href="#div" >dividedBy </a><span>div</span> </li>
112 + <li><a href="#divInt" >dividedToIntegerBy </a><span>divToInt</span></li>
113 + <li><a href="#eq" >equals </a><span>eq</span> </li>
114 + <li><a href="#floor" >floor </a> </li>
115 + <li><a href="#gt" >greaterThan </a><span>gt</span> </li>
116 + <li><a href="#gte" >greaterThanOrEqualTo</a><span>gte</span> </li>
117 + <li><a href="#isF" >isFinite </a> </li>
118 + <li><a href="#isInt" >isInteger </a><span>isInt</span> </li>
119 + <li><a href="#isNaN" >isNaN </a> </li>
120 + <li><a href="#isNeg" >isNegative </a><span>isNeg</span> </li>
121 + <li><a href="#isZ" >isZero </a> </li>
122 + <li><a href="#lt" >lessThan </a><span>lt</span> </li>
123 + <li><a href="#lte" >lessThanOrEqualTo </a><span>lte</span> </li>
124 + <li><a href="#minus" >minus </a><span>sub</span> </li>
125 + <li><a href="#mod" >modulo </a><span>mod</span> </li>
126 + <li><a href="#neg" >negated </a><span>neg</span> </li>
127 + <li><a href="#plus" >plus </a><span>add</span> </li>
128 + <li><a href="#sd" >precision </a><span>sd</span> </li>
129 + <li><a href="#round" >round </a> </li>
130 + <li><a href="#shift" >shift </a> </li>
131 + <li><a href="#sqrt" >squareRoot </a><span>sqrt</span> </li>
132 + <li><a href="#times" >times </a><span>mul</span> </li>
133 + <li><a href="#toD" >toDigits </a> </li>
134 + <li><a href="#toE" >toExponential </a> </li>
135 + <li><a href="#toFix" >toFixed </a> </li>
136 + <li><a href="#toFor" >toFormat </a> </li>
137 + <li><a href="#toFr" >toFraction </a> </li>
138 + <li><a href="#toJSON" >toJSON </a> </li>
139 + <li><a href="#toN" >toNumber </a> </li>
140 + <li><a href="#pow" >toPower </a><span>pow</span> </li>
141 + <li><a href="#toP" >toPrecision </a> </li>
142 + <li><a href="#toS" >toString </a> </li>
143 + <li><a href="#trunc" >truncated </a><span>trunc</span> </li>
144 + <li><a href="#valueOf">valueOf </a> </li>
145 + </ul>
146 +
147 + <a href="#instance-properties">Properties</a>
148 + <ul>
149 + <li><a href="#coefficient">c: coefficient</a></li>
150 + <li><a href="#exponent" >e: exponent</a></li>
151 + <li><a href="#sign" >s: sign</a></li>
152 + <li><a href="#isbig" >isBigNumber</a></li>
153 + </ul>
154 +
155 + <a href="#zero-nan-infinity">Zero, NaN &amp; Infinity</a>
156 + <a href="#Errors">Errors</a>
157 + <a class='end' href="#faq">FAQ</a>
158 +
159 + </div>
160 +
161 + <div class="container">
162 +
163 + <h1>bignumber<span id='js'>.js</span></h1>
164 +
165 + <p>A JavaScript library for arbitrary-precision arithmetic.</p>
166 + <p><a href="https://github.com/MikeMcl/bignumber.js">Hosted on GitHub</a>. </p>
167 +
168 + <h2>API</h2>
169 +
170 + <p>
171 + See the <a href='https://github.com/MikeMcl/bignumber.js'>README</a> on GitHub for a
172 + quick-start introduction.
173 + </p>
174 + <p>
175 + In all examples below, <code>var</code> and semicolons are not shown, and if a commented-out
176 + value is in quotes it means <code>toString</code> has been called on the preceding expression.
177 + </p>
178 +
179 +
180 + <h3>CONSTRUCTOR</h3>
181 +
182 + <h5 id="bignumber">
183 + BigNumber<code class='inset'>BigNumber(value [, base]) <i>&rArr; BigNumber</i></code>
184 + </h5>
185 + <dl>
186 + <dt><code>value</code></dt>
187 + <dd>
188 + <i>number|string|BigNumber</i>: see <a href='#range'>RANGE</a> for
189 + range.
190 + </dd>
191 + <dd>
192 + A numeric value.
193 + </dd>
194 + <dd>
195 + Legitimate values include &plusmn;<code>0</code>, &plusmn;<code>Infinity</code> and
196 + <code>NaN</code>.
197 + </dd>
198 + <dd>
199 + Values of type <em>number</em> with more than <code>15</code> significant digits are
200 + considered invalid (if <a href='#errors'><code>ERRORS</code></a> is true) as calling
201 + <code><a href='#toS'>toString</a></code> or <code><a href='#valueOf'>valueOf</a></code> on
202 + such numbers may not result in the intended value.
203 + <pre>console.log( 823456789123456.3 ); // 823456789123456.2</pre>
204 + </dd>
205 + <dd>
206 + There is no limit to the number of digits of a value of type <em>string</em> (other than
207 + that of JavaScript's maximum array size).
208 + </dd>
209 + <dd>
210 + Decimal string values may be in exponential, as well as normal (fixed-point) notation.
211 + Non-decimal values must be in normal notation.
212 + </dd>
213 + <dd>
214 + String values in hexadecimal literal form, e.g. <code>'0xff'</code>, are valid, as are
215 + string values with the octal and binary prefixs <code>'0o'</code> and <code>'0b'</code>.
216 + String values in octal literal form without the prefix will be interpreted as
217 + decimals, e.g. <code>'011'</code> is interpreted as 11, not 9.
218 + </dd>
219 + <dd>Values in any base may have fraction digits.</dd>
220 + <dd>
221 + For bases from <code>10</code> to <code>36</code>, lower and/or upper case letters can be
222 + used to represent values from <code>10</code> to <code>35</code>.
223 + </dd>
224 + <dd>
225 + For bases above 36, <code>a-z</code> represents values from <code>10</code> to
226 + <code>35</code>, <code>A-Z</code> from <code>36</code> to <code>61</code>, and
227 + <code>$</code> and <code>_</code> represent <code>62</code> and <code>63</code> respectively
228 + <i>(this can be changed by editing the <code>ALPHABET</code> variable near the top of the
229 + source file)</i>.
230 + </dd>
231 + </dl>
232 + <dl>
233 + <dt><code>base</code></dt>
234 + <dd>
235 + <i>number</i>: integer, <code>2</code> to <code>64</code> inclusive
236 + </dd>
237 + <dd>The base of <code>value</code>.</dd>
238 + <dd>
239 + If <code>base</code> is omitted, or is <code>null</code> or <code>undefined</code>, base
240 + <code>10</code> is assumed.
241 + </dd>
242 + </dl>
243 + <br />
244 + <p>Returns a new instance of a BigNumber object.</p>
245 + <p>
246 + If a base is specified, the value is rounded according to
247 + the current <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and
248 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration.
249 + </p>
250 + <p>
251 + See <a href='#Errors'>Errors</a> for the treatment of an invalid <code>value</code> or
252 + <code>base</code>.
253 + </p>
254 + <pre>
255 +x = new BigNumber(9) // '9'
256 +y = new BigNumber(x) // '9'
257 +
258 +// 'new' is optional if ERRORS is false
259 +BigNumber(435.345) // '435.345'
260 +
261 +new BigNumber('5032485723458348569331745.33434346346912144534543')
262 +new BigNumber('4.321e+4') // '43210'
263 +new BigNumber('-735.0918e-430') // '-7.350918e-428'
264 +new BigNumber(Infinity) // 'Infinity'
265 +new BigNumber(NaN) // 'NaN'
266 +new BigNumber('.5') // '0.5'
267 +new BigNumber('+2') // '2'
268 +new BigNumber(-10110100.1, 2) // '-180.5'
269 +new BigNumber(-0b10110100.1) // '-180.5'
270 +new BigNumber('123412421.234324', 5) // '607236.557696'
271 +new BigNumber('ff.8', 16) // '255.5'
272 +new BigNumber('0xff.8') // '255.5'</pre>
273 + <p>
274 + The following throws <code>'not a base 2 number'</code> if
275 + <a href='#errors'><code>ERRORS</code></a> is true, otherwise it returns a BigNumber with value
276 + <code>NaN</code>.
277 + </p>
278 + <pre>new BigNumber(9, 2)</pre>
279 + <p>
280 + The following throws <code>'number type has more than 15 significant digits'</code> if
281 + <a href='#errors'><code>ERRORS</code></a> is true, otherwise it returns a BigNumber with value
282 + <code>96517860459076820</code>.
283 + </p>
284 + <pre>new BigNumber(96517860459076817.4395)</pre>
285 + <p>
286 + The following throws <code>'not a number'</code> if <a href='#errors'><code>ERRORS</code></a>
287 + is true, otherwise it returns a BigNumber with value <code>NaN</code>.
288 + </p>
289 + <pre>new BigNumber('blurgh')</pre>
290 + <p>
291 + A value is only rounded by the constructor if a base is specified.
292 + </p>
293 + <pre>BigNumber.config({ DECIMAL_PLACES: 5 })
294 +new BigNumber(1.23456789) // '1.23456789'
295 +new BigNumber(1.23456789, 10) // '1.23457'</pre>
296 +
297 +
298 +
299 + <h4 id="methods">Methods</h4>
300 + <p>The static methods of a BigNumber constructor.</p>
301 +
302 +
303 +
304 +
305 + <h5 id="another">
306 + another<code class='inset'>.another([obj]) <i>&rArr; BigNumber constructor</i></code>
307 + </h5>
308 + <p><code>obj</code>: <i>object</i></p>
309 + <p>
310 + Returns a new independent BigNumber constructor with configuration as described by
311 + <code>obj</code> (see <a href='#config'><code>config</code></a>), or with the default
312 + configuration if <code>obj</code> is <code>null</code> or <code>undefined</code>.
313 + </p>
314 + <pre>BigNumber.config({ DECIMAL_PLACES: 5 })
315 +BN = BigNumber.another({ DECIMAL_PLACES: 9 })
316 +
317 +x = new BigNumber(1)
318 +y = new BN(1)
319 +
320 +x.div(3) // 0.33333
321 +y.div(3) // 0.333333333
322 +
323 +// BN = BigNumber.another({ DECIMAL_PLACES: 9 }) is equivalent to:
324 +BN = BigNumber.another()
325 +BN.config({ DECIMAL_PLACES: 9 })</pre>
326 +
327 +
328 +
329 + <h5 id="config">config<code class='inset'>set([obj]) <i>&rArr; object</i></code></h5>
330 + <p>
331 + <code>obj</code>: <i>object</i>: an object that contains some or all of the following
332 + properties.
333 + </p>
334 + <p>Configures the settings for this particular BigNumber constructor.</p>
335 + <p><i>Note: the configuration can also be supplied as an argument list, see below.</i></p>
336 + <dl class='inset'>
337 + <dt id="decimal-places"><code><b>DECIMAL_PLACES</b></code></dt>
338 + <dd>
339 + <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br />
340 + Default value: <code>20</code>
341 + </dd>
342 + <dd>
343 + The <u>maximum</u> number of decimal places of the results of operations involving
344 + division, i.e. division, square root and base conversion operations, and power
345 + operations with negative exponents.<br />
346 + </dd>
347 + <dd>
348 + <pre>BigNumber.config({ DECIMAL_PLACES: 5 })
349 +BigNumber.set({ DECIMAL_PLACES: 5 }) // equivalent
350 +BigNumber.config(5) // equivalent</pre>
351 + </dd>
352 +
353 +
354 +
355 + <dt id="rounding-mode"><code><b>ROUNDING_MODE</b></code></dt>
356 + <dd>
357 + <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive<br />
358 + Default value: <code>4</code> <a href="#round-half-up">(<code>ROUND_HALF_UP</code>)</a>
359 + </dd>
360 + <dd>
361 + The rounding mode used in the above operations and the default rounding mode of
362 + <a href='#round'><code>round</code></a>,
363 + <a href='#toE'><code>toExponential</code></a>,
364 + <a href='#toFix'><code>toFixed</code></a>,
365 + <a href='#toFor'><code>toFormat</code></a> and
366 + <a href='#toP'><code>toPrecision</code></a>.
367 + </dd>
368 + <dd>The modes are available as enumerated properties of the BigNumber constructor.</dd>
369 + <dd>
370 + <pre>BigNumber.config({ ROUNDING_MODE: 0 })
371 +BigNumber.config(null, BigNumber.ROUND_UP) // equivalent</pre>
372 + </dd>
373 +
374 +
375 +
376 + <dt id="exponential-at"><code><b>EXPONENTIAL_AT</b></code></dt>
377 + <dd>
378 + <i>number</i>: integer, magnitude <code>0</code> to <code>1e+9</code> inclusive, or
379 + <br />
380 + <i>number</i>[]: [ integer <code>-1e+9</code> to <code>0</code> inclusive, integer
381 + <code>0</code> to <code>1e+9</code> inclusive ]<br />
382 + Default value: <code>[-7, 20]</code>
383 + </dd>
384 + <dd>
385 + The exponent value(s) at which <code>toString</code> returns exponential notation.
386 + </dd>
387 + <dd>
388 + If a single number is assigned, the value is the exponent magnitude.<br />
389 + If an array of two numbers is assigned then the first number is the negative exponent
390 + value at and beneath which exponential notation is used, and the second number is the
391 + positive exponent value at and above which the same.
392 + </dd>
393 + <dd>
394 + For example, to emulate JavaScript numbers in terms of the exponent values at which they
395 + begin to use exponential notation, use <code>[-7, 20]</code>.
396 + </dd>
397 + <dd>
398 + <pre>BigNumber.config({ EXPONENTIAL_AT: 2 })
399 +new BigNumber(12.3) // '12.3' e is only 1
400 +new BigNumber(123) // '1.23e+2'
401 +new BigNumber(0.123) // '0.123' e is only -1
402 +new BigNumber(0.0123) // '1.23e-2'
403 +
404 +BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
405 +new BigNumber(123456789) // '123456789' e is only 8
406 +new BigNumber(0.000000123) // '1.23e-7'
407 +
408 +// Almost never return exponential notation:
409 +BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
410 +
411 +// Always return exponential notation:
412 +BigNumber.config({ EXPONENTIAL_AT: 0 })</pre>
413 + </dd>
414 + <dd>
415 + Regardless of the value of <code>EXPONENTIAL_AT</code>, the <code>toFixed</code> method
416 + will always return a value in normal notation and the <code>toExponential</code> method
417 + will always return a value in exponential form.
418 + </dd>
419 + <dd>
420 + Calling <code>toString</code> with a base argument, e.g. <code>toString(10)</code>, will
421 + also always return normal notation.
422 + </dd>
423 +
424 +
425 +
426 + <dt id="range"><code><b>RANGE</b></code></dt>
427 + <dd>
428 + <i>number</i>: integer, magnitude <code>1</code> to <code>1e+9</code> inclusive, or
429 + <br />
430 + <i>number</i>[]: [ integer <code>-1e+9</code> to <code>-1</code> inclusive, integer
431 + <code>1</code> to <code>1e+9</code> inclusive ]<br />
432 + Default value: <code>[-1e+9, 1e+9]</code>
433 + </dd>
434 + <dd>
435 + The exponent value(s) beyond which overflow to <code>Infinity</code> and underflow to
436 + zero occurs.
437 + </dd>
438 + <dd>
439 + If a single number is assigned, it is the maximum exponent magnitude: values wth a
440 + positive exponent of greater magnitude become <code>Infinity</code> and those with a
441 + negative exponent of greater magnitude become zero.
442 + <dd>
443 + If an array of two numbers is assigned then the first number is the negative exponent
444 + limit and the second number is the positive exponent limit.
445 + </dd>
446 + <dd>
447 + For example, to emulate JavaScript numbers in terms of the exponent values at which they
448 + become zero and <code>Infinity</code>, use <code>[-324, 308]</code>.
449 + </dd>
450 + <dd>
451 + <pre>BigNumber.config({ RANGE: 500 })
452 +BigNumber.config().RANGE // [ -500, 500 ]
453 +new BigNumber('9.999e499') // '9.999e+499'
454 +new BigNumber('1e500') // 'Infinity'
455 +new BigNumber('1e-499') // '1e-499'
456 +new BigNumber('1e-500') // '0'
457 +
458 +BigNumber.config({ RANGE: [-3, 4] })
459 +new BigNumber(99999) // '99999' e is only 4
460 +new BigNumber(100000) // 'Infinity' e is 5
461 +new BigNumber(0.001) // '0.01' e is only -3
462 +new BigNumber(0.0001) // '0' e is -4</pre>
463 + </dd>
464 + <dd>
465 + The largest possible magnitude of a finite BigNumber is
466 + <code>9.999...e+1000000000</code>.<br />
467 + The smallest possible magnitude of a non-zero BigNumber is <code>1e-1000000000</code>.
468 + </dd>
469 +
470 +
471 +
472 + <dt id="errors"><code><b>ERRORS</b></code></dt>
473 + <dd>
474 + <i>boolean|number</i>: <code>true</code>, <code>false</code>, <code>0</code> or
475 + <code>1</code>.<br />
476 + Default value: <code>true</code>
477 + </dd>
478 + <dd>
479 + The value that determines whether BigNumber Errors are thrown.<br />
480 + If <code>ERRORS</code> is false, no errors will be thrown.
481 + </dd>
482 + <dd>See <a href='#Errors'>Errors</a>.</dd>
483 + <dd><pre>BigNumber.config({ ERRORS: false })</pre></dd>
484 +
485 +
486 +
487 + <dt id="crypto"><code><b>CRYPTO</b></code></dt>
488 + <dd>
489 + <i>boolean|number</i>: <code>true</code>, <code>false</code>, <code>0</code> or
490 + <code>1</code>.<br />
491 + Default value: <code>false</code>
492 + </dd>
493 + <dd>
494 + The value that determines whether cryptographically-secure pseudo-random number
495 + generation is used.
496 + </dd>
497 + <dd>
498 + If <code>CRYPTO</code> is set to <code>true</code> then the
499 + <a href='#random'><code>random</code></a> method will generate random digits using
500 + <code>crypto.getRandomValues</code> in browsers that support it, or
501 + <code>crypto.randomBytes</code> if using a version of Node.js that supports it.
502 + </dd>
503 + <dd>
504 + If neither function is supported by the host environment then attempting to set
505 + <code>CRYPTO</code> to <code>true</code> will fail, and if <code>ERRORS</code>
506 + is <code>true</code> an exception will be thrown.
507 + </dd>
508 + <dd>
509 + If <code>CRYPTO</code> is <code>false</code> then the source of randomness used will be
510 + <code>Math.random</code> (which is assumed to generate at least <code>30</code> bits of
511 + randomness).
512 + </dd>
513 + <dd>See <a href='#random'><code>random</code></a>.</dd>
514 + <dd>
515 + <pre>BigNumber.config({ CRYPTO: true })
516 +BigNumber.config().CRYPTO // true
517 +BigNumber.random() // 0.54340758610486147524</pre>
518 + </dd>
519 +
520 +
521 +
522 + <dt id="modulo-mode"><code><b>MODULO_MODE</b></code></dt>
523 + <dd>
524 + <i>number</i>: integer, <code>0</code> to <code>9</code> inclusive<br />
525 + Default value: <code>1</code> (<a href="#round-down"><code>ROUND_DOWN</code></a>)
526 + </dd>
527 + <dd>The modulo mode used when calculating the modulus: <code>a mod n</code>.</dd>
528 + <dd>
529 + The quotient, <code>q = a / n</code>, is calculated according to the
530 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> that corresponds to the chosen
531 + <code>MODULO_MODE</code>.
532 + </dd>
533 + <dd>The remainder, <code>r</code>, is calculated as: <code>r = a - n * q</code>.</dd>
534 + <dd>
535 + The modes that are most commonly used for the modulus/remainder operation are shown in
536 + the following table. Although the other rounding modes can be used, they may not give
537 + useful results.
538 + </dd>
539 + <dd>
540 + <table>
541 + <tr><th>Property</th><th>Value</th><th>Description</th></tr>
542 + <tr>
543 + <td><b>ROUND_UP</b></td><td class='centre'>0</td>
544 + <td>
545 + The remainder is positive if the dividend is negative, otherwise it is negative.
546 + </td>
547 + </tr>
548 + <tr>
549 + <td><b>ROUND_DOWN</b></td><td class='centre'>1</td>
550 + <td>
551 + The remainder has the same sign as the dividend.<br />
552 + This uses 'truncating division' and matches the behaviour of JavaScript's
553 + remainder operator <code>%</code>.
554 + </td>
555 + </tr>
556 + <tr>
557 + <td><b>ROUND_FLOOR</b></td><td class='centre'>3</td>
558 + <td>
559 + The remainder has the same sign as the divisor.<br />
560 + This matches Python's <code>%</code> operator.
561 + </td>
562 + </tr>
563 + <tr>
564 + <td><b>ROUND_HALF_EVEN</b></td><td class='centre'>6</td>
565 + <td>The <i>IEEE 754</i> remainder function.</td>
566 + </tr>
567 + <tr>
568 + <td><b>EUCLID</b></td><td class='centre'>9</td>
569 + <td>
570 + The remainder is always positive. Euclidian division: <br />
571 + <code>q = sign(n) * floor(a / abs(n))</code>
572 + </td>
573 + </tr>
574 + </table>
575 + </dd>
576 + <dd>
577 + The rounding/modulo modes are available as enumerated properties of the BigNumber
578 + constructor.
579 + </dd>
580 + <dd>See <a href='#mod'><code>modulo</code></a>.</dd>
581 + <dd>
582 + <pre>BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
583 +BigNumber.config({ MODULO_MODE: 9 }) // equivalent</pre>
584 + </dd>
585 +
586 +
587 +
588 + <dt id="pow-precision"><code><b>POW_PRECISION</b></code></dt>
589 + <dd>
590 + <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive.<br />
591 + Default value: <code>0</code>
592 + </dd>
593 + <dd>
594 + The <i>maximum</i> number of significant digits of the result of the power operation
595 + (unless a modulus is specified).
596 + </dd>
597 + <dd>If set to <code>0</code>, the number of signifcant digits will not be limited.</dd>
598 + <dd>See <a href='#pow'><code>toPower</code></a>.</dd>
599 + <dd><pre>BigNumber.config({ POW_PRECISION: 100 })</pre></dd>
600 +
601 +
602 +
603 + <dt id="format"><code><b>FORMAT</b></code></dt>
604 + <dd><i>object</i></dd>
605 + <dd>
606 + The <code>FORMAT</code> object configures the format of the string returned by the
607 + <a href='#toFor'><code>toFormat</code></a> method.
608 + </dd>
609 + <dd>
610 + The example below shows the properties of the <code>FORMAT</code> object that are
611 + recognised, and their default values.
612 + </dd>
613 + <dd>
614 + Unlike the other configuration properties, the values of the properties of the
615 + <code>FORMAT</code> object will not be checked for validity. The existing
616 + <code>FORMAT</code> object will simply be replaced by the object that is passed in.
617 + Note that all the properties shown below do not have to be included.
618 + </dd>
619 + <dd>See <a href='#toFor'><code>toFormat</code></a> for examples of usage.</dd>
620 + <dd>
621 + <pre>
622 +BigNumber.config({
623 + FORMAT: {
624 + // the decimal separator
625 + decimalSeparator: '.',
626 + // the grouping separator of the integer part
627 + groupSeparator: ',',
628 + // the primary grouping size of the integer part
629 + groupSize: 3,
630 + // the secondary grouping size of the integer part
631 + secondaryGroupSize: 0,
632 + // the grouping separator of the fraction part
633 + fractionGroupSeparator: ' ',
634 + // the grouping size of the fraction part
635 + fractionGroupSize: 0
636 + }
637 +});</pre>
638 + </dd>
639 + </dl>
640 + <br />
641 + <p>Returns an object with the above properties and their current values.</p>
642 + <p>
643 + If the value to be assigned to any of the above properties is <code>null</code> or
644 + <code>undefined</code> it is ignored.
645 + </p>
646 + <p>See <a href='#Errors'>Errors</a> for the treatment of invalid values.</p>
647 + <pre>
648 +BigNumber.config({
649 + DECIMAL_PLACES: 40,
650 + ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL,
651 + EXPONENTIAL_AT: [-10, 20],
652 + RANGE: [-500, 500],
653 + ERRORS: true,
654 + CRYPTO: true,
655 + MODULO_MODE: BigNumber.ROUND_FLOOR,
656 + POW_PRECISION: 80,
657 + FORMAT: {
658 + groupSize: 3,
659 + groupSeparator: ' ',
660 + decimalSeparator: ','
661 + }
662 +});
663 +
664 +// Alternatively but equivalently (excluding FORMAT):
665 +BigNumber.config( 40, 7, [-10, 20], 500, 1, 1, 3, 80 )
666 +
667 +obj = BigNumber.config();
668 +obj.ERRORS // true
669 +obj.RANGE // [-500, 500]</pre>
670 +
671 +
672 +
673 + <h5 id="max">
674 + max<code class='inset'>.max([arg1 [, arg2, ...]]) <i>&rArr; BigNumber</i></code>
675 + </h5>
676 + <p>
677 + <code>arg1</code>, <code>arg2</code>, ...: <i>number|string|BigNumber</i><br />
678 + <i>See <code><a href="#bignumber">BigNumber</a></code> for further parameter details.</i>
679 + </p>
680 + <p>
681 + Returns a BigNumber whose value is the maximum of <code>arg1</code>,
682 + <code>arg2</code>,... .
683 + </p>
684 + <p>The argument to this method can also be an array of values.</p>
685 + <p>The return value is always exact and unrounded.</p>
686 + <pre>x = new BigNumber('3257869345.0378653')
687 +BigNumber.max(4e9, x, '123456789.9') // '4000000000'
688 +
689 +arr = [12, '13', new BigNumber(14)]
690 +BigNumber.max(arr) // '14'</pre>
691 +
692 +
693 +
694 + <h5 id="min">
695 + min<code class='inset'>.min([arg1 [, arg2, ...]]) <i>&rArr; BigNumber</i></code>
696 + </h5>
697 + <p>
698 + <code>arg1</code>, <code>arg2</code>, ...: <i>number|string|BigNumber</i><br />
699 + <i>See <code><a href="#bignumber">BigNumber</a></code> for further parameter details.</i>
700 + </p>
701 + <p>
702 + Returns a BigNumber whose value is the minimum of <code>arg1</code>,
703 + <code>arg2</code>,... .
704 + </p>
705 + <p>The argument to this method can also be an array of values.</p>
706 + <p>The return value is always exact and unrounded.</p>
707 + <pre>x = new BigNumber('3257869345.0378653')
708 +BigNumber.min(4e9, x, '123456789.9') // '123456789.9'
709 +
710 +arr = [2, new BigNumber(-14), '-15.9999', -12]
711 +BigNumber.min(arr) // '-15.9999'</pre>
712 +
713 +
714 +
715 + <h5 id="random">
716 + random<code class='inset'>.random([dp]) <i>&rArr; BigNumber</i></code>
717 + </h5>
718 + <p><code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive</p>
719 + <p>
720 + Returns a new BigNumber with a pseudo-random value equal to or greater than <code>0</code> and
721 + less than <code>1</code>.
722 + </p>
723 + <p>
724 + The return value will have <code>dp</code> decimal places (or less if trailing zeros are
725 + produced).<br />
726 + If <code>dp</code> is omitted then the number of decimal places will default to the current
727 + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> setting.
728 + </p>
729 + <p>
730 + Depending on the value of this BigNumber constructor's
731 + <a href='#crypto'><code>CRYPTO</code></a> setting and the support for the
732 + <code>crypto</code> object in the host environment, the random digits of the return value are
733 + generated by either <code>Math.random</code> (fastest), <code>crypto.getRandomValues</code>
734 + (Web Cryptography API in recent browsers) or <code>crypto.randomBytes</code> (Node.js).
735 + </p>
736 + <p>
737 + If <a href='#crypto'><code>CRYPTO</code></a> is <code>true</code>, i.e. one of the
738 + <code>crypto</code> methods is to be used, the value of a returned BigNumber should be
739 + cryptographically-secure and statistically indistinguishable from a random value.
740 + </p>
741 + <pre>BigNumber.config({ DECIMAL_PLACES: 10 })
742 +BigNumber.random() // '0.4117936847'
743 +BigNumber.random(20) // '0.78193327636914089009'</pre>
744 +
745 +
746 +
747 + <h4 id="constructor-properties">Properties</h4>
748 + <p>
749 + The library's enumerated rounding modes are stored as properties of the constructor.<br />
750 + (They are not referenced internally by the library itself.)
751 + </p>
752 + <p>
753 + Rounding modes <code>0</code> to <code>6</code> (inclusive) are the same as those of Java's
754 + BigDecimal class.
755 + </p>
756 + <table>
757 + <tr>
758 + <th>Property</th>
759 + <th>Value</th>
760 + <th>Description</th>
761 + </tr>
762 + <tr>
763 + <td id="round-up"><b>ROUND_UP</b></td>
764 + <td class='centre'>0</td>
765 + <td>Rounds away from zero</td>
766 + </tr>
767 + <tr>
768 + <td id="round-down"><b>ROUND_DOWN</b></td>
769 + <td class='centre'>1</td>
770 + <td>Rounds towards zero</td>
771 + </tr>
772 + <tr>
773 + <td id="round-ceil"><b>ROUND_CEIL</b></td>
774 + <td class='centre'>2</td>
775 + <td>Rounds towards <code>Infinity</code></td>
776 + </tr>
777 + <tr>
778 + <td id="round-floor"><b>ROUND_FLOOR</b></td>
779 + <td class='centre'>3</td>
780 + <td>Rounds towards <code>-Infinity</code></td>
781 + </tr>
782 + <tr>
783 + <td id="round-half-up"><b>ROUND_HALF_UP</b></td>
784 + <td class='centre'>4</td>
785 + <td>
786 + Rounds towards nearest neighbour.<br />
787 + If equidistant, rounds away from zero
788 + </td>
789 + </tr>
790 + <tr>
791 + <td id="round-half-down"><b>ROUND_HALF_DOWN</b></td>
792 + <td class='centre'>5</td>
793 + <td>
794 + Rounds towards nearest neighbour.<br />
795 + If equidistant, rounds towards zero
796 + </td>
797 + </tr>
798 + <tr>
799 + <td id="round-half-even"><b>ROUND_HALF_EVEN</b></td>
800 + <td class='centre'>6</td>
801 + <td>
802 + Rounds towards nearest neighbour.<br />
803 + If equidistant, rounds towards even neighbour
804 + </td>
805 + </tr>
806 + <tr>
807 + <td id="round-half-ceil"><b>ROUND_HALF_CEIL</b></td>
808 + <td class='centre'>7</td>
809 + <td>
810 + Rounds towards nearest neighbour.<br />
811 + If equidistant, rounds towards <code>Infinity</code>
812 + </td>
813 + </tr>
814 + <tr>
815 + <td id="round-half-floor"><b>ROUND_HALF_FLOOR</b></td>
816 + <td class='centre'>8</td>
817 + <td>
818 + Rounds towards nearest neighbour.<br />
819 + If equidistant, rounds towards <code>-Infinity</code>
820 + </td>
821 + </tr>
822 + </table>
823 + <pre>
824 +BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL })
825 +BigNumber.config({ ROUNDING_MODE: 2 }) // equivalent</pre>
826 +
827 +
828 + <h3>INSTANCE</h3>
829 +
830 + <h4 id="prototype-methods">Methods</h4>
831 + <p>The methods inherited by a BigNumber instance from its constructor's prototype object.</p>
832 + <p>A BigNumber is immutable in the sense that it is not changed by its methods. </p>
833 + <p>
834 + The treatment of &plusmn;<code>0</code>, &plusmn;<code>Infinity</code> and <code>NaN</code> is
835 + consistent with how JavaScript treats these values.
836 + </p>
837 + <p>
838 + Many method names have a shorter alias.<br />
839 + (Internally, the library always uses the shorter method names.)
840 + </p>
841 +
842 +
843 +
844 + <h5 id="abs">absoluteValue<code class='inset'>.abs() <i>&rArr; BigNumber</i></code></h5>
845 + <p>
846 + Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of
847 + this BigNumber.
848 + </p>
849 + <p>The return value is always exact and unrounded.</p>
850 + <pre>
851 +x = new BigNumber(-0.8)
852 +y = x.absoluteValue() // '0.8'
853 +z = y.abs() // '0.8'</pre>
854 +
855 +
856 +
857 + <h5 id="ceil">ceil<code class='inset'>.ceil() <i>&rArr; BigNumber</i></code></h5>
858 + <p>
859 + Returns a BigNumber whose value is the value of this BigNumber rounded to
860 + a whole number in the direction of positive <code>Infinity</code>.
861 + </p>
862 + <pre>
863 +x = new BigNumber(1.3)
864 +x.ceil() // '2'
865 +y = new BigNumber(-1.8)
866 +y.ceil() // '-1'</pre>
867 +
868 +
869 +
870 + <h5 id="cmp">comparedTo<code class='inset'>.cmp(n [, base]) <i>&rArr; number</i></code></h5>
871 + <p>
872 + <code>n</code>: <i>number|string|BigNumber</i><br />
873 + <code>base</code>: <i>number</i><br />
874 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
875 + </p>
876 + <table>
877 + <tr><th>Returns</th><th>&nbsp;</th></tr>
878 + <tr>
879 + <td class='centre'><code>1</code></td>
880 + <td>If the value of this BigNumber is greater than the value of <code>n</code></td>
881 + </tr>
882 + <tr>
883 + <td class='centre'><code>-1</code></td>
884 + <td>If the value of this BigNumber is less than the value of <code>n</code></td>
885 + </tr>
886 + <tr>
887 + <td class='centre'><code>0</code></td>
888 + <td>If this BigNumber and <code>n</code> have the same value</td>
889 + </tr>
890 + <tr>
891 + <td class='centre'><code>null</code></td>
892 + <td>If the value of either this BigNumber or <code>n</code> is <code>NaN</code></td>
893 + </tr>
894 + </table>
895 + <pre>
896 +x = new BigNumber(Infinity)
897 +y = new BigNumber(5)
898 +x.comparedTo(y) // 1
899 +x.comparedTo(x.minus(1)) // 0
900 +y.cmp(NaN) // null
901 +y.cmp('110', 2) // -1</pre>
902 +
903 +
904 +
905 + <h5 id="dp">decimalPlaces<code class='inset'>.dp() <i>&rArr; number</i></code></h5>
906 + <p>
907 + Return the number of decimal places of the value of this BigNumber, or <code>null</code> if
908 + the value of this BigNumber is &plusmn;<code>Infinity</code> or <code>NaN</code>.
909 + </p>
910 + <pre>
911 +x = new BigNumber(123.45)
912 +x.decimalPlaces() // 2
913 +y = new BigNumber('9.9e-101')
914 +y.dp() // 102</pre>
915 +
916 +
917 +
918 + <h5 id="div">dividedBy<code class='inset'>.div(n [, base]) <i>&rArr; BigNumber</i></code>
919 + </h5>
920 + <p>
921 + <code>n</code>: <i>number|string|BigNumber</i><br />
922 + <code>base</code>: <i>number</i><br />
923 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
924 + </p>
925 + <p>
926 + Returns a BigNumber whose value is the value of this BigNumber divided by
927 + <code>n</code>, rounded according to the current
928 + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and
929 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration.
930 + </p>
931 + <pre>
932 +x = new BigNumber(355)
933 +y = new BigNumber(113)
934 +x.dividedBy(y) // '3.14159292035398230088'
935 +x.div(5) // '71'
936 +x.div(47, 16) // '5'</pre>
937 +
938 +
939 +
940 + <h5 id="divInt">
941 + dividedToIntegerBy<code class='inset'>.divToInt(n [, base]) &rArr;
942 + <i>BigNumber</i></code>
943 + </h5>
944 + <p>
945 + <code>n</code>: <i>number|string|BigNumber</i><br />
946 + <code>base</code>: <i>number</i><br />
947 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
948 + </p>
949 + <p>
950 + Return a BigNumber whose value is the integer part of dividing the value of this BigNumber by
951 + <code>n</code>.
952 + </p>
953 + <pre>
954 +x = new BigNumber(5)
955 +y = new BigNumber(3)
956 +x.dividedToIntegerBy(y) // '1'
957 +x.divToInt(0.7) // '7'
958 +x.divToInt('0.f', 16) // '5'</pre>
959 +
960 +
961 +
962 + <h5 id="eq">equals<code class='inset'>.eq(n [, base]) <i>&rArr; boolean</i></code></h5>
963 + <p>
964 + <code>n</code>: <i>number|string|BigNumber</i><br />
965 + <code>base</code>: <i>number</i><br />
966 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
967 + </p>
968 + <p>
969 + Returns <code>true</code> if the value of this BigNumber equals the value of <code>n</code>,
970 + otherwise returns <code>false</code>.<br />
971 + As with JavaScript, <code>NaN</code> does not equal <code>NaN</code>.
972 + </p>
973 + <p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p>
974 + <pre>
975 +0 === 1e-324 // true
976 +x = new BigNumber(0)
977 +x.equals('1e-324') // false
978 +BigNumber(-0).eq(x) // true ( -0 === 0 )
979 +BigNumber(255).eq('ff', 16) // true
980 +
981 +y = new BigNumber(NaN)
982 +y.equals(NaN) // false</pre>
983 +
984 +
985 +
986 + <h5 id="floor">floor<code class='inset'>.floor() <i>&rArr; BigNumber</i></code></h5>
987 + <p>
988 + Returns a BigNumber whose value is the value of this BigNumber rounded to a whole number in
989 + the direction of negative <code>Infinity</code>.
990 + </p>
991 + <pre>
992 +x = new BigNumber(1.8)
993 +x.floor() // '1'
994 +y = new BigNumber(-1.3)
995 +y.floor() // '-2'</pre>
996 +
997 +
998 +
999 + <h5 id="gt">greaterThan<code class='inset'>.gt(n [, base]) <i>&rArr; boolean</i></code></h5>
1000 + <p>
1001 + <code>n</code>: <i>number|string|BigNumber</i><br />
1002 + <code>base</code>: <i>number</i><br />
1003 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
1004 + </p>
1005 + <p>
1006 + Returns <code>true</code> if the value of this BigNumber is greater than the value of
1007 + <code>n</code>, otherwise returns <code>false</code>.
1008 + </p>
1009 + <p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p>
1010 + <pre>
1011 +0.1 &gt; (0.3 - 0.2) // true
1012 +x = new BigNumber(0.1)
1013 +x.greaterThan(BigNumber(0.3).minus(0.2)) // false
1014 +BigNumber(0).gt(x) // false
1015 +BigNumber(11, 3).gt(11.1, 2) // true</pre>
1016 +
1017 +
1018 +
1019 + <h5 id="gte">
1020 + greaterThanOrEqualTo<code class='inset'>.gte(n [, base]) <i>&rArr; boolean</i></code>
1021 + </h5>
1022 + <p>
1023 + <code>n</code>: <i>number|string|BigNumber</i><br />
1024 + <code>base</code>: <i>number</i><br />
1025 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
1026 + </p>
1027 + <p>
1028 + Returns <code>true</code> if the value of this BigNumber is greater than or equal to the value
1029 + of <code>n</code>, otherwise returns <code>false</code>.
1030 + </p>
1031 + <p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p>
1032 + <pre>
1033 +(0.3 - 0.2) &gt;= 0.1 // false
1034 +x = new BigNumber(0.3).minus(0.2)
1035 +x.greaterThanOrEqualTo(0.1) // true
1036 +BigNumber(1).gte(x) // true
1037 +BigNumber(10, 18).gte('i', 36) // true</pre>
1038 +
1039 +
1040 +
1041 + <h5 id="isF">isFinite<code class='inset'>.isFinite() <i>&rArr; boolean</i></code></h5>
1042 + <p>
1043 + Returns <code>true</code> if the value of this BigNumber is a finite number, otherwise
1044 + returns <code>false</code>.
1045 + </p>
1046 + <p>
1047 + The only possible non-finite values of a BigNumber are <code>NaN</code>, <code>Infinity</code>
1048 + and <code>-Infinity</code>.
1049 + </p>
1050 + <pre>
1051 +x = new BigNumber(1)
1052 +x.isFinite() // true
1053 +y = new BigNumber(Infinity)
1054 +y.isFinite() // false</pre>
1055 + <p>
1056 + Note: The native method <code>isFinite()</code> can be used if
1057 + <code>n &lt;= Number.MAX_VALUE</code>.
1058 + </p>
1059 +
1060 +
1061 +
1062 + <h5 id="isInt">isInteger<code class='inset'>.isInt() <i>&rArr; boolean</i></code></h5>
1063 + <p>
1064 + Returns <code>true</code> if the value of this BigNumber is a whole number, otherwise returns
1065 + <code>false</code>.
1066 + </p>
1067 + <pre>
1068 +x = new BigNumber(1)
1069 +x.isInteger() // true
1070 +y = new BigNumber(123.456)
1071 +y.isInt() // false</pre>
1072 +
1073 +
1074 +
1075 + <h5 id="isNaN">isNaN<code class='inset'>.isNaN() <i>&rArr; boolean</i></code></h5>
1076 + <p>
1077 + Returns <code>true</code> if the value of this BigNumber is <code>NaN</code>, otherwise
1078 + returns <code>false</code>.
1079 + </p>
1080 + <pre>
1081 +x = new BigNumber(NaN)
1082 +x.isNaN() // true
1083 +y = new BigNumber('Infinity')
1084 +y.isNaN() // false</pre>
1085 + <p>Note: The native method <code>isNaN()</code> can also be used.</p>
1086 +
1087 +
1088 +
1089 + <h5 id="isNeg">isNegative<code class='inset'>.isNeg() <i>&rArr; boolean</i></code></h5>
1090 + <p>
1091 + Returns <code>true</code> if the value of this BigNumber is negative, otherwise returns
1092 + <code>false</code>.
1093 + </p>
1094 + <pre>
1095 +x = new BigNumber(-0)
1096 +x.isNegative() // true
1097 +y = new BigNumber(2)
1098 +y.isNeg() // false</pre>
1099 + <p>Note: <code>n &lt; 0</code> can be used if <code>n &lt;= -Number.MIN_VALUE</code>.</p>
1100 +
1101 +
1102 +
1103 + <h5 id="isZ">isZero<code class='inset'>.isZero() <i>&rArr; boolean</i></code></h5>
1104 + <p>
1105 + Returns <code>true</code> if the value of this BigNumber is zero or minus zero, otherwise
1106 + returns <code>false</code>.
1107 + </p>
1108 + <pre>
1109 +x = new BigNumber(-0)
1110 +x.isZero() && x.isNeg() // true
1111 +y = new BigNumber(Infinity)
1112 +y.isZero() // false</pre>
1113 + <p>Note: <code>n == 0</code> can be used if <code>n &gt;= Number.MIN_VALUE</code>.</p>
1114 +
1115 +
1116 +
1117 + <h5 id="lt">lessThan<code class='inset'>.lt(n [, base]) <i>&rArr; boolean</i></code></h5>
1118 + <p>
1119 + <code>n</code>: <i>number|string|BigNumber</i><br />
1120 + <code>base</code>: <i>number</i><br />
1121 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
1122 + </p>
1123 + <p>
1124 + Returns <code>true</code> if the value of this BigNumber is less than the value of
1125 + <code>n</code>, otherwise returns <code>false</code>.
1126 + </p>
1127 + <p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p>
1128 + <pre>
1129 +(0.3 - 0.2) &lt; 0.1 // true
1130 +x = new BigNumber(0.3).minus(0.2)
1131 +x.lessThan(0.1) // false
1132 +BigNumber(0).lt(x) // true
1133 +BigNumber(11.1, 2).lt(11, 3) // true</pre>
1134 +
1135 +
1136 +
1137 + <h5 id="lte">
1138 + lessThanOrEqualTo<code class='inset'>.lte(n [, base]) <i>&rArr; boolean</i></code>
1139 + </h5>
1140 + <p>
1141 + <code>n</code>: <i>number|string|BigNumber</i><br />
1142 + <code>base</code>: <i>number</i><br />
1143 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
1144 + </p>
1145 + <p>
1146 + Returns <code>true</code> if the value of this BigNumber is less than or equal to the value of
1147 + <code>n</code>, otherwise returns <code>false</code>.
1148 + </p>
1149 + <p>Note: This method uses the <a href='#cmp'><code>comparedTo</code></a> method internally.</p>
1150 + <pre>
1151 +0.1 &lt;= (0.3 - 0.2) // false
1152 +x = new BigNumber(0.1)
1153 +x.lessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true
1154 +BigNumber(-1).lte(x) // true
1155 +BigNumber(10, 18).lte('i', 36) // true</pre>
1156 +
1157 +
1158 +
1159 + <h5 id="minus">
1160 + minus<code class='inset'>.minus(n [, base]) <i>&rArr; BigNumber</i></code>
1161 + </h5>
1162 + <p>
1163 + <code>n</code>: <i>number|string|BigNumber</i><br />
1164 + <code>base</code>: <i>number</i><br />
1165 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
1166 + </p>
1167 + <p>Returns a BigNumber whose value is the value of this BigNumber minus <code>n</code>.</p>
1168 + <p>The return value is always exact and unrounded.</p>
1169 + <pre>
1170 +0.3 - 0.1 // 0.19999999999999998
1171 +x = new BigNumber(0.3)
1172 +x.minus(0.1) // '0.2'
1173 +x.minus(0.6, 20) // '0'</pre>
1174 +
1175 +
1176 +
1177 + <h5 id="mod">modulo<code class='inset'>.mod(n [, base]) <i>&rArr; BigNumber</i></code></h5>
1178 + <p>
1179 + <code>n</code>: <i>number|string|BigNumber</i><br />
1180 + <code>base</code>: <i>number</i><br />
1181 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
1182 + </p>
1183 + <p>
1184 + Returns a BigNumber whose value is the value of this BigNumber modulo <code>n</code>, i.e.
1185 + the integer remainder of dividing this BigNumber by <code>n</code>.
1186 + </p>
1187 + <p>
1188 + The value returned, and in particular its sign, is dependent on the value of the
1189 + <a href='#modulo-mode'><code>MODULO_MODE</code></a> setting of this BigNumber constructor.
1190 + If it is <code>1</code> (default value), the result will have the same sign as this BigNumber,
1191 + and it will match that of Javascript's <code>%</code> operator (within the limits of double
1192 + precision) and BigDecimal's <code>remainder</code> method.
1193 + </p>
1194 + <p>The return value is always exact and unrounded.</p>
1195 + <p>
1196 + See <a href='#modulo-mode'><code>MODULO_MODE</code></a> for a description of the other
1197 + modulo modes.
1198 + </p>
1199 + <pre>
1200 +1 % 0.9 // 0.09999999999999998
1201 +x = new BigNumber(1)
1202 +x.modulo(0.9) // '0.1'
1203 +y = new BigNumber(33)
1204 +y.mod('a', 33) // '3'</pre>
1205 +
1206 +
1207 +
1208 + <h5 id="neg">negated<code class='inset'>.neg() <i>&rArr; BigNumber</i></code></h5>
1209 + <p>
1210 + Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by
1211 + <code>-1</code>.
1212 + </p>
1213 + <pre>
1214 +x = new BigNumber(1.8)
1215 +x.negated() // '-1.8'
1216 +y = new BigNumber(-1.3)
1217 +y.neg() // '1.3'</pre>
1218 +
1219 +
1220 +
1221 + <h5 id="plus">plus<code class='inset'>.plus(n [, base]) <i>&rArr; BigNumber</i></code></h5>
1222 + <p>
1223 + <code>n</code>: <i>number|string|BigNumber</i><br />
1224 + <code>base</code>: <i>number</i><br />
1225 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
1226 + </p>
1227 + <p>Returns a BigNumber whose value is the value of this BigNumber plus <code>n</code>.</p>
1228 + <p>The return value is always exact and unrounded.</p>
1229 + <pre>
1230 +0.1 + 0.2 // 0.30000000000000004
1231 +x = new BigNumber(0.1)
1232 +y = x.plus(0.2) // '0.3'
1233 +BigNumber(0.7).plus(x).plus(y) // '1'
1234 +x.plus('0.1', 8) // '0.225'</pre>
1235 +
1236 +
1237 +
1238 + <h5 id="sd">precision<code class='inset'>.sd([z]) <i>&rArr; number</i></code></h5>
1239 + <p>
1240 + <code>z</code>: <i>boolean|number</i>: <code>true</code>, <code>false</code>, <code>0</code>
1241 + or <code>1</code>
1242 + </p>
1243 + <p>Returns the number of significant digits of the value of this BigNumber.</p>
1244 + <p>
1245 + If <code>z</code> is <code>true</code> or <code>1</code> then any trailing zeros of the
1246 + integer part of a number are counted as significant digits, otherwise they are not.
1247 + </p>
1248 + <pre>
1249 +x = new BigNumber(1.234)
1250 +x.precision() // 4
1251 +y = new BigNumber(987000)
1252 +y.sd() // 3
1253 +y.sd(true) // 6</pre>
1254 +
1255 +
1256 +
1257 + <h5 id="round">round<code class='inset'>.round([dp [, rm]]) <i>&rArr; BigNumber</i></code></h5>
1258 + <p>
1259 + <code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br />
1260 + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive
1261 + </p>
1262 + <p>
1263 + Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode
1264 + <code>rm</code> to a maximum of <code>dp</code> decimal places.
1265 + </p>
1266 + <p>
1267 + if <code>dp</code> is omitted, or is <code>null</code> or <code>undefined</code>, the
1268 + return value is <code>n</code> rounded to a whole number.<br />
1269 + if <code>rm</code> is omitted, or is <code>null</code> or <code>undefined</code>,
1270 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used.
1271 + </p>
1272 + <p>
1273 + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
1274 + <code>dp</code> or <code>rm</code> values.
1275 + </p>
1276 + <pre>
1277 +x = 1234.56
1278 +Math.round(x) // 1235
1279 +
1280 +y = new BigNumber(x)
1281 +y.round() // '1235'
1282 +y.round(1) // '1234.6'
1283 +y.round(2) // '1234.56'
1284 +y.round(10) // '1234.56'
1285 +y.round(0, 1) // '1234'
1286 +y.round(0, 6) // '1235'
1287 +y.round(1, 1) // '1234.5'
1288 +y.round(1, BigNumber.ROUND_HALF_EVEN) // '1234.6'
1289 +y // '1234.56'</pre>
1290 +
1291 +
1292 +
1293 + <h5 id="shift">shift<code class='inset'>.shift(n) <i>&rArr; BigNumber</i></code></h5>
1294 + <p>
1295 + <code>n</code>: <i>number</i>: integer,
1296 + <code>-9007199254740991</code> to <code>9007199254740991</code> inclusive
1297 + </p>
1298 + <p>
1299 + Returns a BigNumber whose value is the value of this BigNumber shifted <code>n</code> places.
1300 + <p>
1301 + The shift is of the decimal point, i.e. of powers of ten, and is to the left if <code>n</code>
1302 + is negative or to the right if <code>n</code> is positive.
1303 + </p>
1304 + <p>The return value is always exact and unrounded.</p>
1305 + <pre>
1306 +x = new BigNumber(1.23)
1307 +x.shift(3) // '1230'
1308 +x.shift(-3) // '0.00123'</pre>
1309 +
1310 +
1311 +
1312 + <h5 id="sqrt">squareRoot<code class='inset'>.sqrt() <i>&rArr; BigNumber</i></code></h5>
1313 + <p>
1314 + Returns a BigNumber whose value is the square root of the value of this BigNumber,
1315 + rounded according to the current
1316 + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and
1317 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration.
1318 + </p>
1319 + <p>
1320 + The return value will be correctly rounded, i.e. rounded as if the result was first calculated
1321 + to an infinite number of correct digits before rounding.
1322 + </p>
1323 + <pre>
1324 +x = new BigNumber(16)
1325 +x.squareRoot() // '4'
1326 +y = new BigNumber(3)
1327 +y.sqrt() // '1.73205080756887729353'</pre>
1328 +
1329 +
1330 +
1331 + <h5 id="times">times<code class='inset'>.times(n [, base]) <i>&rArr; BigNumber</i></code></h5>
1332 + <p>
1333 + <code>n</code>: <i>number|string|BigNumber</i><br />
1334 + <code>base</code>: <i>number</i><br />
1335 + <i>See <a href="#bignumber">BigNumber</a> for further parameter details.</i>
1336 + </p>
1337 + <p>Returns a BigNumber whose value is the value of this BigNumber times <code>n</code>.</p>
1338 + <p>The return value is always exact and unrounded.</p>
1339 + <pre>
1340 +0.6 * 3 // 1.7999999999999998
1341 +x = new BigNumber(0.6)
1342 +y = x.times(3) // '1.8'
1343 +BigNumber('7e+500').times(y) // '1.26e+501'
1344 +x.times('-a', 16) // '-6'</pre>
1345 +
1346 +
1347 +
1348 + <h5 id="toD">
1349 + toDigits<code class='inset'>.toDigits([sd [, rm]]) <i>&rArr; BigNumber</i></code>
1350 + </h5>
1351 + <p>
1352 + <code>sd</code>: <i>number</i>: integer, <code>1</code> to <code>1e+9</code> inclusive.<br />
1353 + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive.
1354 + </p>
1355 + <p>
1356 + Returns a BigNumber whose value is the value of this BigNumber rounded to <code>sd</code>
1357 + significant digits using rounding mode <code>rm</code>.
1358 + </p>
1359 + <p>
1360 + If <code>sd</code> is omitted or is <code>null</code> or <code>undefined</code>, the return
1361 + value will not be rounded.<br />
1362 + If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>,
1363 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> will be used.
1364 + </p>
1365 + <p>
1366 + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
1367 + <code>sd</code> or <code>rm</code> values.
1368 + </p>
1369 + <pre>
1370 +BigNumber.config({ precision: 5, rounding: 4 })
1371 +x = new BigNumber(9876.54321)
1372 +
1373 +x.toDigits() // '9876.5'
1374 +x.toDigits(6) // '9876.54'
1375 +x.toDigits(6, BigNumber.ROUND_UP) // '9876.55'
1376 +x.toDigits(2) // '9900'
1377 +x.toDigits(2, 1) // '9800'
1378 +x // '9876.54321'</pre>
1379 +
1380 +
1381 +
1382 + <h5 id="toE">
1383 + toExponential<code class='inset'>.toExponential([dp [, rm]]) <i>&rArr; string</i></code>
1384 + </h5>
1385 + <p>
1386 + <code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br />
1387 + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive
1388 + </p>
1389 + <p>
1390 + Returns a string representing the value of this BigNumber in exponential notation rounded
1391 + using rounding mode <code>rm</code> to <code>dp</code> decimal places, i.e with one digit
1392 + before the decimal point and <code>dp</code> digits after it.
1393 + </p>
1394 + <p>
1395 + If the value of this BigNumber in exponential notation has fewer than <code>dp</code> fraction
1396 + digits, the return value will be appended with zeros accordingly.
1397 + </p>
1398 + <p>
1399 + If <code>dp</code> is omitted, or is <code>null</code> or <code>undefined</code>, the number
1400 + of digits after the decimal point defaults to the minimum number of digits necessary to
1401 + represent the value exactly.<br />
1402 + If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>,
1403 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used.
1404 + </p>
1405 + <p>
1406 + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
1407 + <code>dp</code> or <code>rm</code> values.
1408 + </p>
1409 + <pre>
1410 +x = 45.6
1411 +y = new BigNumber(x)
1412 +x.toExponential() // '4.56e+1'
1413 +y.toExponential() // '4.56e+1'
1414 +x.toExponential(0) // '5e+1'
1415 +y.toExponential(0) // '5e+1'
1416 +x.toExponential(1) // '4.6e+1'
1417 +y.toExponential(1) // '4.6e+1'
1418 +y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN)
1419 +x.toExponential(3) // '4.560e+1'
1420 +y.toExponential(3) // '4.560e+1'</pre>
1421 +
1422 +
1423 +
1424 + <h5 id="toFix">
1425 + toFixed<code class='inset'>.toFixed([dp [, rm]]) <i>&rArr; string</i></code>
1426 + </h5>
1427 + <p>
1428 + <code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br />
1429 + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive
1430 + </p>
1431 + <p>
1432 + Returns a string representing the value of this BigNumber in normal (fixed-point) notation
1433 + rounded to <code>dp</code> decimal places using rounding mode <code>rm</code>.
1434 + </p>
1435 + <p>
1436 + If the value of this BigNumber in normal notation has fewer than <code>dp</code> fraction
1437 + digits, the return value will be appended with zeros accordingly.
1438 + </p>
1439 + <p>
1440 + Unlike <code>Number.prototype.toFixed</code>, which returns exponential notation if a number
1441 + is greater or equal to <code>10<sup>21</sup></code>, this method will always return normal
1442 + notation.
1443 + </p>
1444 + <p>
1445 + If <code>dp</code> is omitted or is <code>null</code> or <code>undefined</code>, the return
1446 + value will be unrounded and in normal notation. This is also unlike
1447 + <code>Number.prototype.toFixed</code>, which returns the value to zero decimal places.<br />
1448 + It is useful when fixed-point notation is required and the current
1449 + <a href="#exponential-at"><code>EXPONENTIAL_AT</code></a> setting causes
1450 + <code><a href='#toS'>toString</a></code> to return exponential notation.<br />
1451 + If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>,
1452 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used.
1453 + </p>
1454 + <p>
1455 + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
1456 + <code>dp</code> or <code>rm</code> values.
1457 + </p>
1458 + <pre>
1459 +x = 3.456
1460 +y = new BigNumber(x)
1461 +x.toFixed() // '3'
1462 +y.toFixed() // '3.456'
1463 +y.toFixed(0) // '3'
1464 +x.toFixed(2) // '3.46'
1465 +y.toFixed(2) // '3.46'
1466 +y.toFixed(2, 1) // '3.45' (ROUND_DOWN)
1467 +x.toFixed(5) // '3.45600'
1468 +y.toFixed(5) // '3.45600'</pre>
1469 +
1470 +
1471 +
1472 + <h5 id="toFor">
1473 + toFormat<code class='inset'>.toFormat([dp [, rm]]) <i>&rArr; string</i></code>
1474 + </h5>
1475 + <p>
1476 + <code>dp</code>: <i>number</i>: integer, <code>0</code> to <code>1e+9</code> inclusive<br />
1477 + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive
1478 + </p>
1479 + <p>
1480 + <p>
1481 + Returns a string representing the value of this BigNumber in normal (fixed-point) notation
1482 + rounded to <code>dp</code> decimal places using rounding mode <code>rm</code>, and formatted
1483 + according to the properties of the <a href='#format'><code>FORMAT</code></a> object.
1484 + </p>
1485 + <p>
1486 + See the examples below for the properties of the
1487 + <a href='#format'><code>FORMAT</code></a> object, their types and their usage.
1488 + </p>
1489 + <p>
1490 + If <code>dp</code> is omitted or is <code>null</code> or <code>undefined</code>, then the
1491 + return value is not rounded to a fixed number of decimal places.<br />
1492 + If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>,
1493 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used.
1494 + </p>
1495 + <p>
1496 + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
1497 + <code>dp</code> or <code>rm</code> values.
1498 + </p>
1499 + <pre>
1500 +format = {
1501 + decimalSeparator: '.',
1502 + groupSeparator: ',',
1503 + groupSize: 3,
1504 + secondaryGroupSize: 0,
1505 + fractionGroupSeparator: ' ',
1506 + fractionGroupSize: 0
1507 +}
1508 +BigNumber.config({ FORMAT: format })
1509 +
1510 +x = new BigNumber('123456789.123456789')
1511 +x.toFormat() // '123,456,789.123456789'
1512 +x.toFormat(1) // '123,456,789.1'
1513 +
1514 +// If a reference to the object assigned to FORMAT has been retained,
1515 +// the format properties can be changed directly
1516 +format.groupSeparator = ' '
1517 +format.fractionGroupSize = 5
1518 +x.toFormat() // '123 456 789.12345 6789'
1519 +
1520 +BigNumber.config({
1521 + FORMAT: {
1522 + decimalSeparator: ',',
1523 + groupSeparator: '.',
1524 + groupSize: 3,
1525 + secondaryGroupSize: 2
1526 + }
1527 +})
1528 +
1529 +x.toFormat(6) // '12.34.56.789,123'</pre>
1530 +
1531 +
1532 +
1533 + <h5 id="toFr">
1534 + toFraction<code class='inset'>.toFraction([max]) <i>&rArr; [string, string]</i></code>
1535 + </h5>
1536 + <p>
1537 + <code>max</code>: <i>number|string|BigNumber</i>: integer &gt;= <code>1</code> and &lt;
1538 + <code>Infinity</code>
1539 + </p>
1540 + <p>
1541 + Returns a string array representing the value of this BigNumber as a simple fraction with an
1542 + integer numerator and an integer denominator. The denominator will be a positive non-zero
1543 + value less than or equal to <code>max</code>.
1544 + </p>
1545 + <p>
1546 + If a maximum denominator, <code>max</code>, is not specified, or is <code>null</code> or
1547 + <code>undefined</code>, the denominator will be the lowest value necessary to represent the
1548 + number exactly.
1549 + </p>
1550 + <p>
1551 + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
1552 + <code>max</code> values.
1553 + </p>
1554 + <pre>
1555 +x = new BigNumber(1.75)
1556 +x.toFraction() // '7, 4'
1557 +
1558 +pi = new BigNumber('3.14159265358')
1559 +pi.toFraction() // '157079632679,50000000000'
1560 +pi.toFraction(100000) // '312689, 99532'
1561 +pi.toFraction(10000) // '355, 113'
1562 +pi.toFraction(100) // '311, 99'
1563 +pi.toFraction(10) // '22, 7'
1564 +pi.toFraction(1) // '3, 1'</pre>
1565 +
1566 +
1567 +
1568 + <h5 id="toJSON">toJSON<code class='inset'>.toJSON() <i>&rArr; string</i></code></h5>
1569 + <p>As <code>valueOf</code>.</p>
1570 + <pre>
1571 +x = new BigNumber('177.7e+457')
1572 +y = new BigNumber(235.4325)
1573 +z = new BigNumber('0.0098074')
1574 +
1575 +// Serialize an array of three BigNumbers
1576 +str = JSON.stringify( [x, y, z] )
1577 +// "["1.777e+459","235.4325","0.0098074"]"
1578 +
1579 +// Return an array of three BigNumbers
1580 +JSON.parse(str, function (key, val) {
1581 + return key === '' ? val : new BigNumber(val)
1582 +})</pre>
1583 +
1584 +
1585 +
1586 + <h5 id="toN">toNumber<code class='inset'>.toNumber() <i>&rArr; number</i></code></h5>
1587 + <p>Returns the value of this BigNumber as a JavaScript number primitive.</p>
1588 + <p>
1589 + Type coercion with, for example, the unary plus operator will also work, except that a
1590 + BigNumber with the value minus zero will be converted to positive zero.
1591 + </p>
1592 + <pre>
1593 +x = new BigNumber(456.789)
1594 +x.toNumber() // 456.789
1595 ++x // 456.789
1596 +
1597 +y = new BigNumber('45987349857634085409857349856430985')
1598 +y.toNumber() // 4.598734985763409e+34
1599 +
1600 +z = new BigNumber(-0)
1601 +1 / +z // Infinity
1602 +1 / z.toNumber() // -Infinity</pre>
1603 +
1604 +
1605 +
1606 + <h5 id="pow">toPower<code class='inset'>.pow(n [, m]) <i>&rArr; BigNumber</i></code></h5>
1607 + <p>
1608 + <code>n</code>: <i>number</i>: integer,
1609 + <code>-9007199254740991</code> to <code>9007199254740991</code> inclusive<br />
1610 + <code>m</code>: <i>number|string|BigNumber</i>
1611 + </p>
1612 + <p>
1613 + Returns a BigNumber whose value is the value of this BigNumber raised to the power
1614 + <code>n</code>, and optionally modulo a modulus <code>m</code>.
1615 + </p>
1616 + <p>
1617 + If <code>n</code> is negative the result is rounded according to the current
1618 + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> and
1619 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration.
1620 + </p>
1621 + <p>
1622 + If <code>n</code> is not an integer or is out of range:
1623 + </p>
1624 + <p class='inset'>
1625 + If <code>ERRORS</code> is <code>true</code> a BigNumber Error is thrown,<br />
1626 + else if <code>n</code> is greater than <code>9007199254740991</code>, it is interpreted as
1627 + <code>Infinity</code>;<br />
1628 + else if <code>n</code> is less than <code>-9007199254740991</code>, it is interpreted as
1629 + <code>-Infinity</code>;<br />
1630 + else if <code>n</code> is otherwise a number, it is truncated to an integer;<br />
1631 + else it is interpreted as <code>NaN</code>.
1632 + </p>
1633 + <p>
1634 + As the number of digits of the result of the power operation can grow so large so quickly,
1635 + e.g. 123.456<sup>10000</sup> has over <code>50000</code> digits, the number of significant
1636 + digits calculated is limited to the value of the
1637 + <a href='#pow-precision'><code>POW_PRECISION</code></a> setting (unless a modulus
1638 + <code>m</code> is specified).
1639 + </p>
1640 + <p>
1641 + By default <a href='#pow-precision'><code>POW_PRECISION</code></a> is set to <code>0</code>.
1642 + This means that an unlimited number of significant digits will be calculated, and that the
1643 + method's performance will decrease dramatically for larger exponents.
1644 + </p>
1645 + <p>
1646 + Negative exponents will be calculated to the number of decimal places specified by
1647 + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a> (but not to more than
1648 + <a href='#pow-precision'><code>POW_PRECISION</code></a> significant digits).
1649 + </p>
1650 + <p>
1651 + If <code>m</code> is specified and the value of <code>m</code>, <code>n</code> and this
1652 + BigNumber are positive integers, then a fast modular exponentiation algorithm is used,
1653 + otherwise if any of the values is not a positive integer the operation will simply be
1654 + performed as <code>x.toPower(n).modulo(m)</code> with a
1655 + <a href='#pow-precision'><code>POW_PRECISION</code></a> of <code>0</code>.
1656 + </p>
1657 + <pre>
1658 +Math.pow(0.7, 2) // 0.48999999999999994
1659 +x = new BigNumber(0.7)
1660 +x.toPower(2) // '0.49'
1661 +BigNumber(3).pow(-2) // '0.11111111111111111111'</pre>
1662 +
1663 +
1664 +
1665 + <h5 id="toP">
1666 + toPrecision<code class='inset'>.toPrecision([sd [, rm]]) <i>&rArr; string</i></code>
1667 + </h5>
1668 + <p>
1669 + <code>sd</code>: <i>number</i>: integer, <code>1</code> to <code>1e+9</code> inclusive<br />
1670 + <code>rm</code>: <i>number</i>: integer, <code>0</code> to <code>8</code> inclusive
1671 + </p>
1672 + <p>
1673 + Returns a string representing the value of this BigNumber rounded to <code>sd</code>
1674 + significant digits using rounding mode <code>rm</code>.
1675 + </p>
1676 + <p>
1677 + If <code>sd</code> is less than the number of digits necessary to represent the integer part
1678 + of the value in normal (fixed-point) notation, then exponential notation is used.
1679 + </p>
1680 + <p>
1681 + If <code>sd</code> is omitted, or is <code>null</code> or <code>undefined</code>, then the
1682 + return value is the same as <code>n.toString()</code>.<br />
1683 + If <code>rm</code> is omitted or is <code>null</code> or <code>undefined</code>,
1684 + <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> is used.
1685 + </p>
1686 + <p>
1687 + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
1688 + <code>sd</code> or <code>rm</code> values.
1689 + </p>
1690 + <pre>
1691 +x = 45.6
1692 +y = new BigNumber(x)
1693 +x.toPrecision() // '45.6'
1694 +y.toPrecision() // '45.6'
1695 +x.toPrecision(1) // '5e+1'
1696 +y.toPrecision(1) // '5e+1'
1697 +y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP)
1698 +y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN)
1699 +x.toPrecision(5) // '45.600'
1700 +y.toPrecision(5) // '45.600'</pre>
1701 +
1702 +
1703 +
1704 + <h5 id="toS">toString<code class='inset'>.toString([base]) <i>&rArr; string</i></code></h5>
1705 + <p><code>base</code>: <i>number</i>: integer, <code>2</code> to <code>64</code> inclusive</p>
1706 + <p>
1707 + Returns a string representing the value of this BigNumber in the specified base, or base
1708 + <code>10</code> if <code>base</code> is omitted or is <code>null</code> or
1709 + <code>undefined</code>.
1710 + </p>
1711 + <p>
1712 + For bases above <code>10</code>, values from <code>10</code> to <code>35</code> are
1713 + represented by <code>a-z</code> (as with <code>Number.prototype.toString</code>),
1714 + <code>36</code> to <code>61</code> by <code>A-Z</code>, and <code>62</code> and
1715 + <code>63</code> by <code>$</code> and <code>_</code> respectively.
1716 + </p>
1717 + <p>
1718 + If a base is specified the value is rounded according to the current
1719 + <a href='#decimal-places'><code>DECIMAL_PLACES</code></a>
1720 + and <a href='#rounding-mode'><code>ROUNDING_MODE</code></a> configuration.
1721 + </p>
1722 + <p>
1723 + If a base is not specified, and this BigNumber has a positive
1724 + exponent that is equal to or greater than the positive component of the
1725 + current <a href="#exponential-at"><code>EXPONENTIAL_AT</code></a> setting,
1726 + or a negative exponent equal to or less than the negative component of the
1727 + setting, then exponential notation is returned.
1728 + </p>
1729 + <p>If <code>base</code> is <code>null</code> or <code>undefined</code> it is ignored.</p>
1730 + <p>
1731 + See <a href='#Errors'>Errors</a> for the treatment of other non-integer or out of range
1732 + <code>base</code> values.
1733 + </p>
1734 + <pre>
1735 +x = new BigNumber(750000)
1736 +x.toString() // '750000'
1737 +BigNumber.config({ EXPONENTIAL_AT: 5 })
1738 +x.toString() // '7.5e+5'
1739 +
1740 +y = new BigNumber(362.875)
1741 +y.toString(2) // '101101010.111'
1742 +y.toString(9) // '442.77777777777777777778'
1743 +y.toString(32) // 'ba.s'
1744 +
1745 +BigNumber.config({ DECIMAL_PLACES: 4 });
1746 +z = new BigNumber('1.23456789')
1747 +z.toString() // '1.23456789'
1748 +z.toString(10) // '1.2346'</pre>
1749 +
1750 +
1751 +
1752 + <h5 id="trunc">truncated<code class='inset'>.trunc() <i>&rArr; BigNumber</i></code></h5>
1753 + <p>
1754 + Returns a BigNumber whose value is the value of this BigNumber truncated to a whole number.
1755 + </p>
1756 + <pre>
1757 +x = new BigNumber(123.456)
1758 +x.truncated() // '123'
1759 +y = new BigNumber(-12.3)
1760 +y.trunc() // '-12'</pre>
1761 +
1762 +
1763 +
1764 + <h5 id="valueOf">valueOf<code class='inset'>.valueOf() <i>&rArr; string</i></code></h5>
1765 + <p>
1766 + As <code>toString</code>, but does not accept a base argument and includes the minus sign
1767 + for negative zero.
1768 + </p>
1769 + <pre>
1770 +x = new BigNumber('-0')
1771 +x.toString() // '0'
1772 +x.valueOf() // '-0'
1773 +y = new BigNumber('1.777e+457')
1774 +y.valueOf() // '1.777e+457'</pre>
1775 +
1776 +
1777 +
1778 + <h4 id="instance-properties">Properties</h4>
1779 + <p>The properties of a BigNumber instance:</p>
1780 + <table>
1781 + <tr>
1782 + <th>Property</th>
1783 + <th>Description</th>
1784 + <th>Type</th>
1785 + <th>Value</th>
1786 + </tr>
1787 + <tr>
1788 + <td class='centre' id='coefficient'><b>c</b></td>
1789 + <td>coefficient<sup>*</sup></td>
1790 + <td><i>number</i><code>[]</code></td>
1791 + <td> Array of base <code>1e14</code> numbers</td>
1792 + </tr>
1793 + <tr>
1794 + <td class='centre' id='exponent'><b>e</b></td>
1795 + <td>exponent</td>
1796 + <td><i>number</i></td>
1797 + <td>Integer, <code>-1000000000</code> to <code>1000000000</code> inclusive</td>
1798 + </tr>
1799 + <tr>
1800 + <td class='centre' id='sign'><b>s</b></td>
1801 + <td>sign</td>
1802 + <td><i>number</i></td>
1803 + <td><code>-1</code> or <code>1</code></td>
1804 + </tr>
1805 + <tr>
1806 + <td class='centre' id='isbig'><b>isBigNumber</b></td>
1807 + <td>type identifier</td>
1808 + <td><i>boolean</i></td>
1809 + <td><code>true</code></td>
1810 + </tr>
1811 + </table>
1812 + <p><sup>*</sup>significand</p>
1813 + <p>
1814 + The value of any of the <code>c</code>, <code>e</code> and <code>s</code> properties may also
1815 + be <code>null</code>.
1816 + </p>
1817 + <p>
1818 + From v2.0.0 of this library, the value of the coefficient of a BigNumber is stored in a
1819 + normalised base <code>100000000000000</code> floating point format, as opposed to the base
1820 + <code>10</code> format used in v1.x.x
1821 + </p>
1822 + <p>
1823 + This change means the properties of a BigNumber are now best considered to be read-only.
1824 + Previously it was acceptable to change the exponent of a BigNumber by writing to its exponent
1825 + property directly, but this is no longer recommended as the number of digits in the first
1826 + element of the coefficient array is dependent on the exponent, so the coefficient would also
1827 + need to be altered.
1828 + </p>
1829 + <p>
1830 + Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are
1831 + not necessarily preserved.
1832 + </p>
1833 + <pre>x = new BigNumber(0.123) // '0.123'
1834 +x.toExponential() // '1.23e-1'
1835 +x.c // '1,2,3'
1836 +x.e // -1
1837 +x.s // 1
1838 +
1839 +y = new Number(-123.4567000e+2) // '-12345.67'
1840 +y.toExponential() // '-1.234567e+4'
1841 +z = new BigNumber('-123.4567000e+2') // '-12345.67'
1842 +z.toExponential() // '-1.234567e+4'
1843 +z.c // '1,2,3,4,5,6,7'
1844 +z.e // 4
1845 +z.s // -1</pre>
1846 + <p>Checking if a value is a BigNumber instance:</p>
1847 + <pre>
1848 +x = new BigNumber(3)
1849 +x instanceof BigNumber // true
1850 +x.isBigNumber // true
1851 +
1852 +BN = BigNumber.another();
1853 +
1854 +y = new BN(3)
1855 +y instanceof BigNumber // false
1856 +y.isBigNumber // true</pre>
1857 +
1858 +
1859 +
1860 +
1861 + <h4 id="zero-nan-infinity">Zero, NaN and Infinity</h4>
1862 + <p>
1863 + The table below shows how &plusmn;<code>0</code>, <code>NaN</code> and
1864 + &plusmn;<code>Infinity</code> are stored.
1865 + </p>
1866 + <table>
1867 + <tr>
1868 + <th> </th>
1869 + <th class='centre'>c</th>
1870 + <th class='centre'>e</th>
1871 + <th class='centre'>s</th>
1872 + </tr>
1873 + <tr>
1874 + <td>&plusmn;0</td>
1875 + <td><code>[0]</code></td>
1876 + <td><code>0</code></td>
1877 + <td><code>&plusmn;1</code></td>
1878 + </tr>
1879 + <tr>
1880 + <td>NaN</td>
1881 + <td><code>null</code></td>
1882 + <td><code>null</code></td>
1883 + <td><code>null</code></td>
1884 + </tr>
1885 + <tr>
1886 + <td>&plusmn;Infinity</td>
1887 + <td><code>null</code></td>
1888 + <td><code>null</code></td>
1889 + <td><code>&plusmn;1</code></td>
1890 + </tr>
1891 + </table>
1892 + <pre>
1893 +x = new Number(-0) // 0
1894 +1 / x == -Infinity // true
1895 +
1896 +y = new BigNumber(-0) // '0'
1897 +y.c // '0' ( [0].toString() )
1898 +y.e // 0
1899 +y.s // -1</pre>
1900 +
1901 +
1902 +
1903 + <h4 id='Errors'>Errors</h4>
1904 + <p>
1905 + The errors that are thrown are generic <code>Error</code> objects with <code>name</code>
1906 + <i>BigNumber Error</i>.
1907 + </p>
1908 + <p>
1909 + The table below shows the errors that may be thrown if <code>ERRORS</code> is
1910 + <code>true</code>, and the action taken if <code>ERRORS</code> is <code>false</code>.
1911 + </p>
1912 + <table class='error-table'>
1913 + <tr>
1914 + <th>Method(s)</th>
1915 + <th>ERRORS: true<br />Throw BigNumber Error</th>
1916 + <th>ERRORS: false<br />Action on invalid argument</th>
1917 + </tr>
1918 + <tr>
1919 + <td rowspan=5>
1920 + <code>
1921 + BigNumber<br />
1922 + comparedTo<br />
1923 + dividedBy<br />
1924 + dividedToIntegerBy<br />
1925 + equals<br />
1926 + greaterThan<br />
1927 + greaterThanOrEqualTo<br />
1928 + lessThan<br />
1929 + lessThanOrEqualTo<br />
1930 + minus<br />
1931 + modulo<br />
1932 + plus<br />
1933 + times
1934 + </code></td>
1935 + <td>number type has more than<br />15 significant digits</td>
1936 + <td>Accept.</td>
1937 + </tr>
1938 + <tr>
1939 + <td>not a base... number</td>
1940 + <td>Substitute <code>NaN</code>.</td>
1941 + </tr>
1942 + <tr>
1943 + <td>base not an integer</td>
1944 + <td>Truncate to integer.<br />Ignore if not a number.</td>
1945 + </tr>
1946 + <tr>
1947 + <td>base out of range</td>
1948 + <td>Ignore.</td>
1949 + </tr>
1950 + <tr>
1951 + <td>not a number<sup>*</sup></td>
1952 + <td>Substitute <code>NaN</code>.</td>
1953 + </tr>
1954 + <tr>
1955 + <td><code>another</code></td>
1956 + <td>not an object</td>
1957 + <td>Ignore.</td>
1958 + </tr>
1959 + <tr>
1960 + <td rowspan=17><code>config</code></td>
1961 + <td><code>DECIMAL_PLACES</code> not an integer</td>
1962 + <td>Truncate to integer.<br />Ignore if not a number.</td>
1963 + </tr>
1964 + <tr>
1965 + <td><code>DECIMAL_PLACES</code> out of range</td>
1966 + <td>Ignore.</td>
1967 + </tr>
1968 + <tr>
1969 + <td><code>ROUNDING_MODE</code> not an integer</td>
1970 + <td>Truncate to integer.<br />Ignore if not a number.</td>
1971 + </tr>
1972 + <tr>
1973 + <td><code>ROUNDING_MODE</code> out of range</td>
1974 + <td>Ignore.</td>
1975 + </tr>
1976 + <tr>
1977 + <td><code>EXPONENTIAL_AT</code> not an integer<br />or not [integer, integer]</td>
1978 + <td>Truncate to integer(s).<br />Ignore if not number(s).</td>
1979 + </tr>
1980 + <tr>
1981 + <td><code>EXPONENTIAL_AT</code> out of range<br />or not [negative, positive]</td>
1982 + <td>Ignore.</td>
1983 + </tr>
1984 + <tr>
1985 + <td><code>RANGE</code> not an integer<br />or not [integer, integer]</td>
1986 + <td> Truncate to integer(s).<br />Ignore if not number(s).</td>
1987 + </tr>
1988 + <tr>
1989 + <td><code>RANGE</code> cannot be zero</td>
1990 + <td>Ignore.</td>
1991 + </tr>
1992 + <tr>
1993 + <td><code>RANGE</code> out of range<br />or not [negative, positive]</td>
1994 + <td>Ignore.</td>
1995 + </tr>
1996 + <tr>
1997 + <td><code>ERRORS</code> not a boolean<br />or binary digit</td>
1998 + <td>Ignore.</td>
1999 + </tr>
2000 + <tr>
2001 + <td><code>CRYPTO</code> not a boolean<br />or binary digit</td>
2002 + <td>Ignore.</td>
2003 + </tr>
2004 + <tr>
2005 + <td><code>CRYPTO</code> crypto unavailable</td>
2006 + <td>Ignore.</td>
2007 + </tr>
2008 + <tr>
2009 + <td><code>MODULO_MODE</code> not an integer</td>
2010 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2011 + </tr>
2012 + <tr>
2013 + <td><code>MODULO_MODE</code> out of range</td>
2014 + <td>Ignore.</td>
2015 + </tr>
2016 + <tr>
2017 + <td><code>POW_PRECISION</code> not an integer</td>
2018 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2019 + </tr>
2020 + <tr>
2021 + <td><code>POW_PRECISION</code> out of range</td>
2022 + <td>Ignore.</td>
2023 + </tr>
2024 + <tr>
2025 + <td><code>FORMAT</code> not an object</td>
2026 + <td>Ignore.</td>
2027 + </tr>
2028 + <tr>
2029 + <td><code>precision</code></td>
2030 + <td>argument not a boolean<br />or binary digit</td>
2031 + <td>Ignore.</td>
2032 + </tr>
2033 + <tr>
2034 + <td rowspan=4><code>round</code></td>
2035 + <td>decimal places not an integer</td>
2036 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2037 + </tr>
2038 + <tr>
2039 + <td>decimal places out of range</td>
2040 + <td>Ignore.</td>
2041 + </tr>
2042 + <tr>
2043 + <td>rounding mode not an integer</td>
2044 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2045 + </tr>
2046 + <tr>
2047 + <td>rounding mode out of range</td>
2048 + <td>Ignore.</td>
2049 + </tr>
2050 + <tr>
2051 + <td rowspan=2><code>shift</code></td>
2052 + <td>argument not an integer</td>
2053 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2054 + </tr>
2055 + <tr>
2056 + <td>argument out of range</td>
2057 + <td>Substitute &plusmn;<code>Infinity</code>.
2058 + </tr>
2059 + <tr>
2060 + <td rowspan=4>
2061 + <code>toExponential</code><br />
2062 + <code>toFixed</code><br />
2063 + <code>toFormat</code>
2064 + </td>
2065 + <td>decimal places not an integer</td>
2066 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2067 + </tr>
2068 + <tr>
2069 + <td>decimal places out of range</td>
2070 + <td>Ignore.</td>
2071 + </tr>
2072 + <tr>
2073 + <td>rounding mode not an integer</td>
2074 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2075 + </tr>
2076 + <tr>
2077 + <td>rounding mode out of range</td>
2078 + <td>Ignore.</td>
2079 + </tr>
2080 + <tr>
2081 + <td rowspan=2><code>toFraction</code></td>
2082 + <td>max denominator not an integer</td>
2083 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2084 + </tr>
2085 + <tr>
2086 + <td>max denominator out of range</td>
2087 + <td>Ignore.</td>
2088 + </tr>
2089 + <tr>
2090 + <td rowspan=4>
2091 + <code>toDigits</code><br />
2092 + <code>toPrecision</code>
2093 + </td>
2094 + <td>precision not an integer</td>
2095 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2096 + </tr>
2097 + <tr>
2098 + <td>precision out of range</td>
2099 + <td>Ignore.</td>
2100 + </tr>
2101 + <tr>
2102 + <td>rounding mode not an integer</td>
2103 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2104 + </tr>
2105 + <tr>
2106 + <td>rounding mode out of range</td>
2107 + <td>Ignore.</td>
2108 + </tr>
2109 + <tr>
2110 + <td rowspan=2><code>toPower</code></td>
2111 + <td>exponent not an integer</td>
2112 + <td>Truncate to integer.<br />Substitute <code>NaN</code> if not a number.</td>
2113 + </tr>
2114 + <tr>
2115 + <td>exponent out of range</td>
2116 + <td>Substitute &plusmn;<code>Infinity</code>.
2117 + </td>
2118 + </tr>
2119 + <tr>
2120 + <td rowspan=2><code>toString</code></td>
2121 + <td>base not an integer</td>
2122 + <td>Truncate to integer.<br />Ignore if not a number.</td>
2123 + </tr>
2124 + <tr>
2125 + <td>base out of range</td>
2126 + <td>Ignore.</td>
2127 + </tr>
2128 + </table>
2129 + <p><sup>*</sup>No error is thrown if the value is <code>NaN</code> or 'NaN'.</p>
2130 + <p>
2131 + The message of a <i>BigNumber Error</i> will also contain the name of the method from which
2132 + the error originated.
2133 + </p>
2134 + <p>To determine if an exception is a <i>BigNumber Error</i>:</p>
2135 + <pre>
2136 +try {
2137 + // ...
2138 +} catch (e) {
2139 + if ( e instanceof Error && e.name == 'BigNumber Error' ) {
2140 + // ...
2141 + }
2142 +}</pre>
2143 +
2144 +
2145 +
2146 + <h4 id='faq'>FAQ</h4>
2147 +
2148 + <h6>Why are trailing fractional zeros removed from BigNumbers?</h6>
2149 + <p>
2150 + Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the
2151 + precision of a value. This can be useful but the results of arithmetic operations can be
2152 + misleading.
2153 + </p>
2154 + <pre>
2155 +x = new BigDecimal("1.0")
2156 +y = new BigDecimal("1.1000")
2157 +z = x.add(y) // 2.1000
2158 +
2159 +x = new BigDecimal("1.20")
2160 +y = new BigDecimal("3.45000")
2161 +z = x.multiply(y) // 4.1400000</pre>
2162 + <p>
2163 + To specify the precision of a value is to specify that the value lies
2164 + within a certain range.
2165 + </p>
2166 + <p>
2167 + In the first example, <code>x</code> has a value of <code>1.0</code>. The trailing zero shows
2168 + the precision of the value, implying that it is in the range <code>0.95</code> to
2169 + <code>1.05</code>. Similarly, the precision indicated by the trailing zeros of <code>y</code>
2170 + indicates that the value is in the range <code>1.09995</code> to <code>1.10005</code>.
2171 + </p>
2172 + <p>
2173 + If we add the two lowest values in the ranges we have, <code>0.95 + 1.09995 = 2.04995</code>,
2174 + and if we add the two highest values we have, <code>1.05 + 1.10005 = 2.15005</code>, so the
2175 + range of the result of the addition implied by the precision of its operands is
2176 + <code>2.04995</code> to <code>2.15005</code>.
2177 + </p>
2178 + <p>
2179 + The result given by BigDecimal of <code>2.1000</code> however, indicates that the value is in
2180 + the range <code>2.09995</code> to <code>2.10005</code> and therefore the precision implied by
2181 + its trailing zeros may be misleading.
2182 + </p>
2183 + <p>
2184 + In the second example, the true range is <code>4.122744</code> to <code>4.157256</code> yet
2185 + the BigDecimal answer of <code>4.1400000</code> indicates a range of <code>4.13999995</code>
2186 + to <code>4.14000005</code>. Again, the precision implied by the trailing zeros may be
2187 + misleading.
2188 + </p>
2189 + <p>
2190 + This library, like binary floating point and most calculators, does not retain trailing
2191 + fractional zeros. Instead, the <code>toExponential</code>, <code>toFixed</code> and
2192 + <code>toPrecision</code> methods enable trailing zeros to be added if and when required.<br />
2193 + </p>
2194 + </div>
2195 +
2196 +</body>
2197 +</html>
1 +{
2 + "_from": "bignumber.js@4.1.0",
3 + "_id": "bignumber.js@4.1.0",
4 + "_inBundle": false,
5 + "_integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA==",
6 + "_location": "/bignumber.js",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "version",
10 + "registry": true,
11 + "raw": "bignumber.js@4.1.0",
12 + "name": "bignumber.js",
13 + "escapedName": "bignumber.js",
14 + "rawSpec": "4.1.0",
15 + "saveSpec": null,
16 + "fetchSpec": "4.1.0"
17 + },
18 + "_requiredBy": [
19 + "/mysql"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz",
22 + "_shasum": "db6f14067c140bd46624815a7916c92d9b6c24b1",
23 + "_spec": "bignumber.js@4.1.0",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/mysql",
25 + "author": {
26 + "name": "Michael Mclaughlin",
27 + "email": "M8ch88l@gmail.com"
28 + },
29 + "bugs": {
30 + "url": "https://github.com/MikeMcl/bignumber.js/issues"
31 + },
32 + "bundleDependencies": false,
33 + "deprecated": false,
34 + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
35 + "engines": {
36 + "node": "*"
37 + },
38 + "homepage": "https://github.com/MikeMcl/bignumber.js#readme",
39 + "keywords": [
40 + "arbitrary",
41 + "precision",
42 + "arithmetic",
43 + "big",
44 + "number",
45 + "decimal",
46 + "float",
47 + "biginteger",
48 + "bigdecimal",
49 + "bignumber",
50 + "bigint",
51 + "bignum"
52 + ],
53 + "license": "MIT",
54 + "main": "bignumber.js",
55 + "name": "bignumber.js",
56 + "repository": {
57 + "type": "git",
58 + "url": "git+https://github.com/MikeMcl/bignumber.js.git"
59 + },
60 + "scripts": {
61 + "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 */\"",
62 + "test": "node ./test/every-test.js"
63 + },
64 + "types": "bignumber.d.ts",
65 + "version": "4.1.0"
66 +}
1 +The MIT License (MIT)
2 +
3 +Copyright (c) 2013-2018 Petka Antonov
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in
13 +all copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 +THE SOFTWARE.
1 +<a href="http://promisesaplus.com/">
2 + <img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo"
3 + title="Promises/A+ 1.1 compliant" align="right" />
4 +</a>
5 +
6 +
7 +[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird)
8 +[![coverage-98%](https://img.shields.io/badge/coverage-98%25-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html)
9 +
10 +**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)
11 +
12 +# Introduction
13 +
14 +Bluebird is a fully featured promise library with focus on innovative features and performance
15 +
16 +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.
17 +
18 +For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x).
19 +
20 +### Note
21 +
22 +Promises in Node.js 10 are significantly faster than before. Bluebird still includes a lot of features like cancellation, iteration methods and warnings that native promises don't. If you are using Bluebird for performance rather than for those - please consider giving native promises a shot and running the benchmarks yourself.
23 +
24 +# Questions and issues
25 +
26 +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`.
27 +
28 +
29 +
30 +## Thanks
31 +
32 +Thanks to BrowserStack for providing us with a free account which lets us support old browsers like IE8.
33 +
34 +# License
35 +
36 +The MIT License (MIT)
37 +
38 +Copyright (c) 2013-2017 Petka Antonov
39 +
40 +Permission is hereby granted, free of charge, to any person obtaining a copy
41 +of this software and associated documentation files (the "Software"), to deal
42 +in the Software without restriction, including without limitation the rights
43 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
44 +copies of the Software, and to permit persons to whom the Software is
45 +furnished to do so, subject to the following conditions:
46 +
47 +The above copyright notice and this permission notice shall be included in
48 +all copies or substantial portions of the Software.
49 +
50 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
51 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
52 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
53 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
54 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
55 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
56 +THE SOFTWARE.
57 +
1 +[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html)
This diff could not be displayed because it is too large.
1 +/* @preserve
2 + * The MIT License (MIT)
3 + *
4 + * Copyright (c) 2013-2018 Petka Antonov
5 + *
6 + * Permission is hereby granted, free of charge, to any person obtaining a copy
7 + * of this software and associated documentation files (the "Software"), to deal
8 + * in the Software without restriction, including without limitation the rights
9 + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 + * copies of the Software, and to permit persons to whom the Software is
11 + * furnished to do so, subject to the following conditions:
12 + *
13 + * The above copyright notice and this permission notice shall be included in
14 + * all copies or substantial portions of the Software.
15 + *
16 + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 + * THE SOFTWARE.
23 + *
24 + */
25 +/**
26 + * bluebird build version 3.5.3
27 + * Features enabled: core
28 + * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
29 +*/
30 +!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 f(16),this._normalQueue=new f(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var t=this;this.drainQueues=function(){t._drainQueues()},this._schedule=p}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()}function s(t){for(;t.length()>0;)c(t)}function c(t){var e=t.shift();if("function"!=typeof e)e._settlePromises();else{var n=t.shift(),r=t.shift();e.call(n,r)}}var l;try{throw new Error}catch(u){l=u}var p=t("./schedule"),f=t("./queue"),h=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(){h.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")}},h.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._drainQueues=function(){s(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,s(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=l},{"./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: "+H.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function a(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 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 O(this._peekContext())}function _(t,e){if(V(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=k(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(){this._trace=void 0}function v(t,e,n,r,i){if(void 0===t&&null!==e&&J){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=w(s),l=c.length-1;l>=0;--l){var u=c[l];if(!q.test(u)){var p=u.match(G);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 y(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),g(n)}function g(t,n,r){if(st.warnings){var i,o=new I(t);if(n)r._attachExtraTrace(o);else if(st.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var a=k(o);o.stack=a.message+"\n"+a.stack.join("\n")}nt("warning",o)||j(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 b(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 C(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 w(t){for(var e=[],n=0;n<t.length;++n){var r=t[n],i=" (No stack trace)"===r||M.test(r),o=i&&it(r);i&&!o&&($&&" "!==r.charAt(0)&&(r=" "+r),e.push(r))}return e}function E(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||M.test(r))break}return n>0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function k(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?E(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:w(e)}}function j(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+W(i,t)}else r=e+String(t);"function"==typeof L?L(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function F(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){U.throwLater(o)}"unhandledRejection"===t?nt(t,n,r)||i||j(n,"Unhandled rejection "):nt(t,r)}function T(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"(<"+P(e)+">, no stack trace)"}function P(t){var e=41;return t.length<e?t:t.substr(0,e-3)+"..."}function R(){return"function"==typeof at}function S(t){var e=t.match(ot);return e?{fileName:e[1],line:parseInt(e[2],10)}:void 0}function x(t,e){if(R()){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=S(i[c]);if(l){n=l.fileName,a=l.line;break}}for(var c=0;c<o.length;++c){var l=S(o[c]);if(l){r=l.fileName,s=l.line;break}}0>a||0>s||!n||!r||n!==r||a>=s||(it=function(t){if(Q.test(t))return!0;var e=S(t);return e&&e.fileName===n&&a<=e.line&&e.line<=s?!0:!1})}}function O(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);at(this,O),e>32&&this.uncycle()}var A,N,L,B=e._getDomain,U=e._async,I=t("./errors").Warning,H=t("./util"),D=t("./es5"),V=H.canAttachTrace,Q=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,q=/\((?:timers\.js):\d+:\d+\)/,G=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,M=null,W=null,$=!1,z=!(0==H.env("BLUEBIRD_DEBUG")||!H.env("BLUEBIRD_DEBUG")&&"development"!==H.env("NODE_ENV")),X=!(0==H.env("BLUEBIRD_WARNINGS")||!z&&!H.env("BLUEBIRD_WARNINGS")),K=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!z&&!H.env("BLUEBIRD_LONG_STACK_TRACES")),J=0!=H.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(X||!!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(){F("rejectionHandled",A,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(),F("unhandledRejection",N,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 g(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=B();N="function"==typeof t?null===e?t:H.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=B();A="function"==typeof t?null===e?t:H.domainBind(e,t):void 0};var Y=function(){};e.longStackTraces=function(){if(U.haveItemsQueued()&&!st.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!st.longStackTraces&&R()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace,i=e.prototype._dereferenceTrace;st.longStackTraces=!0,Y=function(){if(U.haveItemsQueued()&&!st.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,e.prototype._dereferenceTrace=i,n.deactivateLongStackTraces(),U.enableTrampoline(),st.longStackTraces=!1},e.prototype._captureStackTrace=h,e.prototype._attachExtraTrace=_,e.prototype._dereferenceTrace=d,n.activateLongStackTraces(),U.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return st.longStackTraces&&R()};var Z=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n={detail:e,cancelable:!0};D.defineProperty(n,"promise",{value:e.promise}),D.defineProperty(n,"reason",{value:e.reason});var r=new CustomEvent(t.toLowerCase(),n);return!H.global.dispatchEvent(r)}}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,D.defineProperty(n,"promise",{value:e.promise}),D.defineProperty(n,"reason",{value:e.reason}),!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}}(),tt=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}}(),et={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},nt=function(t){var e=!1;try{e=tt.apply(null,arguments)}catch(n){U.throwLater(n),e=!0}var r=!1;try{r=Z(t,et[t].apply(null,arguments))}catch(n){U.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()&&Y()),"warnings"in t){var n=t.warnings;st.warnings=!!n,J=st.warnings,H.isObject(n)&&"wForgottenReturn"in n&&(J=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!st.cancellation){if(U.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,rt=u,st.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!st.monitoring?(st.monitoring=!0,e.prototype._fireEvent=nt):!t.monitoring&&st.monitoring&&(st.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._dereferenceTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var rt=p,it=function(){return!1},ot=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(O,Error),n.CapturedTrace=O,O.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}}}},O.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=k(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(w(i.stack.split("\n"))),i=i._parent;C(r),b(r),H.notEnumerableProp(t,"stack",m(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var at=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():T(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,M=t,W=e;var n=Error.captureStackTrace;return it=function(t){return Q.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 M=/@/,W=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?(W=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?T(e):e.toString()},null):(M=t,W=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&&(L=function(t){console.warn(t)},H.isNode&&process.stderr.isTTY?L=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:H.isNode||"string"!=typeof(new Error).stack||(L=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var st={warnings:X,longStackTraces:!1,cancellation:!1,monitoring:!1};return K&&e.longStackTraces(),{longStackTraces:function(){return st.longStackTraces},warnings:function(){return st.warnings},cancellation:function(){return st.cancellation},monitoring:function(){return st.monitoring},propagateFromFunction:function(){return rt},boundValueFunction:function(){return f},checkForgottenReturns:v,setBounds:x,warn:g,deprecated:y,CapturedTrace:O,fireDomEvent:Z,fireGlobalEvent:tt}}},{"./errors":9,"./es5":10,"./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){
31 +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),this._dereferenceTrace())}},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.3",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(){}function n(){return typeof r.foo}e.prototype=t;var r=new e;return n(),n(),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 ...\ No newline at end of file
This diff could not be displayed because it is too large.
1 +/* @preserve
2 + * The MIT License (MIT)
3 + *
4 + * Copyright (c) 2013-2018 Petka Antonov
5 + *
6 + * Permission is hereby granted, free of charge, to any person obtaining a copy
7 + * of this software and associated documentation files (the "Software"), to deal
8 + * in the Software without restriction, including without limitation the rights
9 + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 + * copies of the Software, and to permit persons to whom the Software is
11 + * furnished to do so, subject to the following conditions:
12 + *
13 + * The above copyright notice and this permission notice shall be included in
14 + * all copies or substantial portions of the Software.
15 + *
16 + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 + * THE SOFTWARE.
23 + *
24 + */
25 +/**
26 + * bluebird build version 3.5.3
27 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
28 +*/
29 +!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 h(16),this._normalQueue=new h(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var t=this;this.drainQueues=function(){t._drainQueues()},this._schedule=p}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()}function a(t){for(;t.length()>0;)c(t)}function c(t){var e=t.shift();if("function"!=typeof e)e._settlePromises();else{var n=t.shift(),r=t.shift();e.call(n,r)}}var l;try{throw new Error}catch(u){l=u}var p=t("./schedule"),h=t("./queue"),f=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(){f.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")}},f.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._drainQueues=function(){a(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,a(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=l},{"./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: "+N.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function s(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?N.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 O(this._peekContext())}function _(t,e){if(U(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=E(t);N.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),N.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(){this._trace=void 0}function v(t,e,n,r,i){if(void 0===t&&null!==e&&J){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=C(a),l=c.length-1;l>=0;--l){var u=c[l];if(!q.test(u)){var p=u.match($);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 y(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),m(n)}function m(t,n,r){if(at.warnings){var i,o=new H(t);if(n)r._attachExtraTrace(o);else if(at.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=E(o);o.stack=s.message+"\n"+s.stack.join("\n")}nt("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 b(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 w(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 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&&it(r);i&&!o&&(z&&" "!==r.charAt(0)&&(r=" "+r),e.push(r))}return e}function j(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?j(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(N.isObject(t)){var i=t.stack;r=e+G(i,t)}else r=e+String(t);"function"==typeof V?V(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function F(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){L.throwLater(o)}"unhandledRejection"===t?nt(t,n,r)||i||k(n,"Unhandled rejection "):nt(t,r)}function T(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():N.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 P(){return"function"==typeof st}function R(t){var e=t.match(ot);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"),s=-1,a=-1,c=0;c<i.length;++c){var l=R(i[c]);if(l){n=l.fileName,s=l.line;break}}for(var c=0;c<o.length;++c){var l=R(o[c]);if(l){r=l.fileName,a=l.line;break}}0>s||0>a||!n||!r||n!==r||s>=a||(it=function(t){if(M.test(t))return!0;var e=R(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function O(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);st(this,O),e>32&&this.uncycle()}var A,D,V,I=e._getDomain,L=e._async,H=t("./errors").Warning,N=t("./util"),B=t("./es5"),U=N.canAttachTrace,M=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,q=/\((?:timers\.js):\d+:\d+\)/,$=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,Q=null,G=null,z=!1,X=!(0==N.env("BLUEBIRD_DEBUG")||!N.env("BLUEBIRD_DEBUG")&&"development"!==N.env("NODE_ENV")),W=!(0==N.env("BLUEBIRD_WARNINGS")||!X&&!N.env("BLUEBIRD_WARNINGS")),K=!(0==N.env("BLUEBIRD_LONG_STACK_TRACES")||!X&&!N.env("BLUEBIRD_LONG_STACK_TRACES")),J=0!=N.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(W||!!N.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(){F("rejectionHandled",A,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(),F("unhandledRejection",D,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 m(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=I();D="function"==typeof t?null===e?t:N.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=I();A="function"==typeof t?null===e?t:N.domainBind(e,t):void 0};var Y=function(){};e.longStackTraces=function(){if(L.haveItemsQueued()&&!at.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!at.longStackTraces&&P()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace,i=e.prototype._dereferenceTrace;at.longStackTraces=!0,Y=function(){if(L.haveItemsQueued()&&!at.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,e.prototype._dereferenceTrace=i,n.deactivateLongStackTraces(),L.enableTrampoline(),at.longStackTraces=!1},e.prototype._captureStackTrace=f,e.prototype._attachExtraTrace=_,e.prototype._dereferenceTrace=d,n.activateLongStackTraces(),L.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return at.longStackTraces&&P()};var Z=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return N.global.dispatchEvent(t),function(t,e){var n={detail:e,cancelable:!0};B.defineProperty(n,"promise",{value:e.promise}),B.defineProperty(n,"reason",{value:e.reason});var r=new CustomEvent(t.toLowerCase(),n);return!N.global.dispatchEvent(r)}}if("function"==typeof Event){var t=new Event("CustomEvent");return N.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,B.defineProperty(n,"promise",{value:e.promise}),B.defineProperty(n,"reason",{value:e.reason}),!N.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),N.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!N.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),tt=function(){return N.isNode?function(){return process.emit.apply(process,arguments)}:N.global?function(t){var e="on"+t.toLowerCase(),n=N.global[e];return n?(n.apply(N.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),et={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},nt=function(t){var e=!1;try{e=tt.apply(null,arguments)}catch(n){L.throwLater(n),e=!0}var r=!1;try{r=Z(t,et[t].apply(null,arguments))}catch(n){L.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()&&Y()),"warnings"in t){var n=t.warnings;at.warnings=!!n,J=at.warnings,N.isObject(n)&&"wForgottenReturn"in n&&(J=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!at.cancellation){if(L.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,rt=u,at.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!at.monitoring?(at.monitoring=!0,e.prototype._fireEvent=nt):!t.monitoring&&at.monitoring&&(at.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._dereferenceTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var rt=p,it=function(){return!1},ot=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;N.inherits(O,Error),n.CapturedTrace=O,O.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}}}},O.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;w(r),b(r),N.notEnumerableProp(t,"stack",g(n,r)),N.notEnumerableProp(t,"__stackCleaned__",!0)}};var st=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():T(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,Q=t,G=e;var n=Error.captureStackTrace;return it=function(t){return M.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,z=!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?T(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&&(V=function(t){console.warn(t)},N.isNode&&process.stderr.isTTY?V=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:N.isNode||"string"!=typeof(new Error).stack||(V=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var at={warnings:W,longStackTraces:!1,cancellation:!1,monitoring:!1};return K&&e.longStackTraces(),{longStackTraces:function(){return at.longStackTraces},warnings:function(){return at.warnings},cancellation:function(){return at.cancellation},monitoring:function(){return at.monitoring},propagateFromFunction:function(){return rt},boundValueFunction:function(){return h},checkForgottenReturns:v,setBounds:S,warn:m,deprecated:y,CapturedTrace:O,fireDomEvent:Z,fireGlobalEvent:tt}}},{"./errors":12,"./es5":13,"./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")));
30 +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,T=t("./debuggability")(i,k),x=(T.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(T.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&&T.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):(T.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 x&&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),this._dereferenceTrace())}},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(){T.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,T),t("./bind")(i,b,j,T),t("./cancel")(i,E,p,T),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,E,j,b,v,c),i.Promise=i,i.version="3.5.3",t("./map.js")(i,E,p,j,b,T),t("./call_get.js")(i),t("./using.js")(i,p,j,F,b,T),t("./timers.js")(i,b,T),t("./generators.js")(i,p,b,j,n,T),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,T),t("./settle.js")(i,E,T),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)),T.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,
31 +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 x.e=e,x}}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(){}function n(){return typeof r.foo}e.prototype=t;var r=new e;return n(),n(),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"),T="undefined"==typeof navigator,x={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:T,errorObj:x,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 ...\ No newline at end of file
1 +"use strict";
2 +module.exports = function(Promise) {
3 +var SomePromiseArray = Promise._SomePromiseArray;
4 +function any(promises) {
5 + var ret = new SomePromiseArray(promises);
6 + var promise = ret.promise();
7 + ret.setHowMany(1);
8 + ret.setUnwrap();
9 + ret.init();
10 + return promise;
11 +}
12 +
13 +Promise.any = function (promises) {
14 + return any(promises);
15 +};
16 +
17 +Promise.prototype.any = function () {
18 + return any(this);
19 +};
20 +
21 +};
1 +"use strict";
2 +module.exports = (function(){
3 +var AssertionError = (function() {
4 + function AssertionError(a) {
5 + this.constructor$(a);
6 + this.message = a;
7 + this.name = "AssertionError";
8 + }
9 + AssertionError.prototype = new Error();
10 + AssertionError.prototype.constructor = AssertionError;
11 + AssertionError.prototype.constructor$ = Error;
12 + return AssertionError;
13 +})();
14 +
15 +function getParams(args) {
16 + var params = [];
17 + for (var i = 0; i < args.length; ++i) params.push("arg" + i);
18 + return params;
19 +}
20 +
21 +function nativeAssert(callName, args, expect) {
22 + try {
23 + var params = getParams(args);
24 + var constructorArgs = params;
25 + constructorArgs.push("return " +
26 + callName + "("+ params.join(",") + ");");
27 + var fn = Function.apply(null, constructorArgs);
28 + return fn.apply(null, args);
29 + } catch (e) {
30 + if (!(e instanceof SyntaxError)) {
31 + throw e;
32 + } else {
33 + return expect;
34 + }
35 + }
36 +}
37 +
38 +return function assert(boolExpr, message) {
39 + if (boolExpr === true) return;
40 +
41 + if (typeof boolExpr === "string" &&
42 + boolExpr.charAt(0) === "%") {
43 + var nativeCallName = boolExpr;
44 + 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];};
45 + if (nativeAssert(nativeCallName, args, message) === message) return;
46 + message = (nativeCallName + " !== " + message);
47 + }
48 +
49 + var ret = new AssertionError(message);
50 + if (Error.captureStackTrace) {
51 + Error.captureStackTrace(ret, assert);
52 + }
53 + throw ret;
54 +};
55 +})();
1 +"use strict";
2 +var firstLineError;
3 +try {throw new Error(); } catch (e) {firstLineError = e;}
4 +var schedule = require("./schedule");
5 +var Queue = require("./queue");
6 +var util = require("./util");
7 +
8 +function Async() {
9 + this._customScheduler = false;
10 + this._isTickUsed = false;
11 + this._lateQueue = new Queue(16);
12 + this._normalQueue = new Queue(16);
13 + this._haveDrainedQueues = false;
14 + this._trampolineEnabled = true;
15 + var self = this;
16 + this.drainQueues = function () {
17 + self._drainQueues();
18 + };
19 + this._schedule = schedule;
20 +}
21 +
22 +Async.prototype.setScheduler = function(fn) {
23 + var prev = this._schedule;
24 + this._schedule = fn;
25 + this._customScheduler = true;
26 + return prev;
27 +};
28 +
29 +Async.prototype.hasCustomScheduler = function() {
30 + return this._customScheduler;
31 +};
32 +
33 +Async.prototype.enableTrampoline = function() {
34 + this._trampolineEnabled = true;
35 +};
36 +
37 +Async.prototype.disableTrampolineIfNecessary = function() {
38 + if (util.hasDevTools) {
39 + this._trampolineEnabled = false;
40 + }
41 +};
42 +
43 +Async.prototype.haveItemsQueued = function () {
44 + return this._isTickUsed || this._haveDrainedQueues;
45 +};
46 +
47 +
48 +Async.prototype.fatalError = function(e, isNode) {
49 + if (isNode) {
50 + process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
51 + "\n");
52 + process.exit(2);
53 + } else {
54 + this.throwLater(e);
55 + }
56 +};
57 +
58 +Async.prototype.throwLater = function(fn, arg) {
59 + if (arguments.length === 1) {
60 + arg = fn;
61 + fn = function () { throw arg; };
62 + }
63 + if (typeof setTimeout !== "undefined") {
64 + setTimeout(function() {
65 + fn(arg);
66 + }, 0);
67 + } else try {
68 + this._schedule(function() {
69 + fn(arg);
70 + });
71 + } catch (e) {
72 + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
73 + }
74 +};
75 +
76 +function AsyncInvokeLater(fn, receiver, arg) {
77 + this._lateQueue.push(fn, receiver, arg);
78 + this._queueTick();
79 +}
80 +
81 +function AsyncInvoke(fn, receiver, arg) {
82 + this._normalQueue.push(fn, receiver, arg);
83 + this._queueTick();
84 +}
85 +
86 +function AsyncSettlePromises(promise) {
87 + this._normalQueue._pushOne(promise);
88 + this._queueTick();
89 +}
90 +
91 +if (!util.hasDevTools) {
92 + Async.prototype.invokeLater = AsyncInvokeLater;
93 + Async.prototype.invoke = AsyncInvoke;
94 + Async.prototype.settlePromises = AsyncSettlePromises;
95 +} else {
96 + Async.prototype.invokeLater = function (fn, receiver, arg) {
97 + if (this._trampolineEnabled) {
98 + AsyncInvokeLater.call(this, fn, receiver, arg);
99 + } else {
100 + this._schedule(function() {
101 + setTimeout(function() {
102 + fn.call(receiver, arg);
103 + }, 100);
104 + });
105 + }
106 + };
107 +
108 + Async.prototype.invoke = function (fn, receiver, arg) {
109 + if (this._trampolineEnabled) {
110 + AsyncInvoke.call(this, fn, receiver, arg);
111 + } else {
112 + this._schedule(function() {
113 + fn.call(receiver, arg);
114 + });
115 + }
116 + };
117 +
118 + Async.prototype.settlePromises = function(promise) {
119 + if (this._trampolineEnabled) {
120 + AsyncSettlePromises.call(this, promise);
121 + } else {
122 + this._schedule(function() {
123 + promise._settlePromises();
124 + });
125 + }
126 + };
127 +}
128 +
129 +function _drainQueue(queue) {
130 + while (queue.length() > 0) {
131 + _drainQueueStep(queue);
132 + }
133 +}
134 +
135 +function _drainQueueStep(queue) {
136 + var fn = queue.shift();
137 + if (typeof fn !== "function") {
138 + fn._settlePromises();
139 + } else {
140 + var receiver = queue.shift();
141 + var arg = queue.shift();
142 + fn.call(receiver, arg);
143 + }
144 +}
145 +
146 +Async.prototype._drainQueues = function () {
147 + _drainQueue(this._normalQueue);
148 + this._reset();
149 + this._haveDrainedQueues = true;
150 + _drainQueue(this._lateQueue);
151 +};
152 +
153 +Async.prototype._queueTick = function () {
154 + if (!this._isTickUsed) {
155 + this._isTickUsed = true;
156 + this._schedule(this.drainQueues);
157 + }
158 +};
159 +
160 +Async.prototype._reset = function () {
161 + this._isTickUsed = false;
162 +};
163 +
164 +module.exports = Async;
165 +module.exports.firstLineError = firstLineError;
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
3 +var calledBind = false;
4 +var rejectThis = function(_, e) {
5 + this._reject(e);
6 +};
7 +
8 +var targetRejected = function(e, context) {
9 + context.promiseRejectionQueued = true;
10 + context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
11 +};
12 +
13 +var bindingResolved = function(thisArg, context) {
14 + if (((this._bitField & 50397184) === 0)) {
15 + this._resolveCallback(context.target);
16 + }
17 +};
18 +
19 +var bindingRejected = function(e, context) {
20 + if (!context.promiseRejectionQueued) this._reject(e);
21 +};
22 +
23 +Promise.prototype.bind = function (thisArg) {
24 + if (!calledBind) {
25 + calledBind = true;
26 + Promise.prototype._propagateFrom = debug.propagateFromFunction();
27 + Promise.prototype._boundValue = debug.boundValueFunction();
28 + }
29 + var maybePromise = tryConvertToPromise(thisArg);
30 + var ret = new Promise(INTERNAL);
31 + ret._propagateFrom(this, 1);
32 + var target = this._target();
33 + ret._setBoundTo(maybePromise);
34 + if (maybePromise instanceof Promise) {
35 + var context = {
36 + promiseRejectionQueued: false,
37 + promise: ret,
38 + target: target,
39 + bindingPromise: maybePromise
40 + };
41 + target._then(INTERNAL, targetRejected, undefined, ret, context);
42 + maybePromise._then(
43 + bindingResolved, bindingRejected, undefined, ret, context);
44 + ret._setOnCancel(maybePromise);
45 + } else {
46 + ret._resolveCallback(target);
47 + }
48 + return ret;
49 +};
50 +
51 +Promise.prototype._setBoundTo = function (obj) {
52 + if (obj !== undefined) {
53 + this._bitField = this._bitField | 2097152;
54 + this._boundTo = obj;
55 + } else {
56 + this._bitField = this._bitField & (~2097152);
57 + }
58 +};
59 +
60 +Promise.prototype._isBound = function () {
61 + return (this._bitField & 2097152) === 2097152;
62 +};
63 +
64 +Promise.bind = function (thisArg, value) {
65 + return Promise.resolve(value).bind(thisArg);
66 +};
67 +};
1 +"use strict";
2 +var old;
3 +if (typeof Promise !== "undefined") old = Promise;
4 +function noConflict() {
5 + try { if (Promise === bluebird) Promise = old; }
6 + catch (e) {}
7 + return bluebird;
8 +}
9 +var bluebird = require("./promise")();
10 +bluebird.noConflict = noConflict;
11 +module.exports = bluebird;
1 +"use strict";
2 +var cr = Object.create;
3 +if (cr) {
4 + var callerCache = cr(null);
5 + var getterCache = cr(null);
6 + callerCache[" size"] = getterCache[" size"] = 0;
7 +}
8 +
9 +module.exports = function(Promise) {
10 +var util = require("./util");
11 +var canEvaluate = util.canEvaluate;
12 +var isIdentifier = util.isIdentifier;
13 +
14 +var getMethodCaller;
15 +var getGetter;
16 +if (!false) {
17 +var makeMethodCaller = function (methodName) {
18 + return new Function("ensureMethod", " \n\
19 + return function(obj) { \n\
20 + 'use strict' \n\
21 + var len = this.length; \n\
22 + ensureMethod(obj, 'methodName'); \n\
23 + switch(len) { \n\
24 + case 1: return obj.methodName(this[0]); \n\
25 + case 2: return obj.methodName(this[0], this[1]); \n\
26 + case 3: return obj.methodName(this[0], this[1], this[2]); \n\
27 + case 0: return obj.methodName(); \n\
28 + default: \n\
29 + return obj.methodName.apply(obj, this); \n\
30 + } \n\
31 + }; \n\
32 + ".replace(/methodName/g, methodName))(ensureMethod);
33 +};
34 +
35 +var makeGetter = function (propertyName) {
36 + return new Function("obj", " \n\
37 + 'use strict'; \n\
38 + return obj.propertyName; \n\
39 + ".replace("propertyName", propertyName));
40 +};
41 +
42 +var getCompiled = function(name, compiler, cache) {
43 + var ret = cache[name];
44 + if (typeof ret !== "function") {
45 + if (!isIdentifier(name)) {
46 + return null;
47 + }
48 + ret = compiler(name);
49 + cache[name] = ret;
50 + cache[" size"]++;
51 + if (cache[" size"] > 512) {
52 + var keys = Object.keys(cache);
53 + for (var i = 0; i < 256; ++i) delete cache[keys[i]];
54 + cache[" size"] = keys.length - 256;
55 + }
56 + }
57 + return ret;
58 +};
59 +
60 +getMethodCaller = function(name) {
61 + return getCompiled(name, makeMethodCaller, callerCache);
62 +};
63 +
64 +getGetter = function(name) {
65 + return getCompiled(name, makeGetter, getterCache);
66 +};
67 +}
68 +
69 +function ensureMethod(obj, methodName) {
70 + var fn;
71 + if (obj != null) fn = obj[methodName];
72 + if (typeof fn !== "function") {
73 + var message = "Object " + util.classString(obj) + " has no method '" +
74 + util.toString(methodName) + "'";
75 + throw new Promise.TypeError(message);
76 + }
77 + return fn;
78 +}
79 +
80 +function caller(obj) {
81 + var methodName = this.pop();
82 + var fn = ensureMethod(obj, methodName);
83 + return fn.apply(obj, this);
84 +}
85 +Promise.prototype.call = function (methodName) {
86 + 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];};
87 + if (!false) {
88 + if (canEvaluate) {
89 + var maybeCaller = getMethodCaller(methodName);
90 + if (maybeCaller !== null) {
91 + return this._then(
92 + maybeCaller, undefined, undefined, args, undefined);
93 + }
94 + }
95 + }
96 + args.push(methodName);
97 + return this._then(caller, undefined, undefined, args, undefined);
98 +};
99 +
100 +function namedGetter(obj) {
101 + return obj[this];
102 +}
103 +function indexedGetter(obj) {
104 + var index = +this;
105 + if (index < 0) index = Math.max(0, index + obj.length);
106 + return obj[index];
107 +}
108 +Promise.prototype.get = function (propertyName) {
109 + var isIndex = (typeof propertyName === "number");
110 + var getter;
111 + if (!isIndex) {
112 + if (canEvaluate) {
113 + var maybeGetter = getGetter(propertyName);
114 + getter = maybeGetter !== null ? maybeGetter : namedGetter;
115 + } else {
116 + getter = namedGetter;
117 + }
118 + } else {
119 + getter = indexedGetter;
120 + }
121 + return this._then(getter, undefined, undefined, propertyName, undefined);
122 +};
123 +};
1 +"use strict";
2 +module.exports = function(Promise, PromiseArray, apiRejection, debug) {
3 +var util = require("./util");
4 +var tryCatch = util.tryCatch;
5 +var errorObj = util.errorObj;
6 +var async = Promise._async;
7 +
8 +Promise.prototype["break"] = Promise.prototype.cancel = function() {
9 + if (!debug.cancellation()) return this._warn("cancellation is disabled");
10 +
11 + var promise = this;
12 + var child = promise;
13 + while (promise._isCancellable()) {
14 + if (!promise._cancelBy(child)) {
15 + if (child._isFollowing()) {
16 + child._followee().cancel();
17 + } else {
18 + child._cancelBranched();
19 + }
20 + break;
21 + }
22 +
23 + var parent = promise._cancellationParent;
24 + if (parent == null || !parent._isCancellable()) {
25 + if (promise._isFollowing()) {
26 + promise._followee().cancel();
27 + } else {
28 + promise._cancelBranched();
29 + }
30 + break;
31 + } else {
32 + if (promise._isFollowing()) promise._followee().cancel();
33 + promise._setWillBeCancelled();
34 + child = promise;
35 + promise = parent;
36 + }
37 + }
38 +};
39 +
40 +Promise.prototype._branchHasCancelled = function() {
41 + this._branchesRemainingToCancel--;
42 +};
43 +
44 +Promise.prototype._enoughBranchesHaveCancelled = function() {
45 + return this._branchesRemainingToCancel === undefined ||
46 + this._branchesRemainingToCancel <= 0;
47 +};
48 +
49 +Promise.prototype._cancelBy = function(canceller) {
50 + if (canceller === this) {
51 + this._branchesRemainingToCancel = 0;
52 + this._invokeOnCancel();
53 + return true;
54 + } else {
55 + this._branchHasCancelled();
56 + if (this._enoughBranchesHaveCancelled()) {
57 + this._invokeOnCancel();
58 + return true;
59 + }
60 + }
61 + return false;
62 +};
63 +
64 +Promise.prototype._cancelBranched = function() {
65 + if (this._enoughBranchesHaveCancelled()) {
66 + this._cancel();
67 + }
68 +};
69 +
70 +Promise.prototype._cancel = function() {
71 + if (!this._isCancellable()) return;
72 + this._setCancelled();
73 + async.invoke(this._cancelPromises, this, undefined);
74 +};
75 +
76 +Promise.prototype._cancelPromises = function() {
77 + if (this._length() > 0) this._settlePromises();
78 +};
79 +
80 +Promise.prototype._unsetOnCancel = function() {
81 + this._onCancelField = undefined;
82 +};
83 +
84 +Promise.prototype._isCancellable = function() {
85 + return this.isPending() && !this._isCancelled();
86 +};
87 +
88 +Promise.prototype.isCancellable = function() {
89 + return this.isPending() && !this.isCancelled();
90 +};
91 +
92 +Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
93 + if (util.isArray(onCancelCallback)) {
94 + for (var i = 0; i < onCancelCallback.length; ++i) {
95 + this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
96 + }
97 + } else if (onCancelCallback !== undefined) {
98 + if (typeof onCancelCallback === "function") {
99 + if (!internalOnly) {
100 + var e = tryCatch(onCancelCallback).call(this._boundValue());
101 + if (e === errorObj) {
102 + this._attachExtraTrace(e.e);
103 + async.throwLater(e.e);
104 + }
105 + }
106 + } else {
107 + onCancelCallback._resultCancelled(this);
108 + }
109 + }
110 +};
111 +
112 +Promise.prototype._invokeOnCancel = function() {
113 + var onCancelCallback = this._onCancel();
114 + this._unsetOnCancel();
115 + async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
116 +};
117 +
118 +Promise.prototype._invokeInternalOnCancel = function() {
119 + if (this._isCancellable()) {
120 + this._doInvokeOnCancel(this._onCancel(), true);
121 + this._unsetOnCancel();
122 + }
123 +};
124 +
125 +Promise.prototype._resultCancelled = function() {
126 + this.cancel();
127 +};
128 +
129 +};
1 +"use strict";
2 +module.exports = function(NEXT_FILTER) {
3 +var util = require("./util");
4 +var getKeys = require("./es5").keys;
5 +var tryCatch = util.tryCatch;
6 +var errorObj = util.errorObj;
7 +
8 +function catchFilter(instances, cb, promise) {
9 + return function(e) {
10 + var boundTo = promise._boundValue();
11 + predicateLoop: for (var i = 0; i < instances.length; ++i) {
12 + var item = instances[i];
13 +
14 + if (item === Error ||
15 + (item != null && item.prototype instanceof Error)) {
16 + if (e instanceof item) {
17 + return tryCatch(cb).call(boundTo, e);
18 + }
19 + } else if (typeof item === "function") {
20 + var matchesPredicate = tryCatch(item).call(boundTo, e);
21 + if (matchesPredicate === errorObj) {
22 + return matchesPredicate;
23 + } else if (matchesPredicate) {
24 + return tryCatch(cb).call(boundTo, e);
25 + }
26 + } else if (util.isObject(e)) {
27 + var keys = getKeys(item);
28 + for (var j = 0; j < keys.length; ++j) {
29 + var key = keys[j];
30 + if (item[key] != e[key]) {
31 + continue predicateLoop;
32 + }
33 + }
34 + return tryCatch(cb).call(boundTo, e);
35 + }
36 + }
37 + return NEXT_FILTER;
38 + };
39 +}
40 +
41 +return catchFilter;
42 +};
1 +"use strict";
2 +module.exports = function(Promise) {
3 +var longStackTraces = false;
4 +var contextStack = [];
5 +
6 +Promise.prototype._promiseCreated = function() {};
7 +Promise.prototype._pushContext = function() {};
8 +Promise.prototype._popContext = function() {return null;};
9 +Promise._peekContext = Promise.prototype._peekContext = function() {};
10 +
11 +function Context() {
12 + this._trace = new Context.CapturedTrace(peekContext());
13 +}
14 +Context.prototype._pushContext = function () {
15 + if (this._trace !== undefined) {
16 + this._trace._promiseCreated = null;
17 + contextStack.push(this._trace);
18 + }
19 +};
20 +
21 +Context.prototype._popContext = function () {
22 + if (this._trace !== undefined) {
23 + var trace = contextStack.pop();
24 + var ret = trace._promiseCreated;
25 + trace._promiseCreated = null;
26 + return ret;
27 + }
28 + return null;
29 +};
30 +
31 +function createContext() {
32 + if (longStackTraces) return new Context();
33 +}
34 +
35 +function peekContext() {
36 + var lastIndex = contextStack.length - 1;
37 + if (lastIndex >= 0) {
38 + return contextStack[lastIndex];
39 + }
40 + return undefined;
41 +}
42 +Context.CapturedTrace = null;
43 +Context.create = createContext;
44 +Context.deactivateLongStackTraces = function() {};
45 +Context.activateLongStackTraces = function() {
46 + var Promise_pushContext = Promise.prototype._pushContext;
47 + var Promise_popContext = Promise.prototype._popContext;
48 + var Promise_PeekContext = Promise._peekContext;
49 + var Promise_peekContext = Promise.prototype._peekContext;
50 + var Promise_promiseCreated = Promise.prototype._promiseCreated;
51 + Context.deactivateLongStackTraces = function() {
52 + Promise.prototype._pushContext = Promise_pushContext;
53 + Promise.prototype._popContext = Promise_popContext;
54 + Promise._peekContext = Promise_PeekContext;
55 + Promise.prototype._peekContext = Promise_peekContext;
56 + Promise.prototype._promiseCreated = Promise_promiseCreated;
57 + longStackTraces = false;
58 + };
59 + longStackTraces = true;
60 + Promise.prototype._pushContext = Context.prototype._pushContext;
61 + Promise.prototype._popContext = Context.prototype._popContext;
62 + Promise._peekContext = Promise.prototype._peekContext = peekContext;
63 + Promise.prototype._promiseCreated = function() {
64 + var ctx = this._peekContext();
65 + if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
66 + };
67 +};
68 +return Context;
69 +};
1 +"use strict";
2 +module.exports = function(Promise, Context) {
3 +var getDomain = Promise._getDomain;
4 +var async = Promise._async;
5 +var Warning = require("./errors").Warning;
6 +var util = require("./util");
7 +var es5 = require("./es5");
8 +var canAttachTrace = util.canAttachTrace;
9 +var unhandledRejectionHandled;
10 +var possiblyUnhandledRejection;
11 +var bluebirdFramePattern =
12 + /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
13 +var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
14 +var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
15 +var stackFramePattern = null;
16 +var formatStack = null;
17 +var indentStackFrames = false;
18 +var printWarning;
19 +var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
20 + (false ||
21 + util.env("BLUEBIRD_DEBUG") ||
22 + util.env("NODE_ENV") === "development"));
23 +
24 +var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
25 + (debugging || util.env("BLUEBIRD_WARNINGS")));
26 +
27 +var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
28 + (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
29 +
30 +var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
31 + (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
32 +
33 +Promise.prototype.suppressUnhandledRejections = function() {
34 + var target = this._target();
35 + target._bitField = ((target._bitField & (~1048576)) |
36 + 524288);
37 +};
38 +
39 +Promise.prototype._ensurePossibleRejectionHandled = function () {
40 + if ((this._bitField & 524288) !== 0) return;
41 + this._setRejectionIsUnhandled();
42 + var self = this;
43 + setTimeout(function() {
44 + self._notifyUnhandledRejection();
45 + }, 1);
46 +};
47 +
48 +Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
49 + fireRejectionEvent("rejectionHandled",
50 + unhandledRejectionHandled, undefined, this);
51 +};
52 +
53 +Promise.prototype._setReturnedNonUndefined = function() {
54 + this._bitField = this._bitField | 268435456;
55 +};
56 +
57 +Promise.prototype._returnedNonUndefined = function() {
58 + return (this._bitField & 268435456) !== 0;
59 +};
60 +
61 +Promise.prototype._notifyUnhandledRejection = function () {
62 + if (this._isRejectionUnhandled()) {
63 + var reason = this._settledValue();
64 + this._setUnhandledRejectionIsNotified();
65 + fireRejectionEvent("unhandledRejection",
66 + possiblyUnhandledRejection, reason, this);
67 + }
68 +};
69 +
70 +Promise.prototype._setUnhandledRejectionIsNotified = function () {
71 + this._bitField = this._bitField | 262144;
72 +};
73 +
74 +Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
75 + this._bitField = this._bitField & (~262144);
76 +};
77 +
78 +Promise.prototype._isUnhandledRejectionNotified = function () {
79 + return (this._bitField & 262144) > 0;
80 +};
81 +
82 +Promise.prototype._setRejectionIsUnhandled = function () {
83 + this._bitField = this._bitField | 1048576;
84 +};
85 +
86 +Promise.prototype._unsetRejectionIsUnhandled = function () {
87 + this._bitField = this._bitField & (~1048576);
88 + if (this._isUnhandledRejectionNotified()) {
89 + this._unsetUnhandledRejectionIsNotified();
90 + this._notifyUnhandledRejectionIsHandled();
91 + }
92 +};
93 +
94 +Promise.prototype._isRejectionUnhandled = function () {
95 + return (this._bitField & 1048576) > 0;
96 +};
97 +
98 +Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
99 + return warn(message, shouldUseOwnTrace, promise || this);
100 +};
101 +
102 +Promise.onPossiblyUnhandledRejection = function (fn) {
103 + var domain = getDomain();
104 + possiblyUnhandledRejection =
105 + typeof fn === "function" ? (domain === null ?
106 + fn : util.domainBind(domain, fn))
107 + : undefined;
108 +};
109 +
110 +Promise.onUnhandledRejectionHandled = function (fn) {
111 + var domain = getDomain();
112 + unhandledRejectionHandled =
113 + typeof fn === "function" ? (domain === null ?
114 + fn : util.domainBind(domain, fn))
115 + : undefined;
116 +};
117 +
118 +var disableLongStackTraces = function() {};
119 +Promise.longStackTraces = function () {
120 + if (async.haveItemsQueued() && !config.longStackTraces) {
121 + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
122 + }
123 + if (!config.longStackTraces && longStackTracesIsSupported()) {
124 + var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
125 + var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
126 + var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
127 + config.longStackTraces = true;
128 + disableLongStackTraces = function() {
129 + if (async.haveItemsQueued() && !config.longStackTraces) {
130 + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
131 + }
132 + Promise.prototype._captureStackTrace = Promise_captureStackTrace;
133 + Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
134 + Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
135 + Context.deactivateLongStackTraces();
136 + async.enableTrampoline();
137 + config.longStackTraces = false;
138 + };
139 + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
140 + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
141 + Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
142 + Context.activateLongStackTraces();
143 + async.disableTrampolineIfNecessary();
144 + }
145 +};
146 +
147 +Promise.hasLongStackTraces = function () {
148 + return config.longStackTraces && longStackTracesIsSupported();
149 +};
150 +
151 +var fireDomEvent = (function() {
152 + try {
153 + if (typeof CustomEvent === "function") {
154 + var event = new CustomEvent("CustomEvent");
155 + util.global.dispatchEvent(event);
156 + return function(name, event) {
157 + var eventData = {
158 + detail: event,
159 + cancelable: true
160 + };
161 + es5.defineProperty(
162 + eventData, "promise", {value: event.promise});
163 + es5.defineProperty(eventData, "reason", {value: event.reason});
164 + var domEvent = new CustomEvent(name.toLowerCase(), eventData);
165 + return !util.global.dispatchEvent(domEvent);
166 + };
167 + } else if (typeof Event === "function") {
168 + var event = new Event("CustomEvent");
169 + util.global.dispatchEvent(event);
170 + return function(name, event) {
171 + var domEvent = new Event(name.toLowerCase(), {
172 + cancelable: true
173 + });
174 + domEvent.detail = event;
175 + es5.defineProperty(domEvent, "promise", {value: event.promise});
176 + es5.defineProperty(domEvent, "reason", {value: event.reason});
177 + return !util.global.dispatchEvent(domEvent);
178 + };
179 + } else {
180 + var event = document.createEvent("CustomEvent");
181 + event.initCustomEvent("testingtheevent", false, true, {});
182 + util.global.dispatchEvent(event);
183 + return function(name, event) {
184 + var domEvent = document.createEvent("CustomEvent");
185 + domEvent.initCustomEvent(name.toLowerCase(), false, true,
186 + event);
187 + return !util.global.dispatchEvent(domEvent);
188 + };
189 + }
190 + } catch (e) {}
191 + return function() {
192 + return false;
193 + };
194 +})();
195 +
196 +var fireGlobalEvent = (function() {
197 + if (util.isNode) {
198 + return function() {
199 + return process.emit.apply(process, arguments);
200 + };
201 + } else {
202 + if (!util.global) {
203 + return function() {
204 + return false;
205 + };
206 + }
207 + return function(name) {
208 + var methodName = "on" + name.toLowerCase();
209 + var method = util.global[methodName];
210 + if (!method) return false;
211 + method.apply(util.global, [].slice.call(arguments, 1));
212 + return true;
213 + };
214 + }
215 +})();
216 +
217 +function generatePromiseLifecycleEventObject(name, promise) {
218 + return {promise: promise};
219 +}
220 +
221 +var eventToObjectGenerator = {
222 + promiseCreated: generatePromiseLifecycleEventObject,
223 + promiseFulfilled: generatePromiseLifecycleEventObject,
224 + promiseRejected: generatePromiseLifecycleEventObject,
225 + promiseResolved: generatePromiseLifecycleEventObject,
226 + promiseCancelled: generatePromiseLifecycleEventObject,
227 + promiseChained: function(name, promise, child) {
228 + return {promise: promise, child: child};
229 + },
230 + warning: function(name, warning) {
231 + return {warning: warning};
232 + },
233 + unhandledRejection: function (name, reason, promise) {
234 + return {reason: reason, promise: promise};
235 + },
236 + rejectionHandled: generatePromiseLifecycleEventObject
237 +};
238 +
239 +var activeFireEvent = function (name) {
240 + var globalEventFired = false;
241 + try {
242 + globalEventFired = fireGlobalEvent.apply(null, arguments);
243 + } catch (e) {
244 + async.throwLater(e);
245 + globalEventFired = true;
246 + }
247 +
248 + var domEventFired = false;
249 + try {
250 + domEventFired = fireDomEvent(name,
251 + eventToObjectGenerator[name].apply(null, arguments));
252 + } catch (e) {
253 + async.throwLater(e);
254 + domEventFired = true;
255 + }
256 +
257 + return domEventFired || globalEventFired;
258 +};
259 +
260 +Promise.config = function(opts) {
261 + opts = Object(opts);
262 + if ("longStackTraces" in opts) {
263 + if (opts.longStackTraces) {
264 + Promise.longStackTraces();
265 + } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
266 + disableLongStackTraces();
267 + }
268 + }
269 + if ("warnings" in opts) {
270 + var warningsOption = opts.warnings;
271 + config.warnings = !!warningsOption;
272 + wForgottenReturn = config.warnings;
273 +
274 + if (util.isObject(warningsOption)) {
275 + if ("wForgottenReturn" in warningsOption) {
276 + wForgottenReturn = !!warningsOption.wForgottenReturn;
277 + }
278 + }
279 + }
280 + if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
281 + if (async.haveItemsQueued()) {
282 + throw new Error(
283 + "cannot enable cancellation after promises are in use");
284 + }
285 + Promise.prototype._clearCancellationData =
286 + cancellationClearCancellationData;
287 + Promise.prototype._propagateFrom = cancellationPropagateFrom;
288 + Promise.prototype._onCancel = cancellationOnCancel;
289 + Promise.prototype._setOnCancel = cancellationSetOnCancel;
290 + Promise.prototype._attachCancellationCallback =
291 + cancellationAttachCancellationCallback;
292 + Promise.prototype._execute = cancellationExecute;
293 + propagateFromFunction = cancellationPropagateFrom;
294 + config.cancellation = true;
295 + }
296 + if ("monitoring" in opts) {
297 + if (opts.monitoring && !config.monitoring) {
298 + config.monitoring = true;
299 + Promise.prototype._fireEvent = activeFireEvent;
300 + } else if (!opts.monitoring && config.monitoring) {
301 + config.monitoring = false;
302 + Promise.prototype._fireEvent = defaultFireEvent;
303 + }
304 + }
305 + return Promise;
306 +};
307 +
308 +function defaultFireEvent() { return false; }
309 +
310 +Promise.prototype._fireEvent = defaultFireEvent;
311 +Promise.prototype._execute = function(executor, resolve, reject) {
312 + try {
313 + executor(resolve, reject);
314 + } catch (e) {
315 + return e;
316 + }
317 +};
318 +Promise.prototype._onCancel = function () {};
319 +Promise.prototype._setOnCancel = function (handler) { ; };
320 +Promise.prototype._attachCancellationCallback = function(onCancel) {
321 + ;
322 +};
323 +Promise.prototype._captureStackTrace = function () {};
324 +Promise.prototype._attachExtraTrace = function () {};
325 +Promise.prototype._dereferenceTrace = function () {};
326 +Promise.prototype._clearCancellationData = function() {};
327 +Promise.prototype._propagateFrom = function (parent, flags) {
328 + ;
329 + ;
330 +};
331 +
332 +function cancellationExecute(executor, resolve, reject) {
333 + var promise = this;
334 + try {
335 + executor(resolve, reject, function(onCancel) {
336 + if (typeof onCancel !== "function") {
337 + throw new TypeError("onCancel must be a function, got: " +
338 + util.toString(onCancel));
339 + }
340 + promise._attachCancellationCallback(onCancel);
341 + });
342 + } catch (e) {
343 + return e;
344 + }
345 +}
346 +
347 +function cancellationAttachCancellationCallback(onCancel) {
348 + if (!this._isCancellable()) return this;
349 +
350 + var previousOnCancel = this._onCancel();
351 + if (previousOnCancel !== undefined) {
352 + if (util.isArray(previousOnCancel)) {
353 + previousOnCancel.push(onCancel);
354 + } else {
355 + this._setOnCancel([previousOnCancel, onCancel]);
356 + }
357 + } else {
358 + this._setOnCancel(onCancel);
359 + }
360 +}
361 +
362 +function cancellationOnCancel() {
363 + return this._onCancelField;
364 +}
365 +
366 +function cancellationSetOnCancel(onCancel) {
367 + this._onCancelField = onCancel;
368 +}
369 +
370 +function cancellationClearCancellationData() {
371 + this._cancellationParent = undefined;
372 + this._onCancelField = undefined;
373 +}
374 +
375 +function cancellationPropagateFrom(parent, flags) {
376 + if ((flags & 1) !== 0) {
377 + this._cancellationParent = parent;
378 + var branchesRemainingToCancel = parent._branchesRemainingToCancel;
379 + if (branchesRemainingToCancel === undefined) {
380 + branchesRemainingToCancel = 0;
381 + }
382 + parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
383 + }
384 + if ((flags & 2) !== 0 && parent._isBound()) {
385 + this._setBoundTo(parent._boundTo);
386 + }
387 +}
388 +
389 +function bindingPropagateFrom(parent, flags) {
390 + if ((flags & 2) !== 0 && parent._isBound()) {
391 + this._setBoundTo(parent._boundTo);
392 + }
393 +}
394 +var propagateFromFunction = bindingPropagateFrom;
395 +
396 +function boundValueFunction() {
397 + var ret = this._boundTo;
398 + if (ret !== undefined) {
399 + if (ret instanceof Promise) {
400 + if (ret.isFulfilled()) {
401 + return ret.value();
402 + } else {
403 + return undefined;
404 + }
405 + }
406 + }
407 + return ret;
408 +}
409 +
410 +function longStackTracesCaptureStackTrace() {
411 + this._trace = new CapturedTrace(this._peekContext());
412 +}
413 +
414 +function longStackTracesAttachExtraTrace(error, ignoreSelf) {
415 + if (canAttachTrace(error)) {
416 + var trace = this._trace;
417 + if (trace !== undefined) {
418 + if (ignoreSelf) trace = trace._parent;
419 + }
420 + if (trace !== undefined) {
421 + trace.attachExtraTrace(error);
422 + } else if (!error.__stackCleaned__) {
423 + var parsed = parseStackAndMessage(error);
424 + util.notEnumerableProp(error, "stack",
425 + parsed.message + "\n" + parsed.stack.join("\n"));
426 + util.notEnumerableProp(error, "__stackCleaned__", true);
427 + }
428 + }
429 +}
430 +
431 +function longStackTracesDereferenceTrace() {
432 + this._trace = undefined;
433 +}
434 +
435 +function checkForgottenReturns(returnValue, promiseCreated, name, promise,
436 + parent) {
437 + if (returnValue === undefined && promiseCreated !== null &&
438 + wForgottenReturn) {
439 + if (parent !== undefined && parent._returnedNonUndefined()) return;
440 + if ((promise._bitField & 65535) === 0) return;
441 +
442 + if (name) name = name + " ";
443 + var handlerLine = "";
444 + var creatorLine = "";
445 + if (promiseCreated._trace) {
446 + var traceLines = promiseCreated._trace.stack.split("\n");
447 + var stack = cleanStack(traceLines);
448 + for (var i = stack.length - 1; i >= 0; --i) {
449 + var line = stack[i];
450 + if (!nodeFramePattern.test(line)) {
451 + var lineMatches = line.match(parseLinePattern);
452 + if (lineMatches) {
453 + handlerLine = "at " + lineMatches[1] +
454 + ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
455 + }
456 + break;
457 + }
458 + }
459 +
460 + if (stack.length > 0) {
461 + var firstUserLine = stack[0];
462 + for (var i = 0; i < traceLines.length; ++i) {
463 +
464 + if (traceLines[i] === firstUserLine) {
465 + if (i > 0) {
466 + creatorLine = "\n" + traceLines[i - 1];
467 + }
468 + break;
469 + }
470 + }
471 +
472 + }
473 + }
474 + var msg = "a promise was created in a " + name +
475 + "handler " + handlerLine + "but was not returned from it, " +
476 + "see http://goo.gl/rRqMUw" +
477 + creatorLine;
478 + promise._warn(msg, true, promiseCreated);
479 + }
480 +}
481 +
482 +function deprecated(name, replacement) {
483 + var message = name +
484 + " is deprecated and will be removed in a future version.";
485 + if (replacement) message += " Use " + replacement + " instead.";
486 + return warn(message);
487 +}
488 +
489 +function warn(message, shouldUseOwnTrace, promise) {
490 + if (!config.warnings) return;
491 + var warning = new Warning(message);
492 + var ctx;
493 + if (shouldUseOwnTrace) {
494 + promise._attachExtraTrace(warning);
495 + } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
496 + ctx.attachExtraTrace(warning);
497 + } else {
498 + var parsed = parseStackAndMessage(warning);
499 + warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
500 + }
501 +
502 + if (!activeFireEvent("warning", warning)) {
503 + formatAndLogError(warning, "", true);
504 + }
505 +}
506 +
507 +function reconstructStack(message, stacks) {
508 + for (var i = 0; i < stacks.length - 1; ++i) {
509 + stacks[i].push("From previous event:");
510 + stacks[i] = stacks[i].join("\n");
511 + }
512 + if (i < stacks.length) {
513 + stacks[i] = stacks[i].join("\n");
514 + }
515 + return message + "\n" + stacks.join("\n");
516 +}
517 +
518 +function removeDuplicateOrEmptyJumps(stacks) {
519 + for (var i = 0; i < stacks.length; ++i) {
520 + if (stacks[i].length === 0 ||
521 + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
522 + stacks.splice(i, 1);
523 + i--;
524 + }
525 + }
526 +}
527 +
528 +function removeCommonRoots(stacks) {
529 + var current = stacks[0];
530 + for (var i = 1; i < stacks.length; ++i) {
531 + var prev = stacks[i];
532 + var currentLastIndex = current.length - 1;
533 + var currentLastLine = current[currentLastIndex];
534 + var commonRootMeetPoint = -1;
535 +
536 + for (var j = prev.length - 1; j >= 0; --j) {
537 + if (prev[j] === currentLastLine) {
538 + commonRootMeetPoint = j;
539 + break;
540 + }
541 + }
542 +
543 + for (var j = commonRootMeetPoint; j >= 0; --j) {
544 + var line = prev[j];
545 + if (current[currentLastIndex] === line) {
546 + current.pop();
547 + currentLastIndex--;
548 + } else {
549 + break;
550 + }
551 + }
552 + current = prev;
553 + }
554 +}
555 +
556 +function cleanStack(stack) {
557 + var ret = [];
558 + for (var i = 0; i < stack.length; ++i) {
559 + var line = stack[i];
560 + var isTraceLine = " (No stack trace)" === line ||
561 + stackFramePattern.test(line);
562 + var isInternalFrame = isTraceLine && shouldIgnore(line);
563 + if (isTraceLine && !isInternalFrame) {
564 + if (indentStackFrames && line.charAt(0) !== " ") {
565 + line = " " + line;
566 + }
567 + ret.push(line);
568 + }
569 + }
570 + return ret;
571 +}
572 +
573 +function stackFramesAsArray(error) {
574 + var stack = error.stack.replace(/\s+$/g, "").split("\n");
575 + for (var i = 0; i < stack.length; ++i) {
576 + var line = stack[i];
577 + if (" (No stack trace)" === line || stackFramePattern.test(line)) {
578 + break;
579 + }
580 + }
581 + if (i > 0 && error.name != "SyntaxError") {
582 + stack = stack.slice(i);
583 + }
584 + return stack;
585 +}
586 +
587 +function parseStackAndMessage(error) {
588 + var stack = error.stack;
589 + var message = error.toString();
590 + stack = typeof stack === "string" && stack.length > 0
591 + ? stackFramesAsArray(error) : [" (No stack trace)"];
592 + return {
593 + message: message,
594 + stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
595 + };
596 +}
597 +
598 +function formatAndLogError(error, title, isSoft) {
599 + if (typeof console !== "undefined") {
600 + var message;
601 + if (util.isObject(error)) {
602 + var stack = error.stack;
603 + message = title + formatStack(stack, error);
604 + } else {
605 + message = title + String(error);
606 + }
607 + if (typeof printWarning === "function") {
608 + printWarning(message, isSoft);
609 + } else if (typeof console.log === "function" ||
610 + typeof console.log === "object") {
611 + console.log(message);
612 + }
613 + }
614 +}
615 +
616 +function fireRejectionEvent(name, localHandler, reason, promise) {
617 + var localEventFired = false;
618 + try {
619 + if (typeof localHandler === "function") {
620 + localEventFired = true;
621 + if (name === "rejectionHandled") {
622 + localHandler(promise);
623 + } else {
624 + localHandler(reason, promise);
625 + }
626 + }
627 + } catch (e) {
628 + async.throwLater(e);
629 + }
630 +
631 + if (name === "unhandledRejection") {
632 + if (!activeFireEvent(name, reason, promise) && !localEventFired) {
633 + formatAndLogError(reason, "Unhandled rejection ");
634 + }
635 + } else {
636 + activeFireEvent(name, promise);
637 + }
638 +}
639 +
640 +function formatNonError(obj) {
641 + var str;
642 + if (typeof obj === "function") {
643 + str = "[function " +
644 + (obj.name || "anonymous") +
645 + "]";
646 + } else {
647 + str = obj && typeof obj.toString === "function"
648 + ? obj.toString() : util.toString(obj);
649 + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
650 + if (ruselessToString.test(str)) {
651 + try {
652 + var newStr = JSON.stringify(obj);
653 + str = newStr;
654 + }
655 + catch(e) {
656 +
657 + }
658 + }
659 + if (str.length === 0) {
660 + str = "(empty array)";
661 + }
662 + }
663 + return ("(<" + snip(str) + ">, no stack trace)");
664 +}
665 +
666 +function snip(str) {
667 + var maxChars = 41;
668 + if (str.length < maxChars) {
669 + return str;
670 + }
671 + return str.substr(0, maxChars - 3) + "...";
672 +}
673 +
674 +function longStackTracesIsSupported() {
675 + return typeof captureStackTrace === "function";
676 +}
677 +
678 +var shouldIgnore = function() { return false; };
679 +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
680 +function parseLineInfo(line) {
681 + var matches = line.match(parseLineInfoRegex);
682 + if (matches) {
683 + return {
684 + fileName: matches[1],
685 + line: parseInt(matches[2], 10)
686 + };
687 + }
688 +}
689 +
690 +function setBounds(firstLineError, lastLineError) {
691 + if (!longStackTracesIsSupported()) return;
692 + var firstStackLines = firstLineError.stack.split("\n");
693 + var lastStackLines = lastLineError.stack.split("\n");
694 + var firstIndex = -1;
695 + var lastIndex = -1;
696 + var firstFileName;
697 + var lastFileName;
698 + for (var i = 0; i < firstStackLines.length; ++i) {
699 + var result = parseLineInfo(firstStackLines[i]);
700 + if (result) {
701 + firstFileName = result.fileName;
702 + firstIndex = result.line;
703 + break;
704 + }
705 + }
706 + for (var i = 0; i < lastStackLines.length; ++i) {
707 + var result = parseLineInfo(lastStackLines[i]);
708 + if (result) {
709 + lastFileName = result.fileName;
710 + lastIndex = result.line;
711 + break;
712 + }
713 + }
714 + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
715 + firstFileName !== lastFileName || firstIndex >= lastIndex) {
716 + return;
717 + }
718 +
719 + shouldIgnore = function(line) {
720 + if (bluebirdFramePattern.test(line)) return true;
721 + var info = parseLineInfo(line);
722 + if (info) {
723 + if (info.fileName === firstFileName &&
724 + (firstIndex <= info.line && info.line <= lastIndex)) {
725 + return true;
726 + }
727 + }
728 + return false;
729 + };
730 +}
731 +
732 +function CapturedTrace(parent) {
733 + this._parent = parent;
734 + this._promisesCreated = 0;
735 + var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
736 + captureStackTrace(this, CapturedTrace);
737 + if (length > 32) this.uncycle();
738 +}
739 +util.inherits(CapturedTrace, Error);
740 +Context.CapturedTrace = CapturedTrace;
741 +
742 +CapturedTrace.prototype.uncycle = function() {
743 + var length = this._length;
744 + if (length < 2) return;
745 + var nodes = [];
746 + var stackToIndex = {};
747 +
748 + for (var i = 0, node = this; node !== undefined; ++i) {
749 + nodes.push(node);
750 + node = node._parent;
751 + }
752 + length = this._length = i;
753 + for (var i = length - 1; i >= 0; --i) {
754 + var stack = nodes[i].stack;
755 + if (stackToIndex[stack] === undefined) {
756 + stackToIndex[stack] = i;
757 + }
758 + }
759 + for (var i = 0; i < length; ++i) {
760 + var currentStack = nodes[i].stack;
761 + var index = stackToIndex[currentStack];
762 + if (index !== undefined && index !== i) {
763 + if (index > 0) {
764 + nodes[index - 1]._parent = undefined;
765 + nodes[index - 1]._length = 1;
766 + }
767 + nodes[i]._parent = undefined;
768 + nodes[i]._length = 1;
769 + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
770 +
771 + if (index < length - 1) {
772 + cycleEdgeNode._parent = nodes[index + 1];
773 + cycleEdgeNode._parent.uncycle();
774 + cycleEdgeNode._length =
775 + cycleEdgeNode._parent._length + 1;
776 + } else {
777 + cycleEdgeNode._parent = undefined;
778 + cycleEdgeNode._length = 1;
779 + }
780 + var currentChildLength = cycleEdgeNode._length + 1;
781 + for (var j = i - 2; j >= 0; --j) {
782 + nodes[j]._length = currentChildLength;
783 + currentChildLength++;
784 + }
785 + return;
786 + }
787 + }
788 +};
789 +
790 +CapturedTrace.prototype.attachExtraTrace = function(error) {
791 + if (error.__stackCleaned__) return;
792 + this.uncycle();
793 + var parsed = parseStackAndMessage(error);
794 + var message = parsed.message;
795 + var stacks = [parsed.stack];
796 +
797 + var trace = this;
798 + while (trace !== undefined) {
799 + stacks.push(cleanStack(trace.stack.split("\n")));
800 + trace = trace._parent;
801 + }
802 + removeCommonRoots(stacks);
803 + removeDuplicateOrEmptyJumps(stacks);
804 + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
805 + util.notEnumerableProp(error, "__stackCleaned__", true);
806 +};
807 +
808 +var captureStackTrace = (function stackDetection() {
809 + var v8stackFramePattern = /^\s*at\s*/;
810 + var v8stackFormatter = function(stack, error) {
811 + if (typeof stack === "string") return stack;
812 +
813 + if (error.name !== undefined &&
814 + error.message !== undefined) {
815 + return error.toString();
816 + }
817 + return formatNonError(error);
818 + };
819 +
820 + if (typeof Error.stackTraceLimit === "number" &&
821 + typeof Error.captureStackTrace === "function") {
822 + Error.stackTraceLimit += 6;
823 + stackFramePattern = v8stackFramePattern;
824 + formatStack = v8stackFormatter;
825 + var captureStackTrace = Error.captureStackTrace;
826 +
827 + shouldIgnore = function(line) {
828 + return bluebirdFramePattern.test(line);
829 + };
830 + return function(receiver, ignoreUntil) {
831 + Error.stackTraceLimit += 6;
832 + captureStackTrace(receiver, ignoreUntil);
833 + Error.stackTraceLimit -= 6;
834 + };
835 + }
836 + var err = new Error();
837 +
838 + if (typeof err.stack === "string" &&
839 + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
840 + stackFramePattern = /@/;
841 + formatStack = v8stackFormatter;
842 + indentStackFrames = true;
843 + return function captureStackTrace(o) {
844 + o.stack = new Error().stack;
845 + };
846 + }
847 +
848 + var hasStackAfterThrow;
849 + try { throw new Error(); }
850 + catch(e) {
851 + hasStackAfterThrow = ("stack" in e);
852 + }
853 + if (!("stack" in err) && hasStackAfterThrow &&
854 + typeof Error.stackTraceLimit === "number") {
855 + stackFramePattern = v8stackFramePattern;
856 + formatStack = v8stackFormatter;
857 + return function captureStackTrace(o) {
858 + Error.stackTraceLimit += 6;
859 + try { throw new Error(); }
860 + catch(e) { o.stack = e.stack; }
861 + Error.stackTraceLimit -= 6;
862 + };
863 + }
864 +
865 + formatStack = function(stack, error) {
866 + if (typeof stack === "string") return stack;
867 +
868 + if ((typeof error === "object" ||
869 + typeof error === "function") &&
870 + error.name !== undefined &&
871 + error.message !== undefined) {
872 + return error.toString();
873 + }
874 + return formatNonError(error);
875 + };
876 +
877 + return null;
878 +
879 +})([]);
880 +
881 +if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
882 + printWarning = function (message) {
883 + console.warn(message);
884 + };
885 + if (util.isNode && process.stderr.isTTY) {
886 + printWarning = function(message, isSoft) {
887 + var color = isSoft ? "\u001b[33m" : "\u001b[31m";
888 + console.warn(color + message + "\u001b[0m\n");
889 + };
890 + } else if (!util.isNode && typeof (new Error().stack) === "string") {
891 + printWarning = function(message, isSoft) {
892 + console.warn("%c" + message,
893 + isSoft ? "color: darkorange" : "color: red");
894 + };
895 + }
896 +}
897 +
898 +var config = {
899 + warnings: warnings,
900 + longStackTraces: false,
901 + cancellation: false,
902 + monitoring: false
903 +};
904 +
905 +if (longStackTraces) Promise.longStackTraces();
906 +
907 +return {
908 + longStackTraces: function() {
909 + return config.longStackTraces;
910 + },
911 + warnings: function() {
912 + return config.warnings;
913 + },
914 + cancellation: function() {
915 + return config.cancellation;
916 + },
917 + monitoring: function() {
918 + return config.monitoring;
919 + },
920 + propagateFromFunction: function() {
921 + return propagateFromFunction;
922 + },
923 + boundValueFunction: function() {
924 + return boundValueFunction;
925 + },
926 + checkForgottenReturns: checkForgottenReturns,
927 + setBounds: setBounds,
928 + warn: warn,
929 + deprecated: deprecated,
930 + CapturedTrace: CapturedTrace,
931 + fireDomEvent: fireDomEvent,
932 + fireGlobalEvent: fireGlobalEvent
933 +};
934 +};
1 +"use strict";
2 +module.exports = function(Promise) {
3 +function returner() {
4 + return this.value;
5 +}
6 +function thrower() {
7 + throw this.reason;
8 +}
9 +
10 +Promise.prototype["return"] =
11 +Promise.prototype.thenReturn = function (value) {
12 + if (value instanceof Promise) value.suppressUnhandledRejections();
13 + return this._then(
14 + returner, undefined, undefined, {value: value}, undefined);
15 +};
16 +
17 +Promise.prototype["throw"] =
18 +Promise.prototype.thenThrow = function (reason) {
19 + return this._then(
20 + thrower, undefined, undefined, {reason: reason}, undefined);
21 +};
22 +
23 +Promise.prototype.catchThrow = function (reason) {
24 + if (arguments.length <= 1) {
25 + return this._then(
26 + undefined, thrower, undefined, {reason: reason}, undefined);
27 + } else {
28 + var _reason = arguments[1];
29 + var handler = function() {throw _reason;};
30 + return this.caught(reason, handler);
31 + }
32 +};
33 +
34 +Promise.prototype.catchReturn = function (value) {
35 + if (arguments.length <= 1) {
36 + if (value instanceof Promise) value.suppressUnhandledRejections();
37 + return this._then(
38 + undefined, returner, undefined, {value: value}, undefined);
39 + } else {
40 + var _value = arguments[1];
41 + if (_value instanceof Promise) _value.suppressUnhandledRejections();
42 + var handler = function() {return _value;};
43 + return this.caught(value, handler);
44 + }
45 +};
46 +};
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL) {
3 +var PromiseReduce = Promise.reduce;
4 +var PromiseAll = Promise.all;
5 +
6 +function promiseAllThis() {
7 + return PromiseAll(this);
8 +}
9 +
10 +function PromiseMapSeries(promises, fn) {
11 + return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
12 +}
13 +
14 +Promise.prototype.each = function (fn) {
15 + return PromiseReduce(this, fn, INTERNAL, 0)
16 + ._then(promiseAllThis, undefined, undefined, this, undefined);
17 +};
18 +
19 +Promise.prototype.mapSeries = function (fn) {
20 + return PromiseReduce(this, fn, INTERNAL, INTERNAL);
21 +};
22 +
23 +Promise.each = function (promises, fn) {
24 + return PromiseReduce(promises, fn, INTERNAL, 0)
25 + ._then(promiseAllThis, undefined, undefined, promises, undefined);
26 +};
27 +
28 +Promise.mapSeries = PromiseMapSeries;
29 +};
30 +
1 +"use strict";
2 +var es5 = require("./es5");
3 +var Objectfreeze = es5.freeze;
4 +var util = require("./util");
5 +var inherits = util.inherits;
6 +var notEnumerableProp = util.notEnumerableProp;
7 +
8 +function subError(nameProperty, defaultMessage) {
9 + function SubError(message) {
10 + if (!(this instanceof SubError)) return new SubError(message);
11 + notEnumerableProp(this, "message",
12 + typeof message === "string" ? message : defaultMessage);
13 + notEnumerableProp(this, "name", nameProperty);
14 + if (Error.captureStackTrace) {
15 + Error.captureStackTrace(this, this.constructor);
16 + } else {
17 + Error.call(this);
18 + }
19 + }
20 + inherits(SubError, Error);
21 + return SubError;
22 +}
23 +
24 +var _TypeError, _RangeError;
25 +var Warning = subError("Warning", "warning");
26 +var CancellationError = subError("CancellationError", "cancellation error");
27 +var TimeoutError = subError("TimeoutError", "timeout error");
28 +var AggregateError = subError("AggregateError", "aggregate error");
29 +try {
30 + _TypeError = TypeError;
31 + _RangeError = RangeError;
32 +} catch(e) {
33 + _TypeError = subError("TypeError", "type error");
34 + _RangeError = subError("RangeError", "range error");
35 +}
36 +
37 +var methods = ("join pop push shift unshift slice filter forEach some " +
38 + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
39 +
40 +for (var i = 0; i < methods.length; ++i) {
41 + if (typeof Array.prototype[methods[i]] === "function") {
42 + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
43 + }
44 +}
45 +
46 +es5.defineProperty(AggregateError.prototype, "length", {
47 + value: 0,
48 + configurable: false,
49 + writable: true,
50 + enumerable: true
51 +});
52 +AggregateError.prototype["isOperational"] = true;
53 +var level = 0;
54 +AggregateError.prototype.toString = function() {
55 + var indent = Array(level * 4 + 1).join(" ");
56 + var ret = "\n" + indent + "AggregateError of:" + "\n";
57 + level++;
58 + indent = Array(level * 4 + 1).join(" ");
59 + for (var i = 0; i < this.length; ++i) {
60 + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
61 + var lines = str.split("\n");
62 + for (var j = 0; j < lines.length; ++j) {
63 + lines[j] = indent + lines[j];
64 + }
65 + str = lines.join("\n");
66 + ret += str + "\n";
67 + }
68 + level--;
69 + return ret;
70 +};
71 +
72 +function OperationalError(message) {
73 + if (!(this instanceof OperationalError))
74 + return new OperationalError(message);
75 + notEnumerableProp(this, "name", "OperationalError");
76 + notEnumerableProp(this, "message", message);
77 + this.cause = message;
78 + this["isOperational"] = true;
79 +
80 + if (message instanceof Error) {
81 + notEnumerableProp(this, "message", message.message);
82 + notEnumerableProp(this, "stack", message.stack);
83 + } else if (Error.captureStackTrace) {
84 + Error.captureStackTrace(this, this.constructor);
85 + }
86 +
87 +}
88 +inherits(OperationalError, Error);
89 +
90 +var errorTypes = Error["__BluebirdErrorTypes__"];
91 +if (!errorTypes) {
92 + errorTypes = Objectfreeze({
93 + CancellationError: CancellationError,
94 + TimeoutError: TimeoutError,
95 + OperationalError: OperationalError,
96 + RejectionError: OperationalError,
97 + AggregateError: AggregateError
98 + });
99 + es5.defineProperty(Error, "__BluebirdErrorTypes__", {
100 + value: errorTypes,
101 + writable: false,
102 + enumerable: false,
103 + configurable: false
104 + });
105 +}
106 +
107 +module.exports = {
108 + Error: Error,
109 + TypeError: _TypeError,
110 + RangeError: _RangeError,
111 + CancellationError: errorTypes.CancellationError,
112 + OperationalError: errorTypes.OperationalError,
113 + TimeoutError: errorTypes.TimeoutError,
114 + AggregateError: errorTypes.AggregateError,
115 + Warning: Warning
116 +};
1 +var isES5 = (function(){
2 + "use strict";
3 + return this === undefined;
4 +})();
5 +
6 +if (isES5) {
7 + module.exports = {
8 + freeze: Object.freeze,
9 + defineProperty: Object.defineProperty,
10 + getDescriptor: Object.getOwnPropertyDescriptor,
11 + keys: Object.keys,
12 + names: Object.getOwnPropertyNames,
13 + getPrototypeOf: Object.getPrototypeOf,
14 + isArray: Array.isArray,
15 + isES5: isES5,
16 + propertyIsWritable: function(obj, prop) {
17 + var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
18 + return !!(!descriptor || descriptor.writable || descriptor.set);
19 + }
20 + };
21 +} else {
22 + var has = {}.hasOwnProperty;
23 + var str = {}.toString;
24 + var proto = {}.constructor.prototype;
25 +
26 + var ObjectKeys = function (o) {
27 + var ret = [];
28 + for (var key in o) {
29 + if (has.call(o, key)) {
30 + ret.push(key);
31 + }
32 + }
33 + return ret;
34 + };
35 +
36 + var ObjectGetDescriptor = function(o, key) {
37 + return {value: o[key]};
38 + };
39 +
40 + var ObjectDefineProperty = function (o, key, desc) {
41 + o[key] = desc.value;
42 + return o;
43 + };
44 +
45 + var ObjectFreeze = function (obj) {
46 + return obj;
47 + };
48 +
49 + var ObjectGetPrototypeOf = function (obj) {
50 + try {
51 + return Object(obj).constructor.prototype;
52 + }
53 + catch (e) {
54 + return proto;
55 + }
56 + };
57 +
58 + var ArrayIsArray = function (obj) {
59 + try {
60 + return str.call(obj) === "[object Array]";
61 + }
62 + catch(e) {
63 + return false;
64 + }
65 + };
66 +
67 + module.exports = {
68 + isArray: ArrayIsArray,
69 + keys: ObjectKeys,
70 + names: ObjectKeys,
71 + defineProperty: ObjectDefineProperty,
72 + getDescriptor: ObjectGetDescriptor,
73 + freeze: ObjectFreeze,
74 + getPrototypeOf: ObjectGetPrototypeOf,
75 + isES5: isES5,
76 + propertyIsWritable: function() {
77 + return true;
78 + }
79 + };
80 +}
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL) {
3 +var PromiseMap = Promise.map;
4 +
5 +Promise.prototype.filter = function (fn, options) {
6 + return PromiseMap(this, fn, options, INTERNAL);
7 +};
8 +
9 +Promise.filter = function (promises, fn, options) {
10 + return PromiseMap(promises, fn, options, INTERNAL);
11 +};
12 +};
1 +"use strict";
2 +module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
3 +var util = require("./util");
4 +var CancellationError = Promise.CancellationError;
5 +var errorObj = util.errorObj;
6 +var catchFilter = require("./catch_filter")(NEXT_FILTER);
7 +
8 +function PassThroughHandlerContext(promise, type, handler) {
9 + this.promise = promise;
10 + this.type = type;
11 + this.handler = handler;
12 + this.called = false;
13 + this.cancelPromise = null;
14 +}
15 +
16 +PassThroughHandlerContext.prototype.isFinallyHandler = function() {
17 + return this.type === 0;
18 +};
19 +
20 +function FinallyHandlerCancelReaction(finallyHandler) {
21 + this.finallyHandler = finallyHandler;
22 +}
23 +
24 +FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
25 + checkCancel(this.finallyHandler);
26 +};
27 +
28 +function checkCancel(ctx, reason) {
29 + if (ctx.cancelPromise != null) {
30 + if (arguments.length > 1) {
31 + ctx.cancelPromise._reject(reason);
32 + } else {
33 + ctx.cancelPromise._cancel();
34 + }
35 + ctx.cancelPromise = null;
36 + return true;
37 + }
38 + return false;
39 +}
40 +
41 +function succeed() {
42 + return finallyHandler.call(this, this.promise._target()._settledValue());
43 +}
44 +function fail(reason) {
45 + if (checkCancel(this, reason)) return;
46 + errorObj.e = reason;
47 + return errorObj;
48 +}
49 +function finallyHandler(reasonOrValue) {
50 + var promise = this.promise;
51 + var handler = this.handler;
52 +
53 + if (!this.called) {
54 + this.called = true;
55 + var ret = this.isFinallyHandler()
56 + ? handler.call(promise._boundValue())
57 + : handler.call(promise._boundValue(), reasonOrValue);
58 + if (ret === NEXT_FILTER) {
59 + return ret;
60 + } else if (ret !== undefined) {
61 + promise._setReturnedNonUndefined();
62 + var maybePromise = tryConvertToPromise(ret, promise);
63 + if (maybePromise instanceof Promise) {
64 + if (this.cancelPromise != null) {
65 + if (maybePromise._isCancelled()) {
66 + var reason =
67 + new CancellationError("late cancellation observer");
68 + promise._attachExtraTrace(reason);
69 + errorObj.e = reason;
70 + return errorObj;
71 + } else if (maybePromise.isPending()) {
72 + maybePromise._attachCancellationCallback(
73 + new FinallyHandlerCancelReaction(this));
74 + }
75 + }
76 + return maybePromise._then(
77 + succeed, fail, undefined, this, undefined);
78 + }
79 + }
80 + }
81 +
82 + if (promise.isRejected()) {
83 + checkCancel(this);
84 + errorObj.e = reasonOrValue;
85 + return errorObj;
86 + } else {
87 + checkCancel(this);
88 + return reasonOrValue;
89 + }
90 +}
91 +
92 +Promise.prototype._passThrough = function(handler, type, success, fail) {
93 + if (typeof handler !== "function") return this.then();
94 + return this._then(success,
95 + fail,
96 + undefined,
97 + new PassThroughHandlerContext(this, type, handler),
98 + undefined);
99 +};
100 +
101 +Promise.prototype.lastly =
102 +Promise.prototype["finally"] = function (handler) {
103 + return this._passThrough(handler,
104 + 0,
105 + finallyHandler,
106 + finallyHandler);
107 +};
108 +
109 +
110 +Promise.prototype.tap = function (handler) {
111 + return this._passThrough(handler, 1, finallyHandler);
112 +};
113 +
114 +Promise.prototype.tapCatch = function (handlerOrPredicate) {
115 + var len = arguments.length;
116 + if(len === 1) {
117 + return this._passThrough(handlerOrPredicate,
118 + 1,
119 + undefined,
120 + finallyHandler);
121 + } else {
122 + var catchInstances = new Array(len - 1),
123 + j = 0, i;
124 + for (i = 0; i < len - 1; ++i) {
125 + var item = arguments[i];
126 + if (util.isObject(item)) {
127 + catchInstances[j++] = item;
128 + } else {
129 + return Promise.reject(new TypeError(
130 + "tapCatch statement predicate: "
131 + + "expecting an object but got " + util.classString(item)
132 + ));
133 + }
134 + }
135 + catchInstances.length = j;
136 + var handler = arguments[i];
137 + return this._passThrough(catchFilter(catchInstances, handler, this),
138 + 1,
139 + undefined,
140 + finallyHandler);
141 + }
142 +
143 +};
144 +
145 +return PassThroughHandlerContext;
146 +};
1 +"use strict";
2 +module.exports = function(Promise,
3 + apiRejection,
4 + INTERNAL,
5 + tryConvertToPromise,
6 + Proxyable,
7 + debug) {
8 +var errors = require("./errors");
9 +var TypeError = errors.TypeError;
10 +var util = require("./util");
11 +var errorObj = util.errorObj;
12 +var tryCatch = util.tryCatch;
13 +var yieldHandlers = [];
14 +
15 +function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
16 + for (var i = 0; i < yieldHandlers.length; ++i) {
17 + traceParent._pushContext();
18 + var result = tryCatch(yieldHandlers[i])(value);
19 + traceParent._popContext();
20 + if (result === errorObj) {
21 + traceParent._pushContext();
22 + var ret = Promise.reject(errorObj.e);
23 + traceParent._popContext();
24 + return ret;
25 + }
26 + var maybePromise = tryConvertToPromise(result, traceParent);
27 + if (maybePromise instanceof Promise) return maybePromise;
28 + }
29 + return null;
30 +}
31 +
32 +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
33 + if (debug.cancellation()) {
34 + var internal = new Promise(INTERNAL);
35 + var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
36 + this._promise = internal.lastly(function() {
37 + return _finallyPromise;
38 + });
39 + internal._captureStackTrace();
40 + internal._setOnCancel(this);
41 + } else {
42 + var promise = this._promise = new Promise(INTERNAL);
43 + promise._captureStackTrace();
44 + }
45 + this._stack = stack;
46 + this._generatorFunction = generatorFunction;
47 + this._receiver = receiver;
48 + this._generator = undefined;
49 + this._yieldHandlers = typeof yieldHandler === "function"
50 + ? [yieldHandler].concat(yieldHandlers)
51 + : yieldHandlers;
52 + this._yieldedPromise = null;
53 + this._cancellationPhase = false;
54 +}
55 +util.inherits(PromiseSpawn, Proxyable);
56 +
57 +PromiseSpawn.prototype._isResolved = function() {
58 + return this._promise === null;
59 +};
60 +
61 +PromiseSpawn.prototype._cleanup = function() {
62 + this._promise = this._generator = null;
63 + if (debug.cancellation() && this._finallyPromise !== null) {
64 + this._finallyPromise._fulfill();
65 + this._finallyPromise = null;
66 + }
67 +};
68 +
69 +PromiseSpawn.prototype._promiseCancelled = function() {
70 + if (this._isResolved()) return;
71 + var implementsReturn = typeof this._generator["return"] !== "undefined";
72 +
73 + var result;
74 + if (!implementsReturn) {
75 + var reason = new Promise.CancellationError(
76 + "generator .return() sentinel");
77 + Promise.coroutine.returnSentinel = reason;
78 + this._promise._attachExtraTrace(reason);
79 + this._promise._pushContext();
80 + result = tryCatch(this._generator["throw"]).call(this._generator,
81 + reason);
82 + this._promise._popContext();
83 + } else {
84 + this._promise._pushContext();
85 + result = tryCatch(this._generator["return"]).call(this._generator,
86 + undefined);
87 + this._promise._popContext();
88 + }
89 + this._cancellationPhase = true;
90 + this._yieldedPromise = null;
91 + this._continue(result);
92 +};
93 +
94 +PromiseSpawn.prototype._promiseFulfilled = function(value) {
95 + this._yieldedPromise = null;
96 + this._promise._pushContext();
97 + var result = tryCatch(this._generator.next).call(this._generator, value);
98 + this._promise._popContext();
99 + this._continue(result);
100 +};
101 +
102 +PromiseSpawn.prototype._promiseRejected = function(reason) {
103 + this._yieldedPromise = null;
104 + this._promise._attachExtraTrace(reason);
105 + this._promise._pushContext();
106 + var result = tryCatch(this._generator["throw"])
107 + .call(this._generator, reason);
108 + this._promise._popContext();
109 + this._continue(result);
110 +};
111 +
112 +PromiseSpawn.prototype._resultCancelled = function() {
113 + if (this._yieldedPromise instanceof Promise) {
114 + var promise = this._yieldedPromise;
115 + this._yieldedPromise = null;
116 + promise.cancel();
117 + }
118 +};
119 +
120 +PromiseSpawn.prototype.promise = function () {
121 + return this._promise;
122 +};
123 +
124 +PromiseSpawn.prototype._run = function () {
125 + this._generator = this._generatorFunction.call(this._receiver);
126 + this._receiver =
127 + this._generatorFunction = undefined;
128 + this._promiseFulfilled(undefined);
129 +};
130 +
131 +PromiseSpawn.prototype._continue = function (result) {
132 + var promise = this._promise;
133 + if (result === errorObj) {
134 + this._cleanup();
135 + if (this._cancellationPhase) {
136 + return promise.cancel();
137 + } else {
138 + return promise._rejectCallback(result.e, false);
139 + }
140 + }
141 +
142 + var value = result.value;
143 + if (result.done === true) {
144 + this._cleanup();
145 + if (this._cancellationPhase) {
146 + return promise.cancel();
147 + } else {
148 + return promise._resolveCallback(value);
149 + }
150 + } else {
151 + var maybePromise = tryConvertToPromise(value, this._promise);
152 + if (!(maybePromise instanceof Promise)) {
153 + maybePromise =
154 + promiseFromYieldHandler(maybePromise,
155 + this._yieldHandlers,
156 + this._promise);
157 + if (maybePromise === null) {
158 + this._promiseRejected(
159 + new TypeError(
160 + "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)) +
161 + "From coroutine:\u000a" +
162 + this._stack.split("\n").slice(1, -7).join("\n")
163 + )
164 + );
165 + return;
166 + }
167 + }
168 + maybePromise = maybePromise._target();
169 + var bitField = maybePromise._bitField;
170 + ;
171 + if (((bitField & 50397184) === 0)) {
172 + this._yieldedPromise = maybePromise;
173 + maybePromise._proxy(this, null);
174 + } else if (((bitField & 33554432) !== 0)) {
175 + Promise._async.invoke(
176 + this._promiseFulfilled, this, maybePromise._value()
177 + );
178 + } else if (((bitField & 16777216) !== 0)) {
179 + Promise._async.invoke(
180 + this._promiseRejected, this, maybePromise._reason()
181 + );
182 + } else {
183 + this._promiseCancelled();
184 + }
185 + }
186 +};
187 +
188 +Promise.coroutine = function (generatorFunction, options) {
189 + if (typeof generatorFunction !== "function") {
190 + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
191 + }
192 + var yieldHandler = Object(options).yieldHandler;
193 + var PromiseSpawn$ = PromiseSpawn;
194 + var stack = new Error().stack;
195 + return function () {
196 + var generator = generatorFunction.apply(this, arguments);
197 + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
198 + stack);
199 + var ret = spawn.promise();
200 + spawn._generator = generator;
201 + spawn._promiseFulfilled(undefined);
202 + return ret;
203 + };
204 +};
205 +
206 +Promise.coroutine.addYieldHandler = function(fn) {
207 + if (typeof fn !== "function") {
208 + throw new TypeError("expecting a function but got " + util.classString(fn));
209 + }
210 + yieldHandlers.push(fn);
211 +};
212 +
213 +Promise.spawn = function (generatorFunction) {
214 + debug.deprecated("Promise.spawn()", "Promise.coroutine()");
215 + if (typeof generatorFunction !== "function") {
216 + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
217 + }
218 + var spawn = new PromiseSpawn(generatorFunction, this);
219 + var ret = spawn.promise();
220 + spawn._run(Promise.spawn);
221 + return ret;
222 +};
223 +};
1 +"use strict";
2 +module.exports =
3 +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
4 + getDomain) {
5 +var util = require("./util");
6 +var canEvaluate = util.canEvaluate;
7 +var tryCatch = util.tryCatch;
8 +var errorObj = util.errorObj;
9 +var reject;
10 +
11 +if (!false) {
12 +if (canEvaluate) {
13 + var thenCallback = function(i) {
14 + return new Function("value", "holder", " \n\
15 + 'use strict'; \n\
16 + holder.pIndex = value; \n\
17 + holder.checkFulfillment(this); \n\
18 + ".replace(/Index/g, i));
19 + };
20 +
21 + var promiseSetter = function(i) {
22 + return new Function("promise", "holder", " \n\
23 + 'use strict'; \n\
24 + holder.pIndex = promise; \n\
25 + ".replace(/Index/g, i));
26 + };
27 +
28 + var generateHolderClass = function(total) {
29 + var props = new Array(total);
30 + for (var i = 0; i < props.length; ++i) {
31 + props[i] = "this.p" + (i+1);
32 + }
33 + var assignment = props.join(" = ") + " = null;";
34 + var cancellationCode= "var promise;\n" + props.map(function(prop) {
35 + return " \n\
36 + promise = " + prop + "; \n\
37 + if (promise instanceof Promise) { \n\
38 + promise.cancel(); \n\
39 + } \n\
40 + ";
41 + }).join("\n");
42 + var passedArguments = props.join(", ");
43 + var name = "Holder$" + total;
44 +
45 +
46 + var code = "return function(tryCatch, errorObj, Promise, async) { \n\
47 + 'use strict'; \n\
48 + function [TheName](fn) { \n\
49 + [TheProperties] \n\
50 + this.fn = fn; \n\
51 + this.asyncNeeded = true; \n\
52 + this.now = 0; \n\
53 + } \n\
54 + \n\
55 + [TheName].prototype._callFunction = function(promise) { \n\
56 + promise._pushContext(); \n\
57 + var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
58 + promise._popContext(); \n\
59 + if (ret === errorObj) { \n\
60 + promise._rejectCallback(ret.e, false); \n\
61 + } else { \n\
62 + promise._resolveCallback(ret); \n\
63 + } \n\
64 + }; \n\
65 + \n\
66 + [TheName].prototype.checkFulfillment = function(promise) { \n\
67 + var now = ++this.now; \n\
68 + if (now === [TheTotal]) { \n\
69 + if (this.asyncNeeded) { \n\
70 + async.invoke(this._callFunction, this, promise); \n\
71 + } else { \n\
72 + this._callFunction(promise); \n\
73 + } \n\
74 + \n\
75 + } \n\
76 + }; \n\
77 + \n\
78 + [TheName].prototype._resultCancelled = function() { \n\
79 + [CancellationCode] \n\
80 + }; \n\
81 + \n\
82 + return [TheName]; \n\
83 + }(tryCatch, errorObj, Promise, async); \n\
84 + ";
85 +
86 + code = code.replace(/\[TheName\]/g, name)
87 + .replace(/\[TheTotal\]/g, total)
88 + .replace(/\[ThePassedArguments\]/g, passedArguments)
89 + .replace(/\[TheProperties\]/g, assignment)
90 + .replace(/\[CancellationCode\]/g, cancellationCode);
91 +
92 + return new Function("tryCatch", "errorObj", "Promise", "async", code)
93 + (tryCatch, errorObj, Promise, async);
94 + };
95 +
96 + var holderClasses = [];
97 + var thenCallbacks = [];
98 + var promiseSetters = [];
99 +
100 + for (var i = 0; i < 8; ++i) {
101 + holderClasses.push(generateHolderClass(i + 1));
102 + thenCallbacks.push(thenCallback(i + 1));
103 + promiseSetters.push(promiseSetter(i + 1));
104 + }
105 +
106 + reject = function (reason) {
107 + this._reject(reason);
108 + };
109 +}}
110 +
111 +Promise.join = function () {
112 + var last = arguments.length - 1;
113 + var fn;
114 + if (last > 0 && typeof arguments[last] === "function") {
115 + fn = arguments[last];
116 + if (!false) {
117 + if (last <= 8 && canEvaluate) {
118 + var ret = new Promise(INTERNAL);
119 + ret._captureStackTrace();
120 + var HolderClass = holderClasses[last - 1];
121 + var holder = new HolderClass(fn);
122 + var callbacks = thenCallbacks;
123 +
124 + for (var i = 0; i < last; ++i) {
125 + var maybePromise = tryConvertToPromise(arguments[i], ret);
126 + if (maybePromise instanceof Promise) {
127 + maybePromise = maybePromise._target();
128 + var bitField = maybePromise._bitField;
129 + ;
130 + if (((bitField & 50397184) === 0)) {
131 + maybePromise._then(callbacks[i], reject,
132 + undefined, ret, holder);
133 + promiseSetters[i](maybePromise, holder);
134 + holder.asyncNeeded = false;
135 + } else if (((bitField & 33554432) !== 0)) {
136 + callbacks[i].call(ret,
137 + maybePromise._value(), holder);
138 + } else if (((bitField & 16777216) !== 0)) {
139 + ret._reject(maybePromise._reason());
140 + } else {
141 + ret._cancel();
142 + }
143 + } else {
144 + callbacks[i].call(ret, maybePromise, holder);
145 + }
146 + }
147 +
148 + if (!ret._isFateSealed()) {
149 + if (holder.asyncNeeded) {
150 + var domain = getDomain();
151 + if (domain !== null) {
152 + holder.fn = util.domainBind(domain, holder.fn);
153 + }
154 + }
155 + ret._setAsyncGuaranteed();
156 + ret._setOnCancel(holder);
157 + }
158 + return ret;
159 + }
160 + }
161 + }
162 + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
163 + if (fn) args.pop();
164 + var ret = new PromiseArray(args).promise();
165 + return fn !== undefined ? ret.spread(fn) : ret;
166 +};
167 +
168 +};
1 +"use strict";
2 +module.exports = function(Promise,
3 + PromiseArray,
4 + apiRejection,
5 + tryConvertToPromise,
6 + INTERNAL,
7 + debug) {
8 +var getDomain = Promise._getDomain;
9 +var util = require("./util");
10 +var tryCatch = util.tryCatch;
11 +var errorObj = util.errorObj;
12 +var async = Promise._async;
13 +
14 +function MappingPromiseArray(promises, fn, limit, _filter) {
15 + this.constructor$(promises);
16 + this._promise._captureStackTrace();
17 + var domain = getDomain();
18 + this._callback = domain === null ? fn : util.domainBind(domain, fn);
19 + this._preservedValues = _filter === INTERNAL
20 + ? new Array(this.length())
21 + : null;
22 + this._limit = limit;
23 + this._inFlight = 0;
24 + this._queue = [];
25 + async.invoke(this._asyncInit, this, undefined);
26 +}
27 +util.inherits(MappingPromiseArray, PromiseArray);
28 +
29 +MappingPromiseArray.prototype._asyncInit = function() {
30 + this._init$(undefined, -2);
31 +};
32 +
33 +MappingPromiseArray.prototype._init = function () {};
34 +
35 +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
36 + var values = this._values;
37 + var length = this.length();
38 + var preservedValues = this._preservedValues;
39 + var limit = this._limit;
40 +
41 + if (index < 0) {
42 + index = (index * -1) - 1;
43 + values[index] = value;
44 + if (limit >= 1) {
45 + this._inFlight--;
46 + this._drainQueue();
47 + if (this._isResolved()) return true;
48 + }
49 + } else {
50 + if (limit >= 1 && this._inFlight >= limit) {
51 + values[index] = value;
52 + this._queue.push(index);
53 + return false;
54 + }
55 + if (preservedValues !== null) preservedValues[index] = value;
56 +
57 + var promise = this._promise;
58 + var callback = this._callback;
59 + var receiver = promise._boundValue();
60 + promise._pushContext();
61 + var ret = tryCatch(callback).call(receiver, value, index, length);
62 + var promiseCreated = promise._popContext();
63 + debug.checkForgottenReturns(
64 + ret,
65 + promiseCreated,
66 + preservedValues !== null ? "Promise.filter" : "Promise.map",
67 + promise
68 + );
69 + if (ret === errorObj) {
70 + this._reject(ret.e);
71 + return true;
72 + }
73 +
74 + var maybePromise = tryConvertToPromise(ret, this._promise);
75 + if (maybePromise instanceof Promise) {
76 + maybePromise = maybePromise._target();
77 + var bitField = maybePromise._bitField;
78 + ;
79 + if (((bitField & 50397184) === 0)) {
80 + if (limit >= 1) this._inFlight++;
81 + values[index] = maybePromise;
82 + maybePromise._proxy(this, (index + 1) * -1);
83 + return false;
84 + } else if (((bitField & 33554432) !== 0)) {
85 + ret = maybePromise._value();
86 + } else if (((bitField & 16777216) !== 0)) {
87 + this._reject(maybePromise._reason());
88 + return true;
89 + } else {
90 + this._cancel();
91 + return true;
92 + }
93 + }
94 + values[index] = ret;
95 + }
96 + var totalResolved = ++this._totalResolved;
97 + if (totalResolved >= length) {
98 + if (preservedValues !== null) {
99 + this._filter(values, preservedValues);
100 + } else {
101 + this._resolve(values);
102 + }
103 + return true;
104 + }
105 + return false;
106 +};
107 +
108 +MappingPromiseArray.prototype._drainQueue = function () {
109 + var queue = this._queue;
110 + var limit = this._limit;
111 + var values = this._values;
112 + while (queue.length > 0 && this._inFlight < limit) {
113 + if (this._isResolved()) return;
114 + var index = queue.pop();
115 + this._promiseFulfilled(values[index], index);
116 + }
117 +};
118 +
119 +MappingPromiseArray.prototype._filter = function (booleans, values) {
120 + var len = values.length;
121 + var ret = new Array(len);
122 + var j = 0;
123 + for (var i = 0; i < len; ++i) {
124 + if (booleans[i]) ret[j++] = values[i];
125 + }
126 + ret.length = j;
127 + this._resolve(ret);
128 +};
129 +
130 +MappingPromiseArray.prototype.preservedValues = function () {
131 + return this._preservedValues;
132 +};
133 +
134 +function map(promises, fn, options, _filter) {
135 + if (typeof fn !== "function") {
136 + return apiRejection("expecting a function but got " + util.classString(fn));
137 + }
138 +
139 + var limit = 0;
140 + if (options !== undefined) {
141 + if (typeof options === "object" && options !== null) {
142 + if (typeof options.concurrency !== "number") {
143 + return Promise.reject(
144 + new TypeError("'concurrency' must be a number but it is " +
145 + util.classString(options.concurrency)));
146 + }
147 + limit = options.concurrency;
148 + } else {
149 + return Promise.reject(new TypeError(
150 + "options argument must be an object but it is " +
151 + util.classString(options)));
152 + }
153 + }
154 + limit = typeof limit === "number" &&
155 + isFinite(limit) && limit >= 1 ? limit : 0;
156 + return new MappingPromiseArray(promises, fn, limit, _filter).promise();
157 +}
158 +
159 +Promise.prototype.map = function (fn, options) {
160 + return map(this, fn, options, null);
161 +};
162 +
163 +Promise.map = function (promises, fn, options, _filter) {
164 + return map(promises, fn, options, _filter);
165 +};
166 +
167 +
168 +};
1 +"use strict";
2 +module.exports =
3 +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
4 +var util = require("./util");
5 +var tryCatch = util.tryCatch;
6 +
7 +Promise.method = function (fn) {
8 + if (typeof fn !== "function") {
9 + throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
10 + }
11 + return function () {
12 + var ret = new Promise(INTERNAL);
13 + ret._captureStackTrace();
14 + ret._pushContext();
15 + var value = tryCatch(fn).apply(this, arguments);
16 + var promiseCreated = ret._popContext();
17 + debug.checkForgottenReturns(
18 + value, promiseCreated, "Promise.method", ret);
19 + ret._resolveFromSyncValue(value);
20 + return ret;
21 + };
22 +};
23 +
24 +Promise.attempt = Promise["try"] = function (fn) {
25 + if (typeof fn !== "function") {
26 + return apiRejection("expecting a function but got " + util.classString(fn));
27 + }
28 + var ret = new Promise(INTERNAL);
29 + ret._captureStackTrace();
30 + ret._pushContext();
31 + var value;
32 + if (arguments.length > 1) {
33 + debug.deprecated("calling Promise.try with more than 1 argument");
34 + var arg = arguments[1];
35 + var ctx = arguments[2];
36 + value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
37 + : tryCatch(fn).call(ctx, arg);
38 + } else {
39 + value = tryCatch(fn)();
40 + }
41 + var promiseCreated = ret._popContext();
42 + debug.checkForgottenReturns(
43 + value, promiseCreated, "Promise.try", ret);
44 + ret._resolveFromSyncValue(value);
45 + return ret;
46 +};
47 +
48 +Promise.prototype._resolveFromSyncValue = function (value) {
49 + if (value === util.errorObj) {
50 + this._rejectCallback(value.e, false);
51 + } else {
52 + this._resolveCallback(value, true);
53 + }
54 +};
55 +};
1 +"use strict";
2 +var util = require("./util");
3 +var maybeWrapAsError = util.maybeWrapAsError;
4 +var errors = require("./errors");
5 +var OperationalError = errors.OperationalError;
6 +var es5 = require("./es5");
7 +
8 +function isUntypedError(obj) {
9 + return obj instanceof Error &&
10 + es5.getPrototypeOf(obj) === Error.prototype;
11 +}
12 +
13 +var rErrorKey = /^(?:name|message|stack|cause)$/;
14 +function wrapAsOperationalError(obj) {
15 + var ret;
16 + if (isUntypedError(obj)) {
17 + ret = new OperationalError(obj);
18 + ret.name = obj.name;
19 + ret.message = obj.message;
20 + ret.stack = obj.stack;
21 + var keys = es5.keys(obj);
22 + for (var i = 0; i < keys.length; ++i) {
23 + var key = keys[i];
24 + if (!rErrorKey.test(key)) {
25 + ret[key] = obj[key];
26 + }
27 + }
28 + return ret;
29 + }
30 + util.markAsOriginatingFromRejection(obj);
31 + return obj;
32 +}
33 +
34 +function nodebackForPromise(promise, multiArgs) {
35 + return function(err, value) {
36 + if (promise === null) return;
37 + if (err) {
38 + var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
39 + promise._attachExtraTrace(wrapped);
40 + promise._reject(wrapped);
41 + } else if (!multiArgs) {
42 + promise._fulfill(value);
43 + } else {
44 + 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];};
45 + promise._fulfill(args);
46 + }
47 + promise = null;
48 + };
49 +}
50 +
51 +module.exports = nodebackForPromise;
1 +"use strict";
2 +module.exports = function(Promise) {
3 +var util = require("./util");
4 +var async = Promise._async;
5 +var tryCatch = util.tryCatch;
6 +var errorObj = util.errorObj;
7 +
8 +function spreadAdapter(val, nodeback) {
9 + var promise = this;
10 + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
11 + var ret =
12 + tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
13 + if (ret === errorObj) {
14 + async.throwLater(ret.e);
15 + }
16 +}
17 +
18 +function successAdapter(val, nodeback) {
19 + var promise = this;
20 + var receiver = promise._boundValue();
21 + var ret = val === undefined
22 + ? tryCatch(nodeback).call(receiver, null)
23 + : tryCatch(nodeback).call(receiver, null, val);
24 + if (ret === errorObj) {
25 + async.throwLater(ret.e);
26 + }
27 +}
28 +function errorAdapter(reason, nodeback) {
29 + var promise = this;
30 + if (!reason) {
31 + var newReason = new Error(reason + "");
32 + newReason.cause = reason;
33 + reason = newReason;
34 + }
35 + var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
36 + if (ret === errorObj) {
37 + async.throwLater(ret.e);
38 + }
39 +}
40 +
41 +Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
42 + options) {
43 + if (typeof nodeback == "function") {
44 + var adapter = successAdapter;
45 + if (options !== undefined && Object(options).spread) {
46 + adapter = spreadAdapter;
47 + }
48 + this._then(
49 + adapter,
50 + errorAdapter,
51 + undefined,
52 + this,
53 + nodeback
54 + );
55 + }
56 + return this;
57 +};
58 +};
1 +"use strict";
2 +module.exports = function() {
3 +var makeSelfResolutionError = function () {
4 + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
5 +};
6 +var reflectHandler = function() {
7 + return new Promise.PromiseInspection(this._target());
8 +};
9 +var apiRejection = function(msg) {
10 + return Promise.reject(new TypeError(msg));
11 +};
12 +function Proxyable() {}
13 +var UNDEFINED_BINDING = {};
14 +var util = require("./util");
15 +
16 +var getDomain;
17 +if (util.isNode) {
18 + getDomain = function() {
19 + var ret = process.domain;
20 + if (ret === undefined) ret = null;
21 + return ret;
22 + };
23 +} else {
24 + getDomain = function() {
25 + return null;
26 + };
27 +}
28 +util.notEnumerableProp(Promise, "_getDomain", getDomain);
29 +
30 +var es5 = require("./es5");
31 +var Async = require("./async");
32 +var async = new Async();
33 +es5.defineProperty(Promise, "_async", {value: async});
34 +var errors = require("./errors");
35 +var TypeError = Promise.TypeError = errors.TypeError;
36 +Promise.RangeError = errors.RangeError;
37 +var CancellationError = Promise.CancellationError = errors.CancellationError;
38 +Promise.TimeoutError = errors.TimeoutError;
39 +Promise.OperationalError = errors.OperationalError;
40 +Promise.RejectionError = errors.OperationalError;
41 +Promise.AggregateError = errors.AggregateError;
42 +var INTERNAL = function(){};
43 +var APPLY = {};
44 +var NEXT_FILTER = {};
45 +var tryConvertToPromise = require("./thenables")(Promise, INTERNAL);
46 +var PromiseArray =
47 + require("./promise_array")(Promise, INTERNAL,
48 + tryConvertToPromise, apiRejection, Proxyable);
49 +var Context = require("./context")(Promise);
50 + /*jshint unused:false*/
51 +var createContext = Context.create;
52 +var debug = require("./debuggability")(Promise, Context);
53 +var CapturedTrace = debug.CapturedTrace;
54 +var PassThroughHandlerContext =
55 + require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
56 +var catchFilter = require("./catch_filter")(NEXT_FILTER);
57 +var nodebackForPromise = require("./nodeback");
58 +var errorObj = util.errorObj;
59 +var tryCatch = util.tryCatch;
60 +function check(self, executor) {
61 + if (self == null || self.constructor !== Promise) {
62 + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
63 + }
64 + if (typeof executor !== "function") {
65 + throw new TypeError("expecting a function but got " + util.classString(executor));
66 + }
67 +
68 +}
69 +
70 +function Promise(executor) {
71 + if (executor !== INTERNAL) {
72 + check(this, executor);
73 + }
74 + this._bitField = 0;
75 + this._fulfillmentHandler0 = undefined;
76 + this._rejectionHandler0 = undefined;
77 + this._promise0 = undefined;
78 + this._receiver0 = undefined;
79 + this._resolveFromExecutor(executor);
80 + this._promiseCreated();
81 + this._fireEvent("promiseCreated", this);
82 +}
83 +
84 +Promise.prototype.toString = function () {
85 + return "[object Promise]";
86 +};
87 +
88 +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
89 + var len = arguments.length;
90 + if (len > 1) {
91 + var catchInstances = new Array(len - 1),
92 + j = 0, i;
93 + for (i = 0; i < len - 1; ++i) {
94 + var item = arguments[i];
95 + if (util.isObject(item)) {
96 + catchInstances[j++] = item;
97 + } else {
98 + return apiRejection("Catch statement predicate: " +
99 + "expecting an object but got " + util.classString(item));
100 + }
101 + }
102 + catchInstances.length = j;
103 + fn = arguments[i];
104 + return this.then(undefined, catchFilter(catchInstances, fn, this));
105 + }
106 + return this.then(undefined, fn);
107 +};
108 +
109 +Promise.prototype.reflect = function () {
110 + return this._then(reflectHandler,
111 + reflectHandler, undefined, this, undefined);
112 +};
113 +
114 +Promise.prototype.then = function (didFulfill, didReject) {
115 + if (debug.warnings() && arguments.length > 0 &&
116 + typeof didFulfill !== "function" &&
117 + typeof didReject !== "function") {
118 + var msg = ".then() only accepts functions but was passed: " +
119 + util.classString(didFulfill);
120 + if (arguments.length > 1) {
121 + msg += ", " + util.classString(didReject);
122 + }
123 + this._warn(msg);
124 + }
125 + return this._then(didFulfill, didReject, undefined, undefined, undefined);
126 +};
127 +
128 +Promise.prototype.done = function (didFulfill, didReject) {
129 + var promise =
130 + this._then(didFulfill, didReject, undefined, undefined, undefined);
131 + promise._setIsFinal();
132 +};
133 +
134 +Promise.prototype.spread = function (fn) {
135 + if (typeof fn !== "function") {
136 + return apiRejection("expecting a function but got " + util.classString(fn));
137 + }
138 + return this.all()._then(fn, undefined, undefined, APPLY, undefined);
139 +};
140 +
141 +Promise.prototype.toJSON = function () {
142 + var ret = {
143 + isFulfilled: false,
144 + isRejected: false,
145 + fulfillmentValue: undefined,
146 + rejectionReason: undefined
147 + };
148 + if (this.isFulfilled()) {
149 + ret.fulfillmentValue = this.value();
150 + ret.isFulfilled = true;
151 + } else if (this.isRejected()) {
152 + ret.rejectionReason = this.reason();
153 + ret.isRejected = true;
154 + }
155 + return ret;
156 +};
157 +
158 +Promise.prototype.all = function () {
159 + if (arguments.length > 0) {
160 + this._warn(".all() was passed arguments but it does not take any");
161 + }
162 + return new PromiseArray(this).promise();
163 +};
164 +
165 +Promise.prototype.error = function (fn) {
166 + return this.caught(util.originatesFromRejection, fn);
167 +};
168 +
169 +Promise.getNewLibraryCopy = module.exports;
170 +
171 +Promise.is = function (val) {
172 + return val instanceof Promise;
173 +};
174 +
175 +Promise.fromNode = Promise.fromCallback = function(fn) {
176 + var ret = new Promise(INTERNAL);
177 + ret._captureStackTrace();
178 + var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
179 + : false;
180 + var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
181 + if (result === errorObj) {
182 + ret._rejectCallback(result.e, true);
183 + }
184 + if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
185 + return ret;
186 +};
187 +
188 +Promise.all = function (promises) {
189 + return new PromiseArray(promises).promise();
190 +};
191 +
192 +Promise.cast = function (obj) {
193 + var ret = tryConvertToPromise(obj);
194 + if (!(ret instanceof Promise)) {
195 + ret = new Promise(INTERNAL);
196 + ret._captureStackTrace();
197 + ret._setFulfilled();
198 + ret._rejectionHandler0 = obj;
199 + }
200 + return ret;
201 +};
202 +
203 +Promise.resolve = Promise.fulfilled = Promise.cast;
204 +
205 +Promise.reject = Promise.rejected = function (reason) {
206 + var ret = new Promise(INTERNAL);
207 + ret._captureStackTrace();
208 + ret._rejectCallback(reason, true);
209 + return ret;
210 +};
211 +
212 +Promise.setScheduler = function(fn) {
213 + if (typeof fn !== "function") {
214 + throw new TypeError("expecting a function but got " + util.classString(fn));
215 + }
216 + return async.setScheduler(fn);
217 +};
218 +
219 +Promise.prototype._then = function (
220 + didFulfill,
221 + didReject,
222 + _, receiver,
223 + internalData
224 +) {
225 + var haveInternalData = internalData !== undefined;
226 + var promise = haveInternalData ? internalData : new Promise(INTERNAL);
227 + var target = this._target();
228 + var bitField = target._bitField;
229 +
230 + if (!haveInternalData) {
231 + promise._propagateFrom(this, 3);
232 + promise._captureStackTrace();
233 + if (receiver === undefined &&
234 + ((this._bitField & 2097152) !== 0)) {
235 + if (!((bitField & 50397184) === 0)) {
236 + receiver = this._boundValue();
237 + } else {
238 + receiver = target === this ? undefined : this._boundTo;
239 + }
240 + }
241 + this._fireEvent("promiseChained", this, promise);
242 + }
243 +
244 + var domain = getDomain();
245 + if (!((bitField & 50397184) === 0)) {
246 + var handler, value, settler = target._settlePromiseCtx;
247 + if (((bitField & 33554432) !== 0)) {
248 + value = target._rejectionHandler0;
249 + handler = didFulfill;
250 + } else if (((bitField & 16777216) !== 0)) {
251 + value = target._fulfillmentHandler0;
252 + handler = didReject;
253 + target._unsetRejectionIsUnhandled();
254 + } else {
255 + settler = target._settlePromiseLateCancellationObserver;
256 + value = new CancellationError("late cancellation observer");
257 + target._attachExtraTrace(value);
258 + handler = didReject;
259 + }
260 +
261 + async.invoke(settler, target, {
262 + handler: domain === null ? handler
263 + : (typeof handler === "function" &&
264 + util.domainBind(domain, handler)),
265 + promise: promise,
266 + receiver: receiver,
267 + value: value
268 + });
269 + } else {
270 + target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
271 + }
272 +
273 + return promise;
274 +};
275 +
276 +Promise.prototype._length = function () {
277 + return this._bitField & 65535;
278 +};
279 +
280 +Promise.prototype._isFateSealed = function () {
281 + return (this._bitField & 117506048) !== 0;
282 +};
283 +
284 +Promise.prototype._isFollowing = function () {
285 + return (this._bitField & 67108864) === 67108864;
286 +};
287 +
288 +Promise.prototype._setLength = function (len) {
289 + this._bitField = (this._bitField & -65536) |
290 + (len & 65535);
291 +};
292 +
293 +Promise.prototype._setFulfilled = function () {
294 + this._bitField = this._bitField | 33554432;
295 + this._fireEvent("promiseFulfilled", this);
296 +};
297 +
298 +Promise.prototype._setRejected = function () {
299 + this._bitField = this._bitField | 16777216;
300 + this._fireEvent("promiseRejected", this);
301 +};
302 +
303 +Promise.prototype._setFollowing = function () {
304 + this._bitField = this._bitField | 67108864;
305 + this._fireEvent("promiseResolved", this);
306 +};
307 +
308 +Promise.prototype._setIsFinal = function () {
309 + this._bitField = this._bitField | 4194304;
310 +};
311 +
312 +Promise.prototype._isFinal = function () {
313 + return (this._bitField & 4194304) > 0;
314 +};
315 +
316 +Promise.prototype._unsetCancelled = function() {
317 + this._bitField = this._bitField & (~65536);
318 +};
319 +
320 +Promise.prototype._setCancelled = function() {
321 + this._bitField = this._bitField | 65536;
322 + this._fireEvent("promiseCancelled", this);
323 +};
324 +
325 +Promise.prototype._setWillBeCancelled = function() {
326 + this._bitField = this._bitField | 8388608;
327 +};
328 +
329 +Promise.prototype._setAsyncGuaranteed = function() {
330 + if (async.hasCustomScheduler()) return;
331 + this._bitField = this._bitField | 134217728;
332 +};
333 +
334 +Promise.prototype._receiverAt = function (index) {
335 + var ret = index === 0 ? this._receiver0 : this[
336 + index * 4 - 4 + 3];
337 + if (ret === UNDEFINED_BINDING) {
338 + return undefined;
339 + } else if (ret === undefined && this._isBound()) {
340 + return this._boundValue();
341 + }
342 + return ret;
343 +};
344 +
345 +Promise.prototype._promiseAt = function (index) {
346 + return this[
347 + index * 4 - 4 + 2];
348 +};
349 +
350 +Promise.prototype._fulfillmentHandlerAt = function (index) {
351 + return this[
352 + index * 4 - 4 + 0];
353 +};
354 +
355 +Promise.prototype._rejectionHandlerAt = function (index) {
356 + return this[
357 + index * 4 - 4 + 1];
358 +};
359 +
360 +Promise.prototype._boundValue = function() {};
361 +
362 +Promise.prototype._migrateCallback0 = function (follower) {
363 + var bitField = follower._bitField;
364 + var fulfill = follower._fulfillmentHandler0;
365 + var reject = follower._rejectionHandler0;
366 + var promise = follower._promise0;
367 + var receiver = follower._receiverAt(0);
368 + if (receiver === undefined) receiver = UNDEFINED_BINDING;
369 + this._addCallbacks(fulfill, reject, promise, receiver, null);
370 +};
371 +
372 +Promise.prototype._migrateCallbackAt = function (follower, index) {
373 + var fulfill = follower._fulfillmentHandlerAt(index);
374 + var reject = follower._rejectionHandlerAt(index);
375 + var promise = follower._promiseAt(index);
376 + var receiver = follower._receiverAt(index);
377 + if (receiver === undefined) receiver = UNDEFINED_BINDING;
378 + this._addCallbacks(fulfill, reject, promise, receiver, null);
379 +};
380 +
381 +Promise.prototype._addCallbacks = function (
382 + fulfill,
383 + reject,
384 + promise,
385 + receiver,
386 + domain
387 +) {
388 + var index = this._length();
389 +
390 + if (index >= 65535 - 4) {
391 + index = 0;
392 + this._setLength(0);
393 + }
394 +
395 + if (index === 0) {
396 + this._promise0 = promise;
397 + this._receiver0 = receiver;
398 + if (typeof fulfill === "function") {
399 + this._fulfillmentHandler0 =
400 + domain === null ? fulfill : util.domainBind(domain, fulfill);
401 + }
402 + if (typeof reject === "function") {
403 + this._rejectionHandler0 =
404 + domain === null ? reject : util.domainBind(domain, reject);
405 + }
406 + } else {
407 + var base = index * 4 - 4;
408 + this[base + 2] = promise;
409 + this[base + 3] = receiver;
410 + if (typeof fulfill === "function") {
411 + this[base + 0] =
412 + domain === null ? fulfill : util.domainBind(domain, fulfill);
413 + }
414 + if (typeof reject === "function") {
415 + this[base + 1] =
416 + domain === null ? reject : util.domainBind(domain, reject);
417 + }
418 + }
419 + this._setLength(index + 1);
420 + return index;
421 +};
422 +
423 +Promise.prototype._proxy = function (proxyable, arg) {
424 + this._addCallbacks(undefined, undefined, arg, proxyable, null);
425 +};
426 +
427 +Promise.prototype._resolveCallback = function(value, shouldBind) {
428 + if (((this._bitField & 117506048) !== 0)) return;
429 + if (value === this)
430 + return this._rejectCallback(makeSelfResolutionError(), false);
431 + var maybePromise = tryConvertToPromise(value, this);
432 + if (!(maybePromise instanceof Promise)) return this._fulfill(value);
433 +
434 + if (shouldBind) this._propagateFrom(maybePromise, 2);
435 +
436 + var promise = maybePromise._target();
437 +
438 + if (promise === this) {
439 + this._reject(makeSelfResolutionError());
440 + return;
441 + }
442 +
443 + var bitField = promise._bitField;
444 + if (((bitField & 50397184) === 0)) {
445 + var len = this._length();
446 + if (len > 0) promise._migrateCallback0(this);
447 + for (var i = 1; i < len; ++i) {
448 + promise._migrateCallbackAt(this, i);
449 + }
450 + this._setFollowing();
451 + this._setLength(0);
452 + this._setFollowee(promise);
453 + } else if (((bitField & 33554432) !== 0)) {
454 + this._fulfill(promise._value());
455 + } else if (((bitField & 16777216) !== 0)) {
456 + this._reject(promise._reason());
457 + } else {
458 + var reason = new CancellationError("late cancellation observer");
459 + promise._attachExtraTrace(reason);
460 + this._reject(reason);
461 + }
462 +};
463 +
464 +Promise.prototype._rejectCallback =
465 +function(reason, synchronous, ignoreNonErrorWarnings) {
466 + var trace = util.ensureErrorObject(reason);
467 + var hasStack = trace === reason;
468 + if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
469 + var message = "a promise was rejected with a non-error: " +
470 + util.classString(reason);
471 + this._warn(message, true);
472 + }
473 + this._attachExtraTrace(trace, synchronous ? hasStack : false);
474 + this._reject(reason);
475 +};
476 +
477 +Promise.prototype._resolveFromExecutor = function (executor) {
478 + if (executor === INTERNAL) return;
479 + var promise = this;
480 + this._captureStackTrace();
481 + this._pushContext();
482 + var synchronous = true;
483 + var r = this._execute(executor, function(value) {
484 + promise._resolveCallback(value);
485 + }, function (reason) {
486 + promise._rejectCallback(reason, synchronous);
487 + });
488 + synchronous = false;
489 + this._popContext();
490 +
491 + if (r !== undefined) {
492 + promise._rejectCallback(r, true);
493 + }
494 +};
495 +
496 +Promise.prototype._settlePromiseFromHandler = function (
497 + handler, receiver, value, promise
498 +) {
499 + var bitField = promise._bitField;
500 + if (((bitField & 65536) !== 0)) return;
501 + promise._pushContext();
502 + var x;
503 + if (receiver === APPLY) {
504 + if (!value || typeof value.length !== "number") {
505 + x = errorObj;
506 + x.e = new TypeError("cannot .spread() a non-array: " +
507 + util.classString(value));
508 + } else {
509 + x = tryCatch(handler).apply(this._boundValue(), value);
510 + }
511 + } else {
512 + x = tryCatch(handler).call(receiver, value);
513 + }
514 + var promiseCreated = promise._popContext();
515 + bitField = promise._bitField;
516 + if (((bitField & 65536) !== 0)) return;
517 +
518 + if (x === NEXT_FILTER) {
519 + promise._reject(value);
520 + } else if (x === errorObj) {
521 + promise._rejectCallback(x.e, false);
522 + } else {
523 + debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
524 + promise._resolveCallback(x);
525 + }
526 +};
527 +
528 +Promise.prototype._target = function() {
529 + var ret = this;
530 + while (ret._isFollowing()) ret = ret._followee();
531 + return ret;
532 +};
533 +
534 +Promise.prototype._followee = function() {
535 + return this._rejectionHandler0;
536 +};
537 +
538 +Promise.prototype._setFollowee = function(promise) {
539 + this._rejectionHandler0 = promise;
540 +};
541 +
542 +Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
543 + var isPromise = promise instanceof Promise;
544 + var bitField = this._bitField;
545 + var asyncGuaranteed = ((bitField & 134217728) !== 0);
546 + if (((bitField & 65536) !== 0)) {
547 + if (isPromise) promise._invokeInternalOnCancel();
548 +
549 + if (receiver instanceof PassThroughHandlerContext &&
550 + receiver.isFinallyHandler()) {
551 + receiver.cancelPromise = promise;
552 + if (tryCatch(handler).call(receiver, value) === errorObj) {
553 + promise._reject(errorObj.e);
554 + }
555 + } else if (handler === reflectHandler) {
556 + promise._fulfill(reflectHandler.call(receiver));
557 + } else if (receiver instanceof Proxyable) {
558 + receiver._promiseCancelled(promise);
559 + } else if (isPromise || promise instanceof PromiseArray) {
560 + promise._cancel();
561 + } else {
562 + receiver.cancel();
563 + }
564 + } else if (typeof handler === "function") {
565 + if (!isPromise) {
566 + handler.call(receiver, value, promise);
567 + } else {
568 + if (asyncGuaranteed) promise._setAsyncGuaranteed();
569 + this._settlePromiseFromHandler(handler, receiver, value, promise);
570 + }
571 + } else if (receiver instanceof Proxyable) {
572 + if (!receiver._isResolved()) {
573 + if (((bitField & 33554432) !== 0)) {
574 + receiver._promiseFulfilled(value, promise);
575 + } else {
576 + receiver._promiseRejected(value, promise);
577 + }
578 + }
579 + } else if (isPromise) {
580 + if (asyncGuaranteed) promise._setAsyncGuaranteed();
581 + if (((bitField & 33554432) !== 0)) {
582 + promise._fulfill(value);
583 + } else {
584 + promise._reject(value);
585 + }
586 + }
587 +};
588 +
589 +Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
590 + var handler = ctx.handler;
591 + var promise = ctx.promise;
592 + var receiver = ctx.receiver;
593 + var value = ctx.value;
594 + if (typeof handler === "function") {
595 + if (!(promise instanceof Promise)) {
596 + handler.call(receiver, value, promise);
597 + } else {
598 + this._settlePromiseFromHandler(handler, receiver, value, promise);
599 + }
600 + } else if (promise instanceof Promise) {
601 + promise._reject(value);
602 + }
603 +};
604 +
605 +Promise.prototype._settlePromiseCtx = function(ctx) {
606 + this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
607 +};
608 +
609 +Promise.prototype._settlePromise0 = function(handler, value, bitField) {
610 + var promise = this._promise0;
611 + var receiver = this._receiverAt(0);
612 + this._promise0 = undefined;
613 + this._receiver0 = undefined;
614 + this._settlePromise(promise, handler, receiver, value);
615 +};
616 +
617 +Promise.prototype._clearCallbackDataAtIndex = function(index) {
618 + var base = index * 4 - 4;
619 + this[base + 2] =
620 + this[base + 3] =
621 + this[base + 0] =
622 + this[base + 1] = undefined;
623 +};
624 +
625 +Promise.prototype._fulfill = function (value) {
626 + var bitField = this._bitField;
627 + if (((bitField & 117506048) >>> 16)) return;
628 + if (value === this) {
629 + var err = makeSelfResolutionError();
630 + this._attachExtraTrace(err);
631 + return this._reject(err);
632 + }
633 + this._setFulfilled();
634 + this._rejectionHandler0 = value;
635 +
636 + if ((bitField & 65535) > 0) {
637 + if (((bitField & 134217728) !== 0)) {
638 + this._settlePromises();
639 + } else {
640 + async.settlePromises(this);
641 + }
642 + this._dereferenceTrace();
643 + }
644 +};
645 +
646 +Promise.prototype._reject = function (reason) {
647 + var bitField = this._bitField;
648 + if (((bitField & 117506048) >>> 16)) return;
649 + this._setRejected();
650 + this._fulfillmentHandler0 = reason;
651 +
652 + if (this._isFinal()) {
653 + return async.fatalError(reason, util.isNode);
654 + }
655 +
656 + if ((bitField & 65535) > 0) {
657 + async.settlePromises(this);
658 + } else {
659 + this._ensurePossibleRejectionHandled();
660 + }
661 +};
662 +
663 +Promise.prototype._fulfillPromises = function (len, value) {
664 + for (var i = 1; i < len; i++) {
665 + var handler = this._fulfillmentHandlerAt(i);
666 + var promise = this._promiseAt(i);
667 + var receiver = this._receiverAt(i);
668 + this._clearCallbackDataAtIndex(i);
669 + this._settlePromise(promise, handler, receiver, value);
670 + }
671 +};
672 +
673 +Promise.prototype._rejectPromises = function (len, reason) {
674 + for (var i = 1; i < len; i++) {
675 + var handler = this._rejectionHandlerAt(i);
676 + var promise = this._promiseAt(i);
677 + var receiver = this._receiverAt(i);
678 + this._clearCallbackDataAtIndex(i);
679 + this._settlePromise(promise, handler, receiver, reason);
680 + }
681 +};
682 +
683 +Promise.prototype._settlePromises = function () {
684 + var bitField = this._bitField;
685 + var len = (bitField & 65535);
686 +
687 + if (len > 0) {
688 + if (((bitField & 16842752) !== 0)) {
689 + var reason = this._fulfillmentHandler0;
690 + this._settlePromise0(this._rejectionHandler0, reason, bitField);
691 + this._rejectPromises(len, reason);
692 + } else {
693 + var value = this._rejectionHandler0;
694 + this._settlePromise0(this._fulfillmentHandler0, value, bitField);
695 + this._fulfillPromises(len, value);
696 + }
697 + this._setLength(0);
698 + }
699 + this._clearCancellationData();
700 +};
701 +
702 +Promise.prototype._settledValue = function() {
703 + var bitField = this._bitField;
704 + if (((bitField & 33554432) !== 0)) {
705 + return this._rejectionHandler0;
706 + } else if (((bitField & 16777216) !== 0)) {
707 + return this._fulfillmentHandler0;
708 + }
709 +};
710 +
711 +function deferResolve(v) {this.promise._resolveCallback(v);}
712 +function deferReject(v) {this.promise._rejectCallback(v, false);}
713 +
714 +Promise.defer = Promise.pending = function() {
715 + debug.deprecated("Promise.defer", "new Promise");
716 + var promise = new Promise(INTERNAL);
717 + return {
718 + promise: promise,
719 + resolve: deferResolve,
720 + reject: deferReject
721 + };
722 +};
723 +
724 +util.notEnumerableProp(Promise,
725 + "_makeSelfResolutionError",
726 + makeSelfResolutionError);
727 +
728 +require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
729 + debug);
730 +require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
731 +require("./cancel")(Promise, PromiseArray, apiRejection, debug);
732 +require("./direct_resolve")(Promise);
733 +require("./synchronous_inspection")(Promise);
734 +require("./join")(
735 + Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
736 +Promise.Promise = Promise;
737 +Promise.version = "3.5.3";
738 +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
739 +require('./call_get.js')(Promise);
740 +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
741 +require('./timers.js')(Promise, INTERNAL, debug);
742 +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
743 +require('./nodeify.js')(Promise);
744 +require('./promisify.js')(Promise, INTERNAL);
745 +require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
746 +require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
747 +require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
748 +require('./settle.js')(Promise, PromiseArray, debug);
749 +require('./some.js')(Promise, PromiseArray, apiRejection);
750 +require('./filter.js')(Promise, INTERNAL);
751 +require('./each.js')(Promise, INTERNAL);
752 +require('./any.js')(Promise);
753 +
754 + util.toFastProperties(Promise);
755 + util.toFastProperties(Promise.prototype);
756 + function fillTypes(value) {
757 + var p = new Promise(INTERNAL);
758 + p._fulfillmentHandler0 = value;
759 + p._rejectionHandler0 = value;
760 + p._promise0 = value;
761 + p._receiver0 = value;
762 + }
763 + // Complete slack tracking, opt out of field-type tracking and
764 + // stabilize map
765 + fillTypes({a: 1});
766 + fillTypes({b: 2});
767 + fillTypes({c: 3});
768 + fillTypes(1);
769 + fillTypes(function(){});
770 + fillTypes(undefined);
771 + fillTypes(false);
772 + fillTypes(new Promise(INTERNAL));
773 + debug.setBounds(Async.firstLineError, util.lastLineError);
774 + return Promise;
775 +
776 +};
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL, tryConvertToPromise,
3 + apiRejection, Proxyable) {
4 +var util = require("./util");
5 +var isArray = util.isArray;
6 +
7 +function toResolutionValue(val) {
8 + switch(val) {
9 + case -2: return [];
10 + case -3: return {};
11 + case -6: return new Map();
12 + }
13 +}
14 +
15 +function PromiseArray(values) {
16 + var promise = this._promise = new Promise(INTERNAL);
17 + if (values instanceof Promise) {
18 + promise._propagateFrom(values, 3);
19 + }
20 + promise._setOnCancel(this);
21 + this._values = values;
22 + this._length = 0;
23 + this._totalResolved = 0;
24 + this._init(undefined, -2);
25 +}
26 +util.inherits(PromiseArray, Proxyable);
27 +
28 +PromiseArray.prototype.length = function () {
29 + return this._length;
30 +};
31 +
32 +PromiseArray.prototype.promise = function () {
33 + return this._promise;
34 +};
35 +
36 +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
37 + var values = tryConvertToPromise(this._values, this._promise);
38 + if (values instanceof Promise) {
39 + values = values._target();
40 + var bitField = values._bitField;
41 + ;
42 + this._values = values;
43 +
44 + if (((bitField & 50397184) === 0)) {
45 + this._promise._setAsyncGuaranteed();
46 + return values._then(
47 + init,
48 + this._reject,
49 + undefined,
50 + this,
51 + resolveValueIfEmpty
52 + );
53 + } else if (((bitField & 33554432) !== 0)) {
54 + values = values._value();
55 + } else if (((bitField & 16777216) !== 0)) {
56 + return this._reject(values._reason());
57 + } else {
58 + return this._cancel();
59 + }
60 + }
61 + values = util.asArray(values);
62 + if (values === null) {
63 + var err = apiRejection(
64 + "expecting an array or an iterable object but got " + util.classString(values)).reason();
65 + this._promise._rejectCallback(err, false);
66 + return;
67 + }
68 +
69 + if (values.length === 0) {
70 + if (resolveValueIfEmpty === -5) {
71 + this._resolveEmptyArray();
72 + }
73 + else {
74 + this._resolve(toResolutionValue(resolveValueIfEmpty));
75 + }
76 + return;
77 + }
78 + this._iterate(values);
79 +};
80 +
81 +PromiseArray.prototype._iterate = function(values) {
82 + var len = this.getActualLength(values.length);
83 + this._length = len;
84 + this._values = this.shouldCopyValues() ? new Array(len) : this._values;
85 + var result = this._promise;
86 + var isResolved = false;
87 + var bitField = null;
88 + for (var i = 0; i < len; ++i) {
89 + var maybePromise = tryConvertToPromise(values[i], result);
90 +
91 + if (maybePromise instanceof Promise) {
92 + maybePromise = maybePromise._target();
93 + bitField = maybePromise._bitField;
94 + } else {
95 + bitField = null;
96 + }
97 +
98 + if (isResolved) {
99 + if (bitField !== null) {
100 + maybePromise.suppressUnhandledRejections();
101 + }
102 + } else if (bitField !== null) {
103 + if (((bitField & 50397184) === 0)) {
104 + maybePromise._proxy(this, i);
105 + this._values[i] = maybePromise;
106 + } else if (((bitField & 33554432) !== 0)) {
107 + isResolved = this._promiseFulfilled(maybePromise._value(), i);
108 + } else if (((bitField & 16777216) !== 0)) {
109 + isResolved = this._promiseRejected(maybePromise._reason(), i);
110 + } else {
111 + isResolved = this._promiseCancelled(i);
112 + }
113 + } else {
114 + isResolved = this._promiseFulfilled(maybePromise, i);
115 + }
116 + }
117 + if (!isResolved) result._setAsyncGuaranteed();
118 +};
119 +
120 +PromiseArray.prototype._isResolved = function () {
121 + return this._values === null;
122 +};
123 +
124 +PromiseArray.prototype._resolve = function (value) {
125 + this._values = null;
126 + this._promise._fulfill(value);
127 +};
128 +
129 +PromiseArray.prototype._cancel = function() {
130 + if (this._isResolved() || !this._promise._isCancellable()) return;
131 + this._values = null;
132 + this._promise._cancel();
133 +};
134 +
135 +PromiseArray.prototype._reject = function (reason) {
136 + this._values = null;
137 + this._promise._rejectCallback(reason, false);
138 +};
139 +
140 +PromiseArray.prototype._promiseFulfilled = function (value, index) {
141 + this._values[index] = value;
142 + var totalResolved = ++this._totalResolved;
143 + if (totalResolved >= this._length) {
144 + this._resolve(this._values);
145 + return true;
146 + }
147 + return false;
148 +};
149 +
150 +PromiseArray.prototype._promiseCancelled = function() {
151 + this._cancel();
152 + return true;
153 +};
154 +
155 +PromiseArray.prototype._promiseRejected = function (reason) {
156 + this._totalResolved++;
157 + this._reject(reason);
158 + return true;
159 +};
160 +
161 +PromiseArray.prototype._resultCancelled = function() {
162 + if (this._isResolved()) return;
163 + var values = this._values;
164 + this._cancel();
165 + if (values instanceof Promise) {
166 + values.cancel();
167 + } else {
168 + for (var i = 0; i < values.length; ++i) {
169 + if (values[i] instanceof Promise) {
170 + values[i].cancel();
171 + }
172 + }
173 + }
174 +};
175 +
176 +PromiseArray.prototype.shouldCopyValues = function () {
177 + return true;
178 +};
179 +
180 +PromiseArray.prototype.getActualLength = function (len) {
181 + return len;
182 +};
183 +
184 +return PromiseArray;
185 +};
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL) {
3 +var THIS = {};
4 +var util = require("./util");
5 +var nodebackForPromise = require("./nodeback");
6 +var withAppended = util.withAppended;
7 +var maybeWrapAsError = util.maybeWrapAsError;
8 +var canEvaluate = util.canEvaluate;
9 +var TypeError = require("./errors").TypeError;
10 +var defaultSuffix = "Async";
11 +var defaultPromisified = {__isPromisified__: true};
12 +var noCopyProps = [
13 + "arity", "length",
14 + "name",
15 + "arguments",
16 + "caller",
17 + "callee",
18 + "prototype",
19 + "__isPromisified__"
20 +];
21 +var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
22 +
23 +var defaultFilter = function(name) {
24 + return util.isIdentifier(name) &&
25 + name.charAt(0) !== "_" &&
26 + name !== "constructor";
27 +};
28 +
29 +function propsFilter(key) {
30 + return !noCopyPropsPattern.test(key);
31 +}
32 +
33 +function isPromisified(fn) {
34 + try {
35 + return fn.__isPromisified__ === true;
36 + }
37 + catch (e) {
38 + return false;
39 + }
40 +}
41 +
42 +function hasPromisified(obj, key, suffix) {
43 + var val = util.getDataPropertyOrDefault(obj, key + suffix,
44 + defaultPromisified);
45 + return val ? isPromisified(val) : false;
46 +}
47 +function checkValid(ret, suffix, suffixRegexp) {
48 + for (var i = 0; i < ret.length; i += 2) {
49 + var key = ret[i];
50 + if (suffixRegexp.test(key)) {
51 + var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
52 + for (var j = 0; j < ret.length; j += 2) {
53 + if (ret[j] === keyWithoutAsyncSuffix) {
54 + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
55 + .replace("%s", suffix));
56 + }
57 + }
58 + }
59 + }
60 +}
61 +
62 +function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
63 + var keys = util.inheritedDataKeys(obj);
64 + var ret = [];
65 + for (var i = 0; i < keys.length; ++i) {
66 + var key = keys[i];
67 + var value = obj[key];
68 + var passesDefaultFilter = filter === defaultFilter
69 + ? true : defaultFilter(key, value, obj);
70 + if (typeof value === "function" &&
71 + !isPromisified(value) &&
72 + !hasPromisified(obj, key, suffix) &&
73 + filter(key, value, obj, passesDefaultFilter)) {
74 + ret.push(key, value);
75 + }
76 + }
77 + checkValid(ret, suffix, suffixRegexp);
78 + return ret;
79 +}
80 +
81 +var escapeIdentRegex = function(str) {
82 + return str.replace(/([$])/, "\\$");
83 +};
84 +
85 +var makeNodePromisifiedEval;
86 +if (!false) {
87 +var switchCaseArgumentOrder = function(likelyArgumentCount) {
88 + var ret = [likelyArgumentCount];
89 + var min = Math.max(0, likelyArgumentCount - 1 - 3);
90 + for(var i = likelyArgumentCount - 1; i >= min; --i) {
91 + ret.push(i);
92 + }
93 + for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
94 + ret.push(i);
95 + }
96 + return ret;
97 +};
98 +
99 +var argumentSequence = function(argumentCount) {
100 + return util.filledRange(argumentCount, "_arg", "");
101 +};
102 +
103 +var parameterDeclaration = function(parameterCount) {
104 + return util.filledRange(
105 + Math.max(parameterCount, 3), "_arg", "");
106 +};
107 +
108 +var parameterCount = function(fn) {
109 + if (typeof fn.length === "number") {
110 + return Math.max(Math.min(fn.length, 1023 + 1), 0);
111 + }
112 + return 0;
113 +};
114 +
115 +makeNodePromisifiedEval =
116 +function(callback, receiver, originalName, fn, _, multiArgs) {
117 + var newParameterCount = Math.max(0, parameterCount(fn) - 1);
118 + var argumentOrder = switchCaseArgumentOrder(newParameterCount);
119 + var shouldProxyThis = typeof callback === "string" || receiver === THIS;
120 +
121 + function generateCallForArgumentCount(count) {
122 + var args = argumentSequence(count).join(", ");
123 + var comma = count > 0 ? ", " : "";
124 + var ret;
125 + if (shouldProxyThis) {
126 + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
127 + } else {
128 + ret = receiver === undefined
129 + ? "ret = callback({{args}}, nodeback); break;\n"
130 + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
131 + }
132 + return ret.replace("{{args}}", args).replace(", ", comma);
133 + }
134 +
135 + function generateArgumentSwitchCase() {
136 + var ret = "";
137 + for (var i = 0; i < argumentOrder.length; ++i) {
138 + ret += "case " + argumentOrder[i] +":" +
139 + generateCallForArgumentCount(argumentOrder[i]);
140 + }
141 +
142 + ret += " \n\
143 + default: \n\
144 + var args = new Array(len + 1); \n\
145 + var i = 0; \n\
146 + for (var i = 0; i < len; ++i) { \n\
147 + args[i] = arguments[i]; \n\
148 + } \n\
149 + args[i] = nodeback; \n\
150 + [CodeForCall] \n\
151 + break; \n\
152 + ".replace("[CodeForCall]", (shouldProxyThis
153 + ? "ret = callback.apply(this, args);\n"
154 + : "ret = callback.apply(receiver, args);\n"));
155 + return ret;
156 + }
157 +
158 + var getFunctionCode = typeof callback === "string"
159 + ? ("this != null ? this['"+callback+"'] : fn")
160 + : "fn";
161 + var body = "'use strict'; \n\
162 + var ret = function (Parameters) { \n\
163 + 'use strict'; \n\
164 + var len = arguments.length; \n\
165 + var promise = new Promise(INTERNAL); \n\
166 + promise._captureStackTrace(); \n\
167 + var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
168 + var ret; \n\
169 + var callback = tryCatch([GetFunctionCode]); \n\
170 + switch(len) { \n\
171 + [CodeForSwitchCase] \n\
172 + } \n\
173 + if (ret === errorObj) { \n\
174 + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
175 + } \n\
176 + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
177 + return promise; \n\
178 + }; \n\
179 + notEnumerableProp(ret, '__isPromisified__', true); \n\
180 + return ret; \n\
181 + ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
182 + .replace("[GetFunctionCode]", getFunctionCode);
183 + body = body.replace("Parameters", parameterDeclaration(newParameterCount));
184 + return new Function("Promise",
185 + "fn",
186 + "receiver",
187 + "withAppended",
188 + "maybeWrapAsError",
189 + "nodebackForPromise",
190 + "tryCatch",
191 + "errorObj",
192 + "notEnumerableProp",
193 + "INTERNAL",
194 + body)(
195 + Promise,
196 + fn,
197 + receiver,
198 + withAppended,
199 + maybeWrapAsError,
200 + nodebackForPromise,
201 + util.tryCatch,
202 + util.errorObj,
203 + util.notEnumerableProp,
204 + INTERNAL);
205 +};
206 +}
207 +
208 +function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
209 + var defaultThis = (function() {return this;})();
210 + var method = callback;
211 + if (typeof method === "string") {
212 + callback = fn;
213 + }
214 + function promisified() {
215 + var _receiver = receiver;
216 + if (receiver === THIS) _receiver = this;
217 + var promise = new Promise(INTERNAL);
218 + promise._captureStackTrace();
219 + var cb = typeof method === "string" && this !== defaultThis
220 + ? this[method] : callback;
221 + var fn = nodebackForPromise(promise, multiArgs);
222 + try {
223 + cb.apply(_receiver, withAppended(arguments, fn));
224 + } catch(e) {
225 + promise._rejectCallback(maybeWrapAsError(e), true, true);
226 + }
227 + if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
228 + return promise;
229 + }
230 + util.notEnumerableProp(promisified, "__isPromisified__", true);
231 + return promisified;
232 +}
233 +
234 +var makeNodePromisified = canEvaluate
235 + ? makeNodePromisifiedEval
236 + : makeNodePromisifiedClosure;
237 +
238 +function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
239 + var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
240 + var methods =
241 + promisifiableMethods(obj, suffix, suffixRegexp, filter);
242 +
243 + for (var i = 0, len = methods.length; i < len; i+= 2) {
244 + var key = methods[i];
245 + var fn = methods[i+1];
246 + var promisifiedKey = key + suffix;
247 + if (promisifier === makeNodePromisified) {
248 + obj[promisifiedKey] =
249 + makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
250 + } else {
251 + var promisified = promisifier(fn, function() {
252 + return makeNodePromisified(key, THIS, key,
253 + fn, suffix, multiArgs);
254 + });
255 + util.notEnumerableProp(promisified, "__isPromisified__", true);
256 + obj[promisifiedKey] = promisified;
257 + }
258 + }
259 + util.toFastProperties(obj);
260 + return obj;
261 +}
262 +
263 +function promisify(callback, receiver, multiArgs) {
264 + return makeNodePromisified(callback, receiver, undefined,
265 + callback, null, multiArgs);
266 +}
267 +
268 +Promise.promisify = function (fn, options) {
269 + if (typeof fn !== "function") {
270 + throw new TypeError("expecting a function but got " + util.classString(fn));
271 + }
272 + if (isPromisified(fn)) {
273 + return fn;
274 + }
275 + options = Object(options);
276 + var receiver = options.context === undefined ? THIS : options.context;
277 + var multiArgs = !!options.multiArgs;
278 + var ret = promisify(fn, receiver, multiArgs);
279 + util.copyDescriptors(fn, ret, propsFilter);
280 + return ret;
281 +};
282 +
283 +Promise.promisifyAll = function (target, options) {
284 + if (typeof target !== "function" && typeof target !== "object") {
285 + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
286 + }
287 + options = Object(options);
288 + var multiArgs = !!options.multiArgs;
289 + var suffix = options.suffix;
290 + if (typeof suffix !== "string") suffix = defaultSuffix;
291 + var filter = options.filter;
292 + if (typeof filter !== "function") filter = defaultFilter;
293 + var promisifier = options.promisifier;
294 + if (typeof promisifier !== "function") promisifier = makeNodePromisified;
295 +
296 + if (!util.isIdentifier(suffix)) {
297 + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
298 + }
299 +
300 + var keys = util.inheritedDataKeys(target);
301 + for (var i = 0; i < keys.length; ++i) {
302 + var value = target[keys[i]];
303 + if (keys[i] !== "constructor" &&
304 + util.isClass(value)) {
305 + promisifyAll(value.prototype, suffix, filter, promisifier,
306 + multiArgs);
307 + promisifyAll(value, suffix, filter, promisifier, multiArgs);
308 + }
309 + }
310 +
311 + return promisifyAll(target, suffix, filter, promisifier, multiArgs);
312 +};
313 +};
314 +
1 +"use strict";
2 +module.exports = function(
3 + Promise, PromiseArray, tryConvertToPromise, apiRejection) {
4 +var util = require("./util");
5 +var isObject = util.isObject;
6 +var es5 = require("./es5");
7 +var Es6Map;
8 +if (typeof Map === "function") Es6Map = Map;
9 +
10 +var mapToEntries = (function() {
11 + var index = 0;
12 + var size = 0;
13 +
14 + function extractEntry(value, key) {
15 + this[index] = value;
16 + this[index + size] = key;
17 + index++;
18 + }
19 +
20 + return function mapToEntries(map) {
21 + size = map.size;
22 + index = 0;
23 + var ret = new Array(map.size * 2);
24 + map.forEach(extractEntry, ret);
25 + return ret;
26 + };
27 +})();
28 +
29 +var entriesToMap = function(entries) {
30 + var ret = new Es6Map();
31 + var length = entries.length / 2 | 0;
32 + for (var i = 0; i < length; ++i) {
33 + var key = entries[length + i];
34 + var value = entries[i];
35 + ret.set(key, value);
36 + }
37 + return ret;
38 +};
39 +
40 +function PropertiesPromiseArray(obj) {
41 + var isMap = false;
42 + var entries;
43 + if (Es6Map !== undefined && obj instanceof Es6Map) {
44 + entries = mapToEntries(obj);
45 + isMap = true;
46 + } else {
47 + var keys = es5.keys(obj);
48 + var len = keys.length;
49 + entries = new Array(len * 2);
50 + for (var i = 0; i < len; ++i) {
51 + var key = keys[i];
52 + entries[i] = obj[key];
53 + entries[i + len] = key;
54 + }
55 + }
56 + this.constructor$(entries);
57 + this._isMap = isMap;
58 + this._init$(undefined, isMap ? -6 : -3);
59 +}
60 +util.inherits(PropertiesPromiseArray, PromiseArray);
61 +
62 +PropertiesPromiseArray.prototype._init = function () {};
63 +
64 +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
65 + this._values[index] = value;
66 + var totalResolved = ++this._totalResolved;
67 + if (totalResolved >= this._length) {
68 + var val;
69 + if (this._isMap) {
70 + val = entriesToMap(this._values);
71 + } else {
72 + val = {};
73 + var keyOffset = this.length();
74 + for (var i = 0, len = this.length(); i < len; ++i) {
75 + val[this._values[i + keyOffset]] = this._values[i];
76 + }
77 + }
78 + this._resolve(val);
79 + return true;
80 + }
81 + return false;
82 +};
83 +
84 +PropertiesPromiseArray.prototype.shouldCopyValues = function () {
85 + return false;
86 +};
87 +
88 +PropertiesPromiseArray.prototype.getActualLength = function (len) {
89 + return len >> 1;
90 +};
91 +
92 +function props(promises) {
93 + var ret;
94 + var castValue = tryConvertToPromise(promises);
95 +
96 + if (!isObject(castValue)) {
97 + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
98 + } else if (castValue instanceof Promise) {
99 + ret = castValue._then(
100 + Promise.props, undefined, undefined, undefined, undefined);
101 + } else {
102 + ret = new PropertiesPromiseArray(castValue).promise();
103 + }
104 +
105 + if (castValue instanceof Promise) {
106 + ret._propagateFrom(castValue, 2);
107 + }
108 + return ret;
109 +}
110 +
111 +Promise.prototype.props = function () {
112 + return props(this);
113 +};
114 +
115 +Promise.props = function (promises) {
116 + return props(promises);
117 +};
118 +};
1 +"use strict";
2 +function arrayMove(src, srcIndex, dst, dstIndex, len) {
3 + for (var j = 0; j < len; ++j) {
4 + dst[j + dstIndex] = src[j + srcIndex];
5 + src[j + srcIndex] = void 0;
6 + }
7 +}
8 +
9 +function Queue(capacity) {
10 + this._capacity = capacity;
11 + this._length = 0;
12 + this._front = 0;
13 +}
14 +
15 +Queue.prototype._willBeOverCapacity = function (size) {
16 + return this._capacity < size;
17 +};
18 +
19 +Queue.prototype._pushOne = function (arg) {
20 + var length = this.length();
21 + this._checkCapacity(length + 1);
22 + var i = (this._front + length) & (this._capacity - 1);
23 + this[i] = arg;
24 + this._length = length + 1;
25 +};
26 +
27 +Queue.prototype.push = function (fn, receiver, arg) {
28 + var length = this.length() + 3;
29 + if (this._willBeOverCapacity(length)) {
30 + this._pushOne(fn);
31 + this._pushOne(receiver);
32 + this._pushOne(arg);
33 + return;
34 + }
35 + var j = this._front + length - 3;
36 + this._checkCapacity(length);
37 + var wrapMask = this._capacity - 1;
38 + this[(j + 0) & wrapMask] = fn;
39 + this[(j + 1) & wrapMask] = receiver;
40 + this[(j + 2) & wrapMask] = arg;
41 + this._length = length;
42 +};
43 +
44 +Queue.prototype.shift = function () {
45 + var front = this._front,
46 + ret = this[front];
47 +
48 + this[front] = undefined;
49 + this._front = (front + 1) & (this._capacity - 1);
50 + this._length--;
51 + return ret;
52 +};
53 +
54 +Queue.prototype.length = function () {
55 + return this._length;
56 +};
57 +
58 +Queue.prototype._checkCapacity = function (size) {
59 + if (this._capacity < size) {
60 + this._resizeTo(this._capacity << 1);
61 + }
62 +};
63 +
64 +Queue.prototype._resizeTo = function (capacity) {
65 + var oldCapacity = this._capacity;
66 + this._capacity = capacity;
67 + var front = this._front;
68 + var length = this._length;
69 + var moveItemsCount = (front + length) & (oldCapacity - 1);
70 + arrayMove(this, 0, this, oldCapacity, moveItemsCount);
71 +};
72 +
73 +module.exports = Queue;
1 +"use strict";
2 +module.exports = function(
3 + Promise, INTERNAL, tryConvertToPromise, apiRejection) {
4 +var util = require("./util");
5 +
6 +var raceLater = function (promise) {
7 + return promise.then(function(array) {
8 + return race(array, promise);
9 + });
10 +};
11 +
12 +function race(promises, parent) {
13 + var maybePromise = tryConvertToPromise(promises);
14 +
15 + if (maybePromise instanceof Promise) {
16 + return raceLater(maybePromise);
17 + } else {
18 + promises = util.asArray(promises);
19 + if (promises === null)
20 + return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
21 + }
22 +
23 + var ret = new Promise(INTERNAL);
24 + if (parent !== undefined) {
25 + ret._propagateFrom(parent, 3);
26 + }
27 + var fulfill = ret._fulfill;
28 + var reject = ret._reject;
29 + for (var i = 0, len = promises.length; i < len; ++i) {
30 + var val = promises[i];
31 +
32 + if (val === undefined && !(i in promises)) {
33 + continue;
34 + }
35 +
36 + Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
37 + }
38 + return ret;
39 +}
40 +
41 +Promise.race = function (promises) {
42 + return race(promises, undefined);
43 +};
44 +
45 +Promise.prototype.race = function () {
46 + return race(this, undefined);
47 +};
48 +
49 +};
1 +"use strict";
2 +module.exports = function(Promise,
3 + PromiseArray,
4 + apiRejection,
5 + tryConvertToPromise,
6 + INTERNAL,
7 + debug) {
8 +var getDomain = Promise._getDomain;
9 +var util = require("./util");
10 +var tryCatch = util.tryCatch;
11 +
12 +function ReductionPromiseArray(promises, fn, initialValue, _each) {
13 + this.constructor$(promises);
14 + var domain = getDomain();
15 + this._fn = domain === null ? fn : util.domainBind(domain, fn);
16 + if (initialValue !== undefined) {
17 + initialValue = Promise.resolve(initialValue);
18 + initialValue._attachCancellationCallback(this);
19 + }
20 + this._initialValue = initialValue;
21 + this._currentCancellable = null;
22 + if(_each === INTERNAL) {
23 + this._eachValues = Array(this._length);
24 + } else if (_each === 0) {
25 + this._eachValues = null;
26 + } else {
27 + this._eachValues = undefined;
28 + }
29 + this._promise._captureStackTrace();
30 + this._init$(undefined, -5);
31 +}
32 +util.inherits(ReductionPromiseArray, PromiseArray);
33 +
34 +ReductionPromiseArray.prototype._gotAccum = function(accum) {
35 + if (this._eachValues !== undefined &&
36 + this._eachValues !== null &&
37 + accum !== INTERNAL) {
38 + this._eachValues.push(accum);
39 + }
40 +};
41 +
42 +ReductionPromiseArray.prototype._eachComplete = function(value) {
43 + if (this._eachValues !== null) {
44 + this._eachValues.push(value);
45 + }
46 + return this._eachValues;
47 +};
48 +
49 +ReductionPromiseArray.prototype._init = function() {};
50 +
51 +ReductionPromiseArray.prototype._resolveEmptyArray = function() {
52 + this._resolve(this._eachValues !== undefined ? this._eachValues
53 + : this._initialValue);
54 +};
55 +
56 +ReductionPromiseArray.prototype.shouldCopyValues = function () {
57 + return false;
58 +};
59 +
60 +ReductionPromiseArray.prototype._resolve = function(value) {
61 + this._promise._resolveCallback(value);
62 + this._values = null;
63 +};
64 +
65 +ReductionPromiseArray.prototype._resultCancelled = function(sender) {
66 + if (sender === this._initialValue) return this._cancel();
67 + if (this._isResolved()) return;
68 + this._resultCancelled$();
69 + if (this._currentCancellable instanceof Promise) {
70 + this._currentCancellable.cancel();
71 + }
72 + if (this._initialValue instanceof Promise) {
73 + this._initialValue.cancel();
74 + }
75 +};
76 +
77 +ReductionPromiseArray.prototype._iterate = function (values) {
78 + this._values = values;
79 + var value;
80 + var i;
81 + var length = values.length;
82 + if (this._initialValue !== undefined) {
83 + value = this._initialValue;
84 + i = 0;
85 + } else {
86 + value = Promise.resolve(values[0]);
87 + i = 1;
88 + }
89 +
90 + this._currentCancellable = value;
91 +
92 + if (!value.isRejected()) {
93 + for (; i < length; ++i) {
94 + var ctx = {
95 + accum: null,
96 + value: values[i],
97 + index: i,
98 + length: length,
99 + array: this
100 + };
101 + value = value._then(gotAccum, undefined, undefined, ctx, undefined);
102 + }
103 + }
104 +
105 + if (this._eachValues !== undefined) {
106 + value = value
107 + ._then(this._eachComplete, undefined, undefined, this, undefined);
108 + }
109 + value._then(completed, completed, undefined, value, this);
110 +};
111 +
112 +Promise.prototype.reduce = function (fn, initialValue) {
113 + return reduce(this, fn, initialValue, null);
114 +};
115 +
116 +Promise.reduce = function (promises, fn, initialValue, _each) {
117 + return reduce(promises, fn, initialValue, _each);
118 +};
119 +
120 +function completed(valueOrReason, array) {
121 + if (this.isFulfilled()) {
122 + array._resolve(valueOrReason);
123 + } else {
124 + array._reject(valueOrReason);
125 + }
126 +}
127 +
128 +function reduce(promises, fn, initialValue, _each) {
129 + if (typeof fn !== "function") {
130 + return apiRejection("expecting a function but got " + util.classString(fn));
131 + }
132 + var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
133 + return array.promise();
134 +}
135 +
136 +function gotAccum(accum) {
137 + this.accum = accum;
138 + this.array._gotAccum(accum);
139 + var value = tryConvertToPromise(this.value, this.array._promise);
140 + if (value instanceof Promise) {
141 + this.array._currentCancellable = value;
142 + return value._then(gotValue, undefined, undefined, this, undefined);
143 + } else {
144 + return gotValue.call(this, value);
145 + }
146 +}
147 +
148 +function gotValue(value) {
149 + var array = this.array;
150 + var promise = array._promise;
151 + var fn = tryCatch(array._fn);
152 + promise._pushContext();
153 + var ret;
154 + if (array._eachValues !== undefined) {
155 + ret = fn.call(promise._boundValue(), value, this.index, this.length);
156 + } else {
157 + ret = fn.call(promise._boundValue(),
158 + this.accum, value, this.index, this.length);
159 + }
160 + if (ret instanceof Promise) {
161 + array._currentCancellable = ret;
162 + }
163 + var promiseCreated = promise._popContext();
164 + debug.checkForgottenReturns(
165 + ret,
166 + promiseCreated,
167 + array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
168 + promise
169 + );
170 + return ret;
171 +}
172 +};
1 +"use strict";
2 +var util = require("./util");
3 +var schedule;
4 +var noAsyncScheduler = function() {
5 + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
6 +};
7 +var NativePromise = util.getNativePromise();
8 +if (util.isNode && typeof MutationObserver === "undefined") {
9 + var GlobalSetImmediate = global.setImmediate;
10 + var ProcessNextTick = process.nextTick;
11 + schedule = util.isRecentNode
12 + ? function(fn) { GlobalSetImmediate.call(global, fn); }
13 + : function(fn) { ProcessNextTick.call(process, fn); };
14 +} else if (typeof NativePromise === "function" &&
15 + typeof NativePromise.resolve === "function") {
16 + var nativePromise = NativePromise.resolve();
17 + schedule = function(fn) {
18 + nativePromise.then(fn);
19 + };
20 +} else if ((typeof MutationObserver !== "undefined") &&
21 + !(typeof window !== "undefined" &&
22 + window.navigator &&
23 + (window.navigator.standalone || window.cordova))) {
24 + schedule = (function() {
25 + var div = document.createElement("div");
26 + var opts = {attributes: true};
27 + var toggleScheduled = false;
28 + var div2 = document.createElement("div");
29 + var o2 = new MutationObserver(function() {
30 + div.classList.toggle("foo");
31 + toggleScheduled = false;
32 + });
33 + o2.observe(div2, opts);
34 +
35 + var scheduleToggle = function() {
36 + if (toggleScheduled) return;
37 + toggleScheduled = true;
38 + div2.classList.toggle("foo");
39 + };
40 +
41 + return function schedule(fn) {
42 + var o = new MutationObserver(function() {
43 + o.disconnect();
44 + fn();
45 + });
46 + o.observe(div, opts);
47 + scheduleToggle();
48 + };
49 + })();
50 +} else if (typeof setImmediate !== "undefined") {
51 + schedule = function (fn) {
52 + setImmediate(fn);
53 + };
54 +} else if (typeof setTimeout !== "undefined") {
55 + schedule = function (fn) {
56 + setTimeout(fn, 0);
57 + };
58 +} else {
59 + schedule = noAsyncScheduler;
60 +}
61 +module.exports = schedule;
1 +"use strict";
2 +module.exports =
3 + function(Promise, PromiseArray, debug) {
4 +var PromiseInspection = Promise.PromiseInspection;
5 +var util = require("./util");
6 +
7 +function SettledPromiseArray(values) {
8 + this.constructor$(values);
9 +}
10 +util.inherits(SettledPromiseArray, PromiseArray);
11 +
12 +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
13 + this._values[index] = inspection;
14 + var totalResolved = ++this._totalResolved;
15 + if (totalResolved >= this._length) {
16 + this._resolve(this._values);
17 + return true;
18 + }
19 + return false;
20 +};
21 +
22 +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
23 + var ret = new PromiseInspection();
24 + ret._bitField = 33554432;
25 + ret._settledValueField = value;
26 + return this._promiseResolved(index, ret);
27 +};
28 +SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
29 + var ret = new PromiseInspection();
30 + ret._bitField = 16777216;
31 + ret._settledValueField = reason;
32 + return this._promiseResolved(index, ret);
33 +};
34 +
35 +Promise.settle = function (promises) {
36 + debug.deprecated(".settle()", ".reflect()");
37 + return new SettledPromiseArray(promises).promise();
38 +};
39 +
40 +Promise.prototype.settle = function () {
41 + return Promise.settle(this);
42 +};
43 +};
1 +"use strict";
2 +module.exports =
3 +function(Promise, PromiseArray, apiRejection) {
4 +var util = require("./util");
5 +var RangeError = require("./errors").RangeError;
6 +var AggregateError = require("./errors").AggregateError;
7 +var isArray = util.isArray;
8 +var CANCELLATION = {};
9 +
10 +
11 +function SomePromiseArray(values) {
12 + this.constructor$(values);
13 + this._howMany = 0;
14 + this._unwrap = false;
15 + this._initialized = false;
16 +}
17 +util.inherits(SomePromiseArray, PromiseArray);
18 +
19 +SomePromiseArray.prototype._init = function () {
20 + if (!this._initialized) {
21 + return;
22 + }
23 + if (this._howMany === 0) {
24 + this._resolve([]);
25 + return;
26 + }
27 + this._init$(undefined, -5);
28 + var isArrayResolved = isArray(this._values);
29 + if (!this._isResolved() &&
30 + isArrayResolved &&
31 + this._howMany > this._canPossiblyFulfill()) {
32 + this._reject(this._getRangeError(this.length()));
33 + }
34 +};
35 +
36 +SomePromiseArray.prototype.init = function () {
37 + this._initialized = true;
38 + this._init();
39 +};
40 +
41 +SomePromiseArray.prototype.setUnwrap = function () {
42 + this._unwrap = true;
43 +};
44 +
45 +SomePromiseArray.prototype.howMany = function () {
46 + return this._howMany;
47 +};
48 +
49 +SomePromiseArray.prototype.setHowMany = function (count) {
50 + this._howMany = count;
51 +};
52 +
53 +SomePromiseArray.prototype._promiseFulfilled = function (value) {
54 + this._addFulfilled(value);
55 + if (this._fulfilled() === this.howMany()) {
56 + this._values.length = this.howMany();
57 + if (this.howMany() === 1 && this._unwrap) {
58 + this._resolve(this._values[0]);
59 + } else {
60 + this._resolve(this._values);
61 + }
62 + return true;
63 + }
64 + return false;
65 +
66 +};
67 +SomePromiseArray.prototype._promiseRejected = function (reason) {
68 + this._addRejected(reason);
69 + return this._checkOutcome();
70 +};
71 +
72 +SomePromiseArray.prototype._promiseCancelled = function () {
73 + if (this._values instanceof Promise || this._values == null) {
74 + return this._cancel();
75 + }
76 + this._addRejected(CANCELLATION);
77 + return this._checkOutcome();
78 +};
79 +
80 +SomePromiseArray.prototype._checkOutcome = function() {
81 + if (this.howMany() > this._canPossiblyFulfill()) {
82 + var e = new AggregateError();
83 + for (var i = this.length(); i < this._values.length; ++i) {
84 + if (this._values[i] !== CANCELLATION) {
85 + e.push(this._values[i]);
86 + }
87 + }
88 + if (e.length > 0) {
89 + this._reject(e);
90 + } else {
91 + this._cancel();
92 + }
93 + return true;
94 + }
95 + return false;
96 +};
97 +
98 +SomePromiseArray.prototype._fulfilled = function () {
99 + return this._totalResolved;
100 +};
101 +
102 +SomePromiseArray.prototype._rejected = function () {
103 + return this._values.length - this.length();
104 +};
105 +
106 +SomePromiseArray.prototype._addRejected = function (reason) {
107 + this._values.push(reason);
108 +};
109 +
110 +SomePromiseArray.prototype._addFulfilled = function (value) {
111 + this._values[this._totalResolved++] = value;
112 +};
113 +
114 +SomePromiseArray.prototype._canPossiblyFulfill = function () {
115 + return this.length() - this._rejected();
116 +};
117 +
118 +SomePromiseArray.prototype._getRangeError = function (count) {
119 + var message = "Input array must contain at least " +
120 + this._howMany + " items but contains only " + count + " items";
121 + return new RangeError(message);
122 +};
123 +
124 +SomePromiseArray.prototype._resolveEmptyArray = function () {
125 + this._reject(this._getRangeError(0));
126 +};
127 +
128 +function some(promises, howMany) {
129 + if ((howMany | 0) !== howMany || howMany < 0) {
130 + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
131 + }
132 + var ret = new SomePromiseArray(promises);
133 + var promise = ret.promise();
134 + ret.setHowMany(howMany);
135 + ret.init();
136 + return promise;
137 +}
138 +
139 +Promise.some = function (promises, howMany) {
140 + return some(promises, howMany);
141 +};
142 +
143 +Promise.prototype.some = function (howMany) {
144 + return some(this, howMany);
145 +};
146 +
147 +Promise._SomePromiseArray = SomePromiseArray;
148 +};
1 +"use strict";
2 +module.exports = function(Promise) {
3 +function PromiseInspection(promise) {
4 + if (promise !== undefined) {
5 + promise = promise._target();
6 + this._bitField = promise._bitField;
7 + this._settledValueField = promise._isFateSealed()
8 + ? promise._settledValue() : undefined;
9 + }
10 + else {
11 + this._bitField = 0;
12 + this._settledValueField = undefined;
13 + }
14 +}
15 +
16 +PromiseInspection.prototype._settledValue = function() {
17 + return this._settledValueField;
18 +};
19 +
20 +var value = PromiseInspection.prototype.value = function () {
21 + if (!this.isFulfilled()) {
22 + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
23 + }
24 + return this._settledValue();
25 +};
26 +
27 +var reason = PromiseInspection.prototype.error =
28 +PromiseInspection.prototype.reason = function () {
29 + if (!this.isRejected()) {
30 + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
31 + }
32 + return this._settledValue();
33 +};
34 +
35 +var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
36 + return (this._bitField & 33554432) !== 0;
37 +};
38 +
39 +var isRejected = PromiseInspection.prototype.isRejected = function () {
40 + return (this._bitField & 16777216) !== 0;
41 +};
42 +
43 +var isPending = PromiseInspection.prototype.isPending = function () {
44 + return (this._bitField & 50397184) === 0;
45 +};
46 +
47 +var isResolved = PromiseInspection.prototype.isResolved = function () {
48 + return (this._bitField & 50331648) !== 0;
49 +};
50 +
51 +PromiseInspection.prototype.isCancelled = function() {
52 + return (this._bitField & 8454144) !== 0;
53 +};
54 +
55 +Promise.prototype.__isCancelled = function() {
56 + return (this._bitField & 65536) === 65536;
57 +};
58 +
59 +Promise.prototype._isCancelled = function() {
60 + return this._target().__isCancelled();
61 +};
62 +
63 +Promise.prototype.isCancelled = function() {
64 + return (this._target()._bitField & 8454144) !== 0;
65 +};
66 +
67 +Promise.prototype.isPending = function() {
68 + return isPending.call(this._target());
69 +};
70 +
71 +Promise.prototype.isRejected = function() {
72 + return isRejected.call(this._target());
73 +};
74 +
75 +Promise.prototype.isFulfilled = function() {
76 + return isFulfilled.call(this._target());
77 +};
78 +
79 +Promise.prototype.isResolved = function() {
80 + return isResolved.call(this._target());
81 +};
82 +
83 +Promise.prototype.value = function() {
84 + return value.call(this._target());
85 +};
86 +
87 +Promise.prototype.reason = function() {
88 + var target = this._target();
89 + target._unsetRejectionIsUnhandled();
90 + return reason.call(target);
91 +};
92 +
93 +Promise.prototype._value = function() {
94 + return this._settledValue();
95 +};
96 +
97 +Promise.prototype._reason = function() {
98 + this._unsetRejectionIsUnhandled();
99 + return this._settledValue();
100 +};
101 +
102 +Promise.PromiseInspection = PromiseInspection;
103 +};
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL) {
3 +var util = require("./util");
4 +var errorObj = util.errorObj;
5 +var isObject = util.isObject;
6 +
7 +function tryConvertToPromise(obj, context) {
8 + if (isObject(obj)) {
9 + if (obj instanceof Promise) return obj;
10 + var then = getThen(obj);
11 + if (then === errorObj) {
12 + if (context) context._pushContext();
13 + var ret = Promise.reject(then.e);
14 + if (context) context._popContext();
15 + return ret;
16 + } else if (typeof then === "function") {
17 + if (isAnyBluebirdPromise(obj)) {
18 + var ret = new Promise(INTERNAL);
19 + obj._then(
20 + ret._fulfill,
21 + ret._reject,
22 + undefined,
23 + ret,
24 + null
25 + );
26 + return ret;
27 + }
28 + return doThenable(obj, then, context);
29 + }
30 + }
31 + return obj;
32 +}
33 +
34 +function doGetThen(obj) {
35 + return obj.then;
36 +}
37 +
38 +function getThen(obj) {
39 + try {
40 + return doGetThen(obj);
41 + } catch (e) {
42 + errorObj.e = e;
43 + return errorObj;
44 + }
45 +}
46 +
47 +var hasProp = {}.hasOwnProperty;
48 +function isAnyBluebirdPromise(obj) {
49 + try {
50 + return hasProp.call(obj, "_promise0");
51 + } catch (e) {
52 + return false;
53 + }
54 +}
55 +
56 +function doThenable(x, then, context) {
57 + var promise = new Promise(INTERNAL);
58 + var ret = promise;
59 + if (context) context._pushContext();
60 + promise._captureStackTrace();
61 + if (context) context._popContext();
62 + var synchronous = true;
63 + var result = util.tryCatch(then).call(x, resolve, reject);
64 + synchronous = false;
65 +
66 + if (promise && result === errorObj) {
67 + promise._rejectCallback(result.e, true, true);
68 + promise = null;
69 + }
70 +
71 + function resolve(value) {
72 + if (!promise) return;
73 + promise._resolveCallback(value);
74 + promise = null;
75 + }
76 +
77 + function reject(reason) {
78 + if (!promise) return;
79 + promise._rejectCallback(reason, synchronous, true);
80 + promise = null;
81 + }
82 + return ret;
83 +}
84 +
85 +return tryConvertToPromise;
86 +};
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL, debug) {
3 +var util = require("./util");
4 +var TimeoutError = Promise.TimeoutError;
5 +
6 +function HandleWrapper(handle) {
7 + this.handle = handle;
8 +}
9 +
10 +HandleWrapper.prototype._resultCancelled = function() {
11 + clearTimeout(this.handle);
12 +};
13 +
14 +var afterValue = function(value) { return delay(+this).thenReturn(value); };
15 +var delay = Promise.delay = function (ms, value) {
16 + var ret;
17 + var handle;
18 + if (value !== undefined) {
19 + ret = Promise.resolve(value)
20 + ._then(afterValue, null, null, ms, undefined);
21 + if (debug.cancellation() && value instanceof Promise) {
22 + ret._setOnCancel(value);
23 + }
24 + } else {
25 + ret = new Promise(INTERNAL);
26 + handle = setTimeout(function() { ret._fulfill(); }, +ms);
27 + if (debug.cancellation()) {
28 + ret._setOnCancel(new HandleWrapper(handle));
29 + }
30 + ret._captureStackTrace();
31 + }
32 + ret._setAsyncGuaranteed();
33 + return ret;
34 +};
35 +
36 +Promise.prototype.delay = function (ms) {
37 + return delay(ms, this);
38 +};
39 +
40 +var afterTimeout = function (promise, message, parent) {
41 + var err;
42 + if (typeof message !== "string") {
43 + if (message instanceof Error) {
44 + err = message;
45 + } else {
46 + err = new TimeoutError("operation timed out");
47 + }
48 + } else {
49 + err = new TimeoutError(message);
50 + }
51 + util.markAsOriginatingFromRejection(err);
52 + promise._attachExtraTrace(err);
53 + promise._reject(err);
54 +
55 + if (parent != null) {
56 + parent.cancel();
57 + }
58 +};
59 +
60 +function successClear(value) {
61 + clearTimeout(this.handle);
62 + return value;
63 +}
64 +
65 +function failureClear(reason) {
66 + clearTimeout(this.handle);
67 + throw reason;
68 +}
69 +
70 +Promise.prototype.timeout = function (ms, message) {
71 + ms = +ms;
72 + var ret, parent;
73 +
74 + var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
75 + if (ret.isPending()) {
76 + afterTimeout(ret, message, parent);
77 + }
78 + }, ms));
79 +
80 + if (debug.cancellation()) {
81 + parent = this.then();
82 + ret = parent._then(successClear, failureClear,
83 + undefined, handleWrapper, undefined);
84 + ret._setOnCancel(handleWrapper);
85 + } else {
86 + ret = this._then(successClear, failureClear,
87 + undefined, handleWrapper, undefined);
88 + }
89 +
90 + return ret;
91 +};
92 +
93 +};
1 +"use strict";
2 +module.exports = function (Promise, apiRejection, tryConvertToPromise,
3 + createContext, INTERNAL, debug) {
4 + var util = require("./util");
5 + var TypeError = require("./errors").TypeError;
6 + var inherits = require("./util").inherits;
7 + var errorObj = util.errorObj;
8 + var tryCatch = util.tryCatch;
9 + var NULL = {};
10 +
11 + function thrower(e) {
12 + setTimeout(function(){throw e;}, 0);
13 + }
14 +
15 + function castPreservingDisposable(thenable) {
16 + var maybePromise = tryConvertToPromise(thenable);
17 + if (maybePromise !== thenable &&
18 + typeof thenable._isDisposable === "function" &&
19 + typeof thenable._getDisposer === "function" &&
20 + thenable._isDisposable()) {
21 + maybePromise._setDisposable(thenable._getDisposer());
22 + }
23 + return maybePromise;
24 + }
25 + function dispose(resources, inspection) {
26 + var i = 0;
27 + var len = resources.length;
28 + var ret = new Promise(INTERNAL);
29 + function iterator() {
30 + if (i >= len) return ret._fulfill();
31 + var maybePromise = castPreservingDisposable(resources[i++]);
32 + if (maybePromise instanceof Promise &&
33 + maybePromise._isDisposable()) {
34 + try {
35 + maybePromise = tryConvertToPromise(
36 + maybePromise._getDisposer().tryDispose(inspection),
37 + resources.promise);
38 + } catch (e) {
39 + return thrower(e);
40 + }
41 + if (maybePromise instanceof Promise) {
42 + return maybePromise._then(iterator, thrower,
43 + null, null, null);
44 + }
45 + }
46 + iterator();
47 + }
48 + iterator();
49 + return ret;
50 + }
51 +
52 + function Disposer(data, promise, context) {
53 + this._data = data;
54 + this._promise = promise;
55 + this._context = context;
56 + }
57 +
58 + Disposer.prototype.data = function () {
59 + return this._data;
60 + };
61 +
62 + Disposer.prototype.promise = function () {
63 + return this._promise;
64 + };
65 +
66 + Disposer.prototype.resource = function () {
67 + if (this.promise().isFulfilled()) {
68 + return this.promise().value();
69 + }
70 + return NULL;
71 + };
72 +
73 + Disposer.prototype.tryDispose = function(inspection) {
74 + var resource = this.resource();
75 + var context = this._context;
76 + if (context !== undefined) context._pushContext();
77 + var ret = resource !== NULL
78 + ? this.doDispose(resource, inspection) : null;
79 + if (context !== undefined) context._popContext();
80 + this._promise._unsetDisposable();
81 + this._data = null;
82 + return ret;
83 + };
84 +
85 + Disposer.isDisposer = function (d) {
86 + return (d != null &&
87 + typeof d.resource === "function" &&
88 + typeof d.tryDispose === "function");
89 + };
90 +
91 + function FunctionDisposer(fn, promise, context) {
92 + this.constructor$(fn, promise, context);
93 + }
94 + inherits(FunctionDisposer, Disposer);
95 +
96 + FunctionDisposer.prototype.doDispose = function (resource, inspection) {
97 + var fn = this.data();
98 + return fn.call(resource, resource, inspection);
99 + };
100 +
101 + function maybeUnwrapDisposer(value) {
102 + if (Disposer.isDisposer(value)) {
103 + this.resources[this.index]._setDisposable(value);
104 + return value.promise();
105 + }
106 + return value;
107 + }
108 +
109 + function ResourceList(length) {
110 + this.length = length;
111 + this.promise = null;
112 + this[length-1] = null;
113 + }
114 +
115 + ResourceList.prototype._resultCancelled = function() {
116 + var len = this.length;
117 + for (var i = 0; i < len; ++i) {
118 + var item = this[i];
119 + if (item instanceof Promise) {
120 + item.cancel();
121 + }
122 + }
123 + };
124 +
125 + Promise.using = function () {
126 + var len = arguments.length;
127 + if (len < 2) return apiRejection(
128 + "you must pass at least 2 arguments to Promise.using");
129 + var fn = arguments[len - 1];
130 + if (typeof fn !== "function") {
131 + return apiRejection("expecting a function but got " + util.classString(fn));
132 + }
133 + var input;
134 + var spreadArgs = true;
135 + if (len === 2 && Array.isArray(arguments[0])) {
136 + input = arguments[0];
137 + len = input.length;
138 + spreadArgs = false;
139 + } else {
140 + input = arguments;
141 + len--;
142 + }
143 + var resources = new ResourceList(len);
144 + for (var i = 0; i < len; ++i) {
145 + var resource = input[i];
146 + if (Disposer.isDisposer(resource)) {
147 + var disposer = resource;
148 + resource = resource.promise();
149 + resource._setDisposable(disposer);
150 + } else {
151 + var maybePromise = tryConvertToPromise(resource);
152 + if (maybePromise instanceof Promise) {
153 + resource =
154 + maybePromise._then(maybeUnwrapDisposer, null, null, {
155 + resources: resources,
156 + index: i
157 + }, undefined);
158 + }
159 + }
160 + resources[i] = resource;
161 + }
162 +
163 + var reflectedResources = new Array(resources.length);
164 + for (var i = 0; i < reflectedResources.length; ++i) {
165 + reflectedResources[i] = Promise.resolve(resources[i]).reflect();
166 + }
167 +
168 + var resultPromise = Promise.all(reflectedResources)
169 + .then(function(inspections) {
170 + for (var i = 0; i < inspections.length; ++i) {
171 + var inspection = inspections[i];
172 + if (inspection.isRejected()) {
173 + errorObj.e = inspection.error();
174 + return errorObj;
175 + } else if (!inspection.isFulfilled()) {
176 + resultPromise.cancel();
177 + return;
178 + }
179 + inspections[i] = inspection.value();
180 + }
181 + promise._pushContext();
182 +
183 + fn = tryCatch(fn);
184 + var ret = spreadArgs
185 + ? fn.apply(undefined, inspections) : fn(inspections);
186 + var promiseCreated = promise._popContext();
187 + debug.checkForgottenReturns(
188 + ret, promiseCreated, "Promise.using", promise);
189 + return ret;
190 + });
191 +
192 + var promise = resultPromise.lastly(function() {
193 + var inspection = new Promise.PromiseInspection(resultPromise);
194 + return dispose(resources, inspection);
195 + });
196 + resources.promise = promise;
197 + promise._setOnCancel(resources);
198 + return promise;
199 + };
200 +
201 + Promise.prototype._setDisposable = function (disposer) {
202 + this._bitField = this._bitField | 131072;
203 + this._disposer = disposer;
204 + };
205 +
206 + Promise.prototype._isDisposable = function () {
207 + return (this._bitField & 131072) > 0;
208 + };
209 +
210 + Promise.prototype._getDisposer = function () {
211 + return this._disposer;
212 + };
213 +
214 + Promise.prototype._unsetDisposable = function () {
215 + this._bitField = this._bitField & (~131072);
216 + this._disposer = undefined;
217 + };
218 +
219 + Promise.prototype.disposer = function (fn) {
220 + if (typeof fn === "function") {
221 + return new FunctionDisposer(fn, this, createContext());
222 + }
223 + throw new TypeError();
224 + };
225 +
226 +};
1 +"use strict";
2 +var es5 = require("./es5");
3 +var canEvaluate = typeof navigator == "undefined";
4 +
5 +var errorObj = {e: {}};
6 +var tryCatchTarget;
7 +var globalObject = typeof self !== "undefined" ? self :
8 + typeof window !== "undefined" ? window :
9 + typeof global !== "undefined" ? global :
10 + this !== undefined ? this : null;
11 +
12 +function tryCatcher() {
13 + try {
14 + var target = tryCatchTarget;
15 + tryCatchTarget = null;
16 + return target.apply(this, arguments);
17 + } catch (e) {
18 + errorObj.e = e;
19 + return errorObj;
20 + }
21 +}
22 +function tryCatch(fn) {
23 + tryCatchTarget = fn;
24 + return tryCatcher;
25 +}
26 +
27 +var inherits = function(Child, Parent) {
28 + var hasProp = {}.hasOwnProperty;
29 +
30 + function T() {
31 + this.constructor = Child;
32 + this.constructor$ = Parent;
33 + for (var propertyName in Parent.prototype) {
34 + if (hasProp.call(Parent.prototype, propertyName) &&
35 + propertyName.charAt(propertyName.length-1) !== "$"
36 + ) {
37 + this[propertyName + "$"] = Parent.prototype[propertyName];
38 + }
39 + }
40 + }
41 + T.prototype = Parent.prototype;
42 + Child.prototype = new T();
43 + return Child.prototype;
44 +};
45 +
46 +
47 +function isPrimitive(val) {
48 + return val == null || val === true || val === false ||
49 + typeof val === "string" || typeof val === "number";
50 +
51 +}
52 +
53 +function isObject(value) {
54 + return typeof value === "function" ||
55 + typeof value === "object" && value !== null;
56 +}
57 +
58 +function maybeWrapAsError(maybeError) {
59 + if (!isPrimitive(maybeError)) return maybeError;
60 +
61 + return new Error(safeToString(maybeError));
62 +}
63 +
64 +function withAppended(target, appendee) {
65 + var len = target.length;
66 + var ret = new Array(len + 1);
67 + var i;
68 + for (i = 0; i < len; ++i) {
69 + ret[i] = target[i];
70 + }
71 + ret[i] = appendee;
72 + return ret;
73 +}
74 +
75 +function getDataPropertyOrDefault(obj, key, defaultValue) {
76 + if (es5.isES5) {
77 + var desc = Object.getOwnPropertyDescriptor(obj, key);
78 +
79 + if (desc != null) {
80 + return desc.get == null && desc.set == null
81 + ? desc.value
82 + : defaultValue;
83 + }
84 + } else {
85 + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
86 + }
87 +}
88 +
89 +function notEnumerableProp(obj, name, value) {
90 + if (isPrimitive(obj)) return obj;
91 + var descriptor = {
92 + value: value,
93 + configurable: true,
94 + enumerable: false,
95 + writable: true
96 + };
97 + es5.defineProperty(obj, name, descriptor);
98 + return obj;
99 +}
100 +
101 +function thrower(r) {
102 + throw r;
103 +}
104 +
105 +var inheritedDataKeys = (function() {
106 + var excludedPrototypes = [
107 + Array.prototype,
108 + Object.prototype,
109 + Function.prototype
110 + ];
111 +
112 + var isExcludedProto = function(val) {
113 + for (var i = 0; i < excludedPrototypes.length; ++i) {
114 + if (excludedPrototypes[i] === val) {
115 + return true;
116 + }
117 + }
118 + return false;
119 + };
120 +
121 + if (es5.isES5) {
122 + var getKeys = Object.getOwnPropertyNames;
123 + return function(obj) {
124 + var ret = [];
125 + var visitedKeys = Object.create(null);
126 + while (obj != null && !isExcludedProto(obj)) {
127 + var keys;
128 + try {
129 + keys = getKeys(obj);
130 + } catch (e) {
131 + return ret;
132 + }
133 + for (var i = 0; i < keys.length; ++i) {
134 + var key = keys[i];
135 + if (visitedKeys[key]) continue;
136 + visitedKeys[key] = true;
137 + var desc = Object.getOwnPropertyDescriptor(obj, key);
138 + if (desc != null && desc.get == null && desc.set == null) {
139 + ret.push(key);
140 + }
141 + }
142 + obj = es5.getPrototypeOf(obj);
143 + }
144 + return ret;
145 + };
146 + } else {
147 + var hasProp = {}.hasOwnProperty;
148 + return function(obj) {
149 + if (isExcludedProto(obj)) return [];
150 + var ret = [];
151 +
152 + /*jshint forin:false */
153 + enumeration: for (var key in obj) {
154 + if (hasProp.call(obj, key)) {
155 + ret.push(key);
156 + } else {
157 + for (var i = 0; i < excludedPrototypes.length; ++i) {
158 + if (hasProp.call(excludedPrototypes[i], key)) {
159 + continue enumeration;
160 + }
161 + }
162 + ret.push(key);
163 + }
164 + }
165 + return ret;
166 + };
167 + }
168 +
169 +})();
170 +
171 +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
172 +function isClass(fn) {
173 + try {
174 + if (typeof fn === "function") {
175 + var keys = es5.names(fn.prototype);
176 +
177 + var hasMethods = es5.isES5 && keys.length > 1;
178 + var hasMethodsOtherThanConstructor = keys.length > 0 &&
179 + !(keys.length === 1 && keys[0] === "constructor");
180 + var hasThisAssignmentAndStaticMethods =
181 + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
182 +
183 + if (hasMethods || hasMethodsOtherThanConstructor ||
184 + hasThisAssignmentAndStaticMethods) {
185 + return true;
186 + }
187 + }
188 + return false;
189 + } catch (e) {
190 + return false;
191 + }
192 +}
193 +
194 +function toFastProperties(obj) {
195 + /*jshint -W027,-W055,-W031*/
196 + function FakeConstructor() {}
197 + FakeConstructor.prototype = obj;
198 + var receiver = new FakeConstructor();
199 + function ic() {
200 + return typeof receiver.foo;
201 + }
202 + ic();
203 + ic();
204 + return obj;
205 + eval(obj);
206 +}
207 +
208 +var rident = /^[a-z$_][a-z$_0-9]*$/i;
209 +function isIdentifier(str) {
210 + return rident.test(str);
211 +}
212 +
213 +function filledRange(count, prefix, suffix) {
214 + var ret = new Array(count);
215 + for(var i = 0; i < count; ++i) {
216 + ret[i] = prefix + i + suffix;
217 + }
218 + return ret;
219 +}
220 +
221 +function safeToString(obj) {
222 + try {
223 + return obj + "";
224 + } catch (e) {
225 + return "[no string representation]";
226 + }
227 +}
228 +
229 +function isError(obj) {
230 + return obj instanceof Error ||
231 + (obj !== null &&
232 + typeof obj === "object" &&
233 + typeof obj.message === "string" &&
234 + typeof obj.name === "string");
235 +}
236 +
237 +function markAsOriginatingFromRejection(e) {
238 + try {
239 + notEnumerableProp(e, "isOperational", true);
240 + }
241 + catch(ignore) {}
242 +}
243 +
244 +function originatesFromRejection(e) {
245 + if (e == null) return false;
246 + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
247 + e["isOperational"] === true);
248 +}
249 +
250 +function canAttachTrace(obj) {
251 + return isError(obj) && es5.propertyIsWritable(obj, "stack");
252 +}
253 +
254 +var ensureErrorObject = (function() {
255 + if (!("stack" in new Error())) {
256 + return function(value) {
257 + if (canAttachTrace(value)) return value;
258 + try {throw new Error(safeToString(value));}
259 + catch(err) {return err;}
260 + };
261 + } else {
262 + return function(value) {
263 + if (canAttachTrace(value)) return value;
264 + return new Error(safeToString(value));
265 + };
266 + }
267 +})();
268 +
269 +function classString(obj) {
270 + return {}.toString.call(obj);
271 +}
272 +
273 +function copyDescriptors(from, to, filter) {
274 + var keys = es5.names(from);
275 + for (var i = 0; i < keys.length; ++i) {
276 + var key = keys[i];
277 + if (filter(key)) {
278 + try {
279 + es5.defineProperty(to, key, es5.getDescriptor(from, key));
280 + } catch (ignore) {}
281 + }
282 + }
283 +}
284 +
285 +var asArray = function(v) {
286 + if (es5.isArray(v)) {
287 + return v;
288 + }
289 + return null;
290 +};
291 +
292 +if (typeof Symbol !== "undefined" && Symbol.iterator) {
293 + var ArrayFrom = typeof Array.from === "function" ? function(v) {
294 + return Array.from(v);
295 + } : function(v) {
296 + var ret = [];
297 + var it = v[Symbol.iterator]();
298 + var itResult;
299 + while (!((itResult = it.next()).done)) {
300 + ret.push(itResult.value);
301 + }
302 + return ret;
303 + };
304 +
305 + asArray = function(v) {
306 + if (es5.isArray(v)) {
307 + return v;
308 + } else if (v != null && typeof v[Symbol.iterator] === "function") {
309 + return ArrayFrom(v);
310 + }
311 + return null;
312 + };
313 +}
314 +
315 +var isNode = typeof process !== "undefined" &&
316 + classString(process).toLowerCase() === "[object process]";
317 +
318 +var hasEnvVariables = typeof process !== "undefined" &&
319 + typeof process.env !== "undefined";
320 +
321 +function env(key) {
322 + return hasEnvVariables ? process.env[key] : undefined;
323 +}
324 +
325 +function getNativePromise() {
326 + if (typeof Promise === "function") {
327 + try {
328 + var promise = new Promise(function(){});
329 + if ({}.toString.call(promise) === "[object Promise]") {
330 + return Promise;
331 + }
332 + } catch (e) {}
333 + }
334 +}
335 +
336 +function domainBind(self, cb) {
337 + return self.bind(cb);
338 +}
339 +
340 +var ret = {
341 + isClass: isClass,
342 + isIdentifier: isIdentifier,
343 + inheritedDataKeys: inheritedDataKeys,
344 + getDataPropertyOrDefault: getDataPropertyOrDefault,
345 + thrower: thrower,
346 + isArray: es5.isArray,
347 + asArray: asArray,
348 + notEnumerableProp: notEnumerableProp,
349 + isPrimitive: isPrimitive,
350 + isObject: isObject,
351 + isError: isError,
352 + canEvaluate: canEvaluate,
353 + errorObj: errorObj,
354 + tryCatch: tryCatch,
355 + inherits: inherits,
356 + withAppended: withAppended,
357 + maybeWrapAsError: maybeWrapAsError,
358 + toFastProperties: toFastProperties,
359 + filledRange: filledRange,
360 + toString: safeToString,
361 + canAttachTrace: canAttachTrace,
362 + ensureErrorObject: ensureErrorObject,
363 + originatesFromRejection: originatesFromRejection,
364 + markAsOriginatingFromRejection: markAsOriginatingFromRejection,
365 + classString: classString,
366 + copyDescriptors: copyDescriptors,
367 + hasDevTools: typeof chrome !== "undefined" && chrome &&
368 + typeof chrome.loadTimes === "function",
369 + isNode: isNode,
370 + hasEnvVariables: hasEnvVariables,
371 + env: env,
372 + global: globalObject,
373 + getNativePromise: getNativePromise,
374 + domainBind: domainBind
375 +};
376 +ret.isRecentNode = ret.isNode && (function() {
377 + var version = process.versions.node.split(".").map(Number);
378 + return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
379 +})();
380 +
381 +if (ret.isNode) ret.toFastProperties(process);
382 +
383 +try {throw new Error(); } catch (e) {ret.lastLineError = e;}
384 +module.exports = ret;
1 +{
2 + "_from": "bluebird@^3.5.0",
3 + "_id": "bluebird@3.5.3",
4 + "_inBundle": false,
5 + "_integrity": "sha512-/qKPUQlaW1OyR51WeCPBvRnAlnZFUJkCSG5HzGnuIqhgyJtF+T94lFnn33eiazjRm2LAHVy2guNnaq48X9SJuw==",
6 + "_location": "/bluebird",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "bluebird@^3.5.0",
12 + "name": "bluebird",
13 + "escapedName": "bluebird",
14 + "rawSpec": "^3.5.0",
15 + "saveSpec": null,
16 + "fetchSpec": "^3.5.0"
17 + },
18 + "_requiredBy": [
19 + "/promise-mysql"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.3.tgz",
22 + "_shasum": "7d01c6f9616c9a51ab0f8c549a79dfe6ec33efa7",
23 + "_spec": "bluebird@^3.5.0",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/promise-mysql",
25 + "author": {
26 + "name": "Petka Antonov",
27 + "email": "petka_antonov@hotmail.com",
28 + "url": "http://github.com/petkaantonov/"
29 + },
30 + "browser": "./js/browser/bluebird.js",
31 + "bugs": {
32 + "url": "http://github.com/petkaantonov/bluebird/issues"
33 + },
34 + "bundleDependencies": false,
35 + "deprecated": false,
36 + "description": "Full featured Promises/A+ implementation with exceptionally good performance",
37 + "devDependencies": {
38 + "acorn": "^6.0.2",
39 + "acorn-walk": "^6.1.0",
40 + "baconjs": "^0.7.43",
41 + "bluebird": "^2.9.2",
42 + "body-parser": "^1.10.2",
43 + "browserify": "^8.1.1",
44 + "cli-table": "~0.3.1",
45 + "co": "^4.2.0",
46 + "cross-spawn": "^0.2.3",
47 + "glob": "^4.3.2",
48 + "grunt-saucelabs": "~8.4.1",
49 + "highland": "^2.3.0",
50 + "istanbul": "^0.3.5",
51 + "jshint": "^2.6.0",
52 + "jshint-stylish": "~0.2.0",
53 + "kefir": "^2.4.1",
54 + "mkdirp": "~0.5.0",
55 + "mocha": "~2.1",
56 + "open": "~0.0.5",
57 + "optimist": "~0.6.1",
58 + "rimraf": "~2.2.6",
59 + "rx": "^2.3.25",
60 + "serve-static": "^1.7.1",
61 + "sinon": "~1.7.3",
62 + "uglify-js": "~2.4.16"
63 + },
64 + "files": [
65 + "js/browser",
66 + "js/release",
67 + "LICENSE"
68 + ],
69 + "homepage": "https://github.com/petkaantonov/bluebird",
70 + "keywords": [
71 + "promise",
72 + "performance",
73 + "promises",
74 + "promises-a",
75 + "promises-aplus",
76 + "async",
77 + "await",
78 + "deferred",
79 + "deferreds",
80 + "future",
81 + "flow control",
82 + "dsl",
83 + "fluent interface"
84 + ],
85 + "license": "MIT",
86 + "main": "./js/release/bluebird.js",
87 + "name": "bluebird",
88 + "repository": {
89 + "type": "git",
90 + "url": "git://github.com/petkaantonov/bluebird.git"
91 + },
92 + "scripts": {
93 + "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",
94 + "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify",
95 + "istanbul": "istanbul",
96 + "lint": "node scripts/jshint.js",
97 + "prepublish": "npm run generate-browser-core && npm run generate-browser-full",
98 + "test": "node --expose-gc tools/test.js"
99 + },
100 + "version": "3.5.3",
101 + "webpack": "./js/release/bluebird.js"
102 +}
1 +Copyright Node.js contributors. All rights reserved.
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to
5 +deal in the Software without restriction, including without limitation the
6 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 +sell copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in
11 +all copies or substantial portions of the Software.
12 +
13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19 +IN THE SOFTWARE.
1 +# core-util-is
2 +
3 +The `util.is*` functions introduced in Node v0.12.
1 +diff --git a/lib/util.js b/lib/util.js
2 +index a03e874..9074e8e 100644
3 +--- a/lib/util.js
4 ++++ b/lib/util.js
5 +@@ -19,430 +19,6 @@
6 + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7 + // USE OR OTHER DEALINGS IN THE SOFTWARE.
8 +
9 +-var formatRegExp = /%[sdj%]/g;
10 +-exports.format = function(f) {
11 +- if (!isString(f)) {
12 +- var objects = [];
13 +- for (var i = 0; i < arguments.length; i++) {
14 +- objects.push(inspect(arguments[i]));
15 +- }
16 +- return objects.join(' ');
17 +- }
18 +-
19 +- var i = 1;
20 +- var args = arguments;
21 +- var len = args.length;
22 +- var str = String(f).replace(formatRegExp, function(x) {
23 +- if (x === '%%') return '%';
24 +- if (i >= len) return x;
25 +- switch (x) {
26 +- case '%s': return String(args[i++]);
27 +- case '%d': return Number(args[i++]);
28 +- case '%j':
29 +- try {
30 +- return JSON.stringify(args[i++]);
31 +- } catch (_) {
32 +- return '[Circular]';
33 +- }
34 +- default:
35 +- return x;
36 +- }
37 +- });
38 +- for (var x = args[i]; i < len; x = args[++i]) {
39 +- if (isNull(x) || !isObject(x)) {
40 +- str += ' ' + x;
41 +- } else {
42 +- str += ' ' + inspect(x);
43 +- }
44 +- }
45 +- return str;
46 +-};
47 +-
48 +-
49 +-// Mark that a method should not be used.
50 +-// Returns a modified function which warns once by default.
51 +-// If --no-deprecation is set, then it is a no-op.
52 +-exports.deprecate = function(fn, msg) {
53 +- // Allow for deprecating things in the process of starting up.
54 +- if (isUndefined(global.process)) {
55 +- return function() {
56 +- return exports.deprecate(fn, msg).apply(this, arguments);
57 +- };
58 +- }
59 +-
60 +- if (process.noDeprecation === true) {
61 +- return fn;
62 +- }
63 +-
64 +- var warned = false;
65 +- function deprecated() {
66 +- if (!warned) {
67 +- if (process.throwDeprecation) {
68 +- throw new Error(msg);
69 +- } else if (process.traceDeprecation) {
70 +- console.trace(msg);
71 +- } else {
72 +- console.error(msg);
73 +- }
74 +- warned = true;
75 +- }
76 +- return fn.apply(this, arguments);
77 +- }
78 +-
79 +- return deprecated;
80 +-};
81 +-
82 +-
83 +-var debugs = {};
84 +-var debugEnviron;
85 +-exports.debuglog = function(set) {
86 +- if (isUndefined(debugEnviron))
87 +- debugEnviron = process.env.NODE_DEBUG || '';
88 +- set = set.toUpperCase();
89 +- if (!debugs[set]) {
90 +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
91 +- var pid = process.pid;
92 +- debugs[set] = function() {
93 +- var msg = exports.format.apply(exports, arguments);
94 +- console.error('%s %d: %s', set, pid, msg);
95 +- };
96 +- } else {
97 +- debugs[set] = function() {};
98 +- }
99 +- }
100 +- return debugs[set];
101 +-};
102 +-
103 +-
104 +-/**
105 +- * Echos the value of a value. Trys to print the value out
106 +- * in the best way possible given the different types.
107 +- *
108 +- * @param {Object} obj The object to print out.
109 +- * @param {Object} opts Optional options object that alters the output.
110 +- */
111 +-/* legacy: obj, showHidden, depth, colors*/
112 +-function inspect(obj, opts) {
113 +- // default options
114 +- var ctx = {
115 +- seen: [],
116 +- stylize: stylizeNoColor
117 +- };
118 +- // legacy...
119 +- if (arguments.length >= 3) ctx.depth = arguments[2];
120 +- if (arguments.length >= 4) ctx.colors = arguments[3];
121 +- if (isBoolean(opts)) {
122 +- // legacy...
123 +- ctx.showHidden = opts;
124 +- } else if (opts) {
125 +- // got an "options" object
126 +- exports._extend(ctx, opts);
127 +- }
128 +- // set default options
129 +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
130 +- if (isUndefined(ctx.depth)) ctx.depth = 2;
131 +- if (isUndefined(ctx.colors)) ctx.colors = false;
132 +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
133 +- if (ctx.colors) ctx.stylize = stylizeWithColor;
134 +- return formatValue(ctx, obj, ctx.depth);
135 +-}
136 +-exports.inspect = inspect;
137 +-
138 +-
139 +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
140 +-inspect.colors = {
141 +- 'bold' : [1, 22],
142 +- 'italic' : [3, 23],
143 +- 'underline' : [4, 24],
144 +- 'inverse' : [7, 27],
145 +- 'white' : [37, 39],
146 +- 'grey' : [90, 39],
147 +- 'black' : [30, 39],
148 +- 'blue' : [34, 39],
149 +- 'cyan' : [36, 39],
150 +- 'green' : [32, 39],
151 +- 'magenta' : [35, 39],
152 +- 'red' : [31, 39],
153 +- 'yellow' : [33, 39]
154 +-};
155 +-
156 +-// Don't use 'blue' not visible on cmd.exe
157 +-inspect.styles = {
158 +- 'special': 'cyan',
159 +- 'number': 'yellow',
160 +- 'boolean': 'yellow',
161 +- 'undefined': 'grey',
162 +- 'null': 'bold',
163 +- 'string': 'green',
164 +- 'date': 'magenta',
165 +- // "name": intentionally not styling
166 +- 'regexp': 'red'
167 +-};
168 +-
169 +-
170 +-function stylizeWithColor(str, styleType) {
171 +- var style = inspect.styles[styleType];
172 +-
173 +- if (style) {
174 +- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
175 +- '\u001b[' + inspect.colors[style][1] + 'm';
176 +- } else {
177 +- return str;
178 +- }
179 +-}
180 +-
181 +-
182 +-function stylizeNoColor(str, styleType) {
183 +- return str;
184 +-}
185 +-
186 +-
187 +-function arrayToHash(array) {
188 +- var hash = {};
189 +-
190 +- array.forEach(function(val, idx) {
191 +- hash[val] = true;
192 +- });
193 +-
194 +- return hash;
195 +-}
196 +-
197 +-
198 +-function formatValue(ctx, value, recurseTimes) {
199 +- // Provide a hook for user-specified inspect functions.
200 +- // Check that value is an object with an inspect function on it
201 +- if (ctx.customInspect &&
202 +- value &&
203 +- isFunction(value.inspect) &&
204 +- // Filter out the util module, it's inspect function is special
205 +- value.inspect !== exports.inspect &&
206 +- // Also filter out any prototype objects using the circular check.
207 +- !(value.constructor && value.constructor.prototype === value)) {
208 +- var ret = value.inspect(recurseTimes, ctx);
209 +- if (!isString(ret)) {
210 +- ret = formatValue(ctx, ret, recurseTimes);
211 +- }
212 +- return ret;
213 +- }
214 +-
215 +- // Primitive types cannot have properties
216 +- var primitive = formatPrimitive(ctx, value);
217 +- if (primitive) {
218 +- return primitive;
219 +- }
220 +-
221 +- // Look up the keys of the object.
222 +- var keys = Object.keys(value);
223 +- var visibleKeys = arrayToHash(keys);
224 +-
225 +- if (ctx.showHidden) {
226 +- keys = Object.getOwnPropertyNames(value);
227 +- }
228 +-
229 +- // Some type of object without properties can be shortcutted.
230 +- if (keys.length === 0) {
231 +- if (isFunction(value)) {
232 +- var name = value.name ? ': ' + value.name : '';
233 +- return ctx.stylize('[Function' + name + ']', 'special');
234 +- }
235 +- if (isRegExp(value)) {
236 +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
237 +- }
238 +- if (isDate(value)) {
239 +- return ctx.stylize(Date.prototype.toString.call(value), 'date');
240 +- }
241 +- if (isError(value)) {
242 +- return formatError(value);
243 +- }
244 +- }
245 +-
246 +- var base = '', array = false, braces = ['{', '}'];
247 +-
248 +- // Make Array say that they are Array
249 +- if (isArray(value)) {
250 +- array = true;
251 +- braces = ['[', ']'];
252 +- }
253 +-
254 +- // Make functions say that they are functions
255 +- if (isFunction(value)) {
256 +- var n = value.name ? ': ' + value.name : '';
257 +- base = ' [Function' + n + ']';
258 +- }
259 +-
260 +- // Make RegExps say that they are RegExps
261 +- if (isRegExp(value)) {
262 +- base = ' ' + RegExp.prototype.toString.call(value);
263 +- }
264 +-
265 +- // Make dates with properties first say the date
266 +- if (isDate(value)) {
267 +- base = ' ' + Date.prototype.toUTCString.call(value);
268 +- }
269 +-
270 +- // Make error with message first say the error
271 +- if (isError(value)) {
272 +- base = ' ' + formatError(value);
273 +- }
274 +-
275 +- if (keys.length === 0 && (!array || value.length == 0)) {
276 +- return braces[0] + base + braces[1];
277 +- }
278 +-
279 +- if (recurseTimes < 0) {
280 +- if (isRegExp(value)) {
281 +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
282 +- } else {
283 +- return ctx.stylize('[Object]', 'special');
284 +- }
285 +- }
286 +-
287 +- ctx.seen.push(value);
288 +-
289 +- var output;
290 +- if (array) {
291 +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
292 +- } else {
293 +- output = keys.map(function(key) {
294 +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
295 +- });
296 +- }
297 +-
298 +- ctx.seen.pop();
299 +-
300 +- return reduceToSingleString(output, base, braces);
301 +-}
302 +-
303 +-
304 +-function formatPrimitive(ctx, value) {
305 +- if (isUndefined(value))
306 +- return ctx.stylize('undefined', 'undefined');
307 +- if (isString(value)) {
308 +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
309 +- .replace(/'/g, "\\'")
310 +- .replace(/\\"/g, '"') + '\'';
311 +- return ctx.stylize(simple, 'string');
312 +- }
313 +- if (isNumber(value)) {
314 +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
315 +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
316 +- if (value === 0 && 1 / value < 0)
317 +- return ctx.stylize('-0', 'number');
318 +- return ctx.stylize('' + value, 'number');
319 +- }
320 +- if (isBoolean(value))
321 +- return ctx.stylize('' + value, 'boolean');
322 +- // For some reason typeof null is "object", so special case here.
323 +- if (isNull(value))
324 +- return ctx.stylize('null', 'null');
325 +-}
326 +-
327 +-
328 +-function formatError(value) {
329 +- return '[' + Error.prototype.toString.call(value) + ']';
330 +-}
331 +-
332 +-
333 +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
334 +- var output = [];
335 +- for (var i = 0, l = value.length; i < l; ++i) {
336 +- if (hasOwnProperty(value, String(i))) {
337 +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
338 +- String(i), true));
339 +- } else {
340 +- output.push('');
341 +- }
342 +- }
343 +- keys.forEach(function(key) {
344 +- if (!key.match(/^\d+$/)) {
345 +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
346 +- key, true));
347 +- }
348 +- });
349 +- return output;
350 +-}
351 +-
352 +-
353 +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
354 +- var name, str, desc;
355 +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
356 +- if (desc.get) {
357 +- if (desc.set) {
358 +- str = ctx.stylize('[Getter/Setter]', 'special');
359 +- } else {
360 +- str = ctx.stylize('[Getter]', 'special');
361 +- }
362 +- } else {
363 +- if (desc.set) {
364 +- str = ctx.stylize('[Setter]', 'special');
365 +- }
366 +- }
367 +- if (!hasOwnProperty(visibleKeys, key)) {
368 +- name = '[' + key + ']';
369 +- }
370 +- if (!str) {
371 +- if (ctx.seen.indexOf(desc.value) < 0) {
372 +- if (isNull(recurseTimes)) {
373 +- str = formatValue(ctx, desc.value, null);
374 +- } else {
375 +- str = formatValue(ctx, desc.value, recurseTimes - 1);
376 +- }
377 +- if (str.indexOf('\n') > -1) {
378 +- if (array) {
379 +- str = str.split('\n').map(function(line) {
380 +- return ' ' + line;
381 +- }).join('\n').substr(2);
382 +- } else {
383 +- str = '\n' + str.split('\n').map(function(line) {
384 +- return ' ' + line;
385 +- }).join('\n');
386 +- }
387 +- }
388 +- } else {
389 +- str = ctx.stylize('[Circular]', 'special');
390 +- }
391 +- }
392 +- if (isUndefined(name)) {
393 +- if (array && key.match(/^\d+$/)) {
394 +- return str;
395 +- }
396 +- name = JSON.stringify('' + key);
397 +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
398 +- name = name.substr(1, name.length - 2);
399 +- name = ctx.stylize(name, 'name');
400 +- } else {
401 +- name = name.replace(/'/g, "\\'")
402 +- .replace(/\\"/g, '"')
403 +- .replace(/(^"|"$)/g, "'");
404 +- name = ctx.stylize(name, 'string');
405 +- }
406 +- }
407 +-
408 +- return name + ': ' + str;
409 +-}
410 +-
411 +-
412 +-function reduceToSingleString(output, base, braces) {
413 +- var numLinesEst = 0;
414 +- var length = output.reduce(function(prev, cur) {
415 +- numLinesEst++;
416 +- if (cur.indexOf('\n') >= 0) numLinesEst++;
417 +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
418 +- }, 0);
419 +-
420 +- if (length > 60) {
421 +- return braces[0] +
422 +- (base === '' ? '' : base + '\n ') +
423 +- ' ' +
424 +- output.join(',\n ') +
425 +- ' ' +
426 +- braces[1];
427 +- }
428 +-
429 +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
430 +-}
431 +-
432 +-
433 + // NOTE: These type checking functions intentionally don't use `instanceof`
434 + // because it is fragile and can be easily faked with `Object.create()`.
435 + function isArray(ar) {
436 +@@ -522,166 +98,10 @@ function isPrimitive(arg) {
437 + exports.isPrimitive = isPrimitive;
438 +
439 + function isBuffer(arg) {
440 +- return arg instanceof Buffer;
441 ++ return Buffer.isBuffer(arg);
442 + }
443 + exports.isBuffer = isBuffer;
444 +
445 + function objectToString(o) {
446 + return Object.prototype.toString.call(o);
447 +-}
448 +-
449 +-
450 +-function pad(n) {
451 +- return n < 10 ? '0' + n.toString(10) : n.toString(10);
452 +-}
453 +-
454 +-
455 +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
456 +- 'Oct', 'Nov', 'Dec'];
457 +-
458 +-// 26 Feb 16:19:34
459 +-function timestamp() {
460 +- var d = new Date();
461 +- var time = [pad(d.getHours()),
462 +- pad(d.getMinutes()),
463 +- pad(d.getSeconds())].join(':');
464 +- return [d.getDate(), months[d.getMonth()], time].join(' ');
465 +-}
466 +-
467 +-
468 +-// log is just a thin wrapper to console.log that prepends a timestamp
469 +-exports.log = function() {
470 +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
471 +-};
472 +-
473 +-
474 +-/**
475 +- * Inherit the prototype methods from one constructor into another.
476 +- *
477 +- * The Function.prototype.inherits from lang.js rewritten as a standalone
478 +- * function (not on Function.prototype). NOTE: If this file is to be loaded
479 +- * during bootstrapping this function needs to be rewritten using some native
480 +- * functions as prototype setup using normal JavaScript does not work as
481 +- * expected during bootstrapping (see mirror.js in r114903).
482 +- *
483 +- * @param {function} ctor Constructor function which needs to inherit the
484 +- * prototype.
485 +- * @param {function} superCtor Constructor function to inherit prototype from.
486 +- */
487 +-exports.inherits = function(ctor, superCtor) {
488 +- ctor.super_ = superCtor;
489 +- ctor.prototype = Object.create(superCtor.prototype, {
490 +- constructor: {
491 +- value: ctor,
492 +- enumerable: false,
493 +- writable: true,
494 +- configurable: true
495 +- }
496 +- });
497 +-};
498 +-
499 +-exports._extend = function(origin, add) {
500 +- // Don't do anything if add isn't an object
501 +- if (!add || !isObject(add)) return origin;
502 +-
503 +- var keys = Object.keys(add);
504 +- var i = keys.length;
505 +- while (i--) {
506 +- origin[keys[i]] = add[keys[i]];
507 +- }
508 +- return origin;
509 +-};
510 +-
511 +-function hasOwnProperty(obj, prop) {
512 +- return Object.prototype.hasOwnProperty.call(obj, prop);
513 +-}
514 +-
515 +-
516 +-// Deprecated old stuff.
517 +-
518 +-exports.p = exports.deprecate(function() {
519 +- for (var i = 0, len = arguments.length; i < len; ++i) {
520 +- console.error(exports.inspect(arguments[i]));
521 +- }
522 +-}, 'util.p: Use console.error() instead');
523 +-
524 +-
525 +-exports.exec = exports.deprecate(function() {
526 +- return require('child_process').exec.apply(this, arguments);
527 +-}, 'util.exec is now called `child_process.exec`.');
528 +-
529 +-
530 +-exports.print = exports.deprecate(function() {
531 +- for (var i = 0, len = arguments.length; i < len; ++i) {
532 +- process.stdout.write(String(arguments[i]));
533 +- }
534 +-}, 'util.print: Use console.log instead');
535 +-
536 +-
537 +-exports.puts = exports.deprecate(function() {
538 +- for (var i = 0, len = arguments.length; i < len; ++i) {
539 +- process.stdout.write(arguments[i] + '\n');
540 +- }
541 +-}, 'util.puts: Use console.log instead');
542 +-
543 +-
544 +-exports.debug = exports.deprecate(function(x) {
545 +- process.stderr.write('DEBUG: ' + x + '\n');
546 +-}, 'util.debug: Use console.error instead');
547 +-
548 +-
549 +-exports.error = exports.deprecate(function(x) {
550 +- for (var i = 0, len = arguments.length; i < len; ++i) {
551 +- process.stderr.write(arguments[i] + '\n');
552 +- }
553 +-}, 'util.error: Use console.error instead');
554 +-
555 +-
556 +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
557 +- var callbackCalled = false;
558 +-
559 +- function call(a, b, c) {
560 +- if (callback && !callbackCalled) {
561 +- callback(a, b, c);
562 +- callbackCalled = true;
563 +- }
564 +- }
565 +-
566 +- readStream.addListener('data', function(chunk) {
567 +- if (writeStream.write(chunk) === false) readStream.pause();
568 +- });
569 +-
570 +- writeStream.addListener('drain', function() {
571 +- readStream.resume();
572 +- });
573 +-
574 +- readStream.addListener('end', function() {
575 +- writeStream.end();
576 +- });
577 +-
578 +- readStream.addListener('close', function() {
579 +- call();
580 +- });
581 +-
582 +- readStream.addListener('error', function(err) {
583 +- writeStream.end();
584 +- call(err);
585 +- });
586 +-
587 +- writeStream.addListener('error', function(err) {
588 +- readStream.destroy();
589 +- call(err);
590 +- });
591 +-}, 'util.pump(): Use readableStream.pipe() instead');
592 +-
593 +-
594 +-var uv;
595 +-exports._errnoException = function(err, syscall) {
596 +- if (isUndefined(uv)) uv = process.binding('uv');
597 +- var errname = uv.errname(err);
598 +- var e = new Error(syscall + ' ' + errname);
599 +- e.code = errname;
600 +- e.errno = errname;
601 +- e.syscall = syscall;
602 +- return e;
603 +-};
604 ++}
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// NOTE: These type checking functions intentionally don't use `instanceof`
23 +// because it is fragile and can be easily faked with `Object.create()`.
24 +
25 +function isArray(arg) {
26 + if (Array.isArray) {
27 + return Array.isArray(arg);
28 + }
29 + return objectToString(arg) === '[object Array]';
30 +}
31 +exports.isArray = isArray;
32 +
33 +function isBoolean(arg) {
34 + return typeof arg === 'boolean';
35 +}
36 +exports.isBoolean = isBoolean;
37 +
38 +function isNull(arg) {
39 + return arg === null;
40 +}
41 +exports.isNull = isNull;
42 +
43 +function isNullOrUndefined(arg) {
44 + return arg == null;
45 +}
46 +exports.isNullOrUndefined = isNullOrUndefined;
47 +
48 +function isNumber(arg) {
49 + return typeof arg === 'number';
50 +}
51 +exports.isNumber = isNumber;
52 +
53 +function isString(arg) {
54 + return typeof arg === 'string';
55 +}
56 +exports.isString = isString;
57 +
58 +function isSymbol(arg) {
59 + return typeof arg === 'symbol';
60 +}
61 +exports.isSymbol = isSymbol;
62 +
63 +function isUndefined(arg) {
64 + return arg === void 0;
65 +}
66 +exports.isUndefined = isUndefined;
67 +
68 +function isRegExp(re) {
69 + return objectToString(re) === '[object RegExp]';
70 +}
71 +exports.isRegExp = isRegExp;
72 +
73 +function isObject(arg) {
74 + return typeof arg === 'object' && arg !== null;
75 +}
76 +exports.isObject = isObject;
77 +
78 +function isDate(d) {
79 + return objectToString(d) === '[object Date]';
80 +}
81 +exports.isDate = isDate;
82 +
83 +function isError(e) {
84 + return (objectToString(e) === '[object Error]' || e instanceof Error);
85 +}
86 +exports.isError = isError;
87 +
88 +function isFunction(arg) {
89 + return typeof arg === 'function';
90 +}
91 +exports.isFunction = isFunction;
92 +
93 +function isPrimitive(arg) {
94 + return arg === null ||
95 + typeof arg === 'boolean' ||
96 + typeof arg === 'number' ||
97 + typeof arg === 'string' ||
98 + typeof arg === 'symbol' || // ES6 symbol
99 + typeof arg === 'undefined';
100 +}
101 +exports.isPrimitive = isPrimitive;
102 +
103 +exports.isBuffer = Buffer.isBuffer;
104 +
105 +function objectToString(o) {
106 + return Object.prototype.toString.call(o);
107 +}
1 +{
2 + "_from": "core-util-is@~1.0.0",
3 + "_id": "core-util-is@1.0.2",
4 + "_inBundle": false,
5 + "_integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=",
6 + "_location": "/core-util-is",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "core-util-is@~1.0.0",
12 + "name": "core-util-is",
13 + "escapedName": "core-util-is",
14 + "rawSpec": "~1.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "~1.0.0"
17 + },
18 + "_requiredBy": [
19 + "/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
22 + "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7",
23 + "_spec": "core-util-is@~1.0.0",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/readable-stream",
25 + "author": {
26 + "name": "Isaac Z. Schlueter",
27 + "email": "i@izs.me",
28 + "url": "http://blog.izs.me/"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/isaacs/core-util-is/issues"
32 + },
33 + "bundleDependencies": false,
34 + "deprecated": false,
35 + "description": "The `util.is*` functions introduced in Node v0.12.",
36 + "devDependencies": {
37 + "tap": "^2.3.0"
38 + },
39 + "homepage": "https://github.com/isaacs/core-util-is#readme",
40 + "keywords": [
41 + "util",
42 + "isBuffer",
43 + "isArray",
44 + "isNumber",
45 + "isString",
46 + "isRegExp",
47 + "isThis",
48 + "isThat",
49 + "polyfill"
50 + ],
51 + "license": "MIT",
52 + "main": "lib/util.js",
53 + "name": "core-util-is",
54 + "repository": {
55 + "type": "git",
56 + "url": "git://github.com/isaacs/core-util-is.git"
57 + },
58 + "scripts": {
59 + "test": "tap test.js"
60 + },
61 + "version": "1.0.2"
62 +}
1 +var assert = require('tap');
2 +
3 +var t = require('./lib/util');
4 +
5 +assert.equal(t.isArray([]), true);
6 +assert.equal(t.isArray({}), false);
7 +
8 +assert.equal(t.isBoolean(null), false);
9 +assert.equal(t.isBoolean(true), true);
10 +assert.equal(t.isBoolean(false), true);
11 +
12 +assert.equal(t.isNull(null), true);
13 +assert.equal(t.isNull(undefined), false);
14 +assert.equal(t.isNull(false), false);
15 +assert.equal(t.isNull(), false);
16 +
17 +assert.equal(t.isNullOrUndefined(null), true);
18 +assert.equal(t.isNullOrUndefined(undefined), true);
19 +assert.equal(t.isNullOrUndefined(false), false);
20 +assert.equal(t.isNullOrUndefined(), true);
21 +
22 +assert.equal(t.isNumber(null), false);
23 +assert.equal(t.isNumber('1'), false);
24 +assert.equal(t.isNumber(1), true);
25 +
26 +assert.equal(t.isString(null), false);
27 +assert.equal(t.isString('1'), true);
28 +assert.equal(t.isString(1), false);
29 +
30 +assert.equal(t.isSymbol(null), false);
31 +assert.equal(t.isSymbol('1'), false);
32 +assert.equal(t.isSymbol(1), false);
33 +assert.equal(t.isSymbol(Symbol()), true);
34 +
35 +assert.equal(t.isUndefined(null), false);
36 +assert.equal(t.isUndefined(undefined), true);
37 +assert.equal(t.isUndefined(false), false);
38 +assert.equal(t.isUndefined(), true);
39 +
40 +assert.equal(t.isRegExp(null), false);
41 +assert.equal(t.isRegExp('1'), false);
42 +assert.equal(t.isRegExp(new RegExp()), true);
43 +
44 +assert.equal(t.isObject({}), true);
45 +assert.equal(t.isObject([]), true);
46 +assert.equal(t.isObject(new RegExp()), true);
47 +assert.equal(t.isObject(new Date()), true);
48 +
49 +assert.equal(t.isDate(null), false);
50 +assert.equal(t.isDate('1'), false);
51 +assert.equal(t.isDate(new Date()), true);
52 +
53 +assert.equal(t.isError(null), false);
54 +assert.equal(t.isError({ err: true }), false);
55 +assert.equal(t.isError(new Error()), true);
56 +
57 +assert.equal(t.isFunction(null), false);
58 +assert.equal(t.isFunction({ }), false);
59 +assert.equal(t.isFunction(function() {}), true);
60 +
61 +assert.equal(t.isPrimitive(null), true);
62 +assert.equal(t.isPrimitive(''), true);
63 +assert.equal(t.isPrimitive(0), true);
64 +assert.equal(t.isPrimitive(new Date()), false);
65 +
66 +assert.equal(t.isBuffer(null), false);
67 +assert.equal(t.isBuffer({}), false);
68 +assert.equal(t.isBuffer(new Buffer(0)), true);
1 +language: node_js
2 +node_js:
3 + - "0.8"
4 + - "0.10"
1 +
2 +test:
3 + @node_modules/.bin/tape test.js
4 +
5 +.PHONY: test
6 +
1 +
2 +# isarray
3 +
4 +`Array#isArray` for older browsers.
5 +
6 +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray)
7 +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray)
8 +
9 +[![browser support](https://ci.testling.com/juliangruber/isarray.png)
10 +](https://ci.testling.com/juliangruber/isarray)
11 +
12 +## Usage
13 +
14 +```js
15 +var isArray = require('isarray');
16 +
17 +console.log(isArray([])); // => true
18 +console.log(isArray({})); // => false
19 +```
20 +
21 +## Installation
22 +
23 +With [npm](http://npmjs.org) do
24 +
25 +```bash
26 +$ npm install isarray
27 +```
28 +
29 +Then bundle for the browser with
30 +[browserify](https://github.com/substack/browserify).
31 +
32 +With [component](http://component.io) do
33 +
34 +```bash
35 +$ component install juliangruber/isarray
36 +```
37 +
38 +## License
39 +
40 +(MIT)
41 +
42 +Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
43 +
44 +Permission is hereby granted, free of charge, to any person obtaining a copy of
45 +this software and associated documentation files (the "Software"), to deal in
46 +the Software without restriction, including without limitation the rights to
47 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
48 +of the Software, and to permit persons to whom the Software is furnished to do
49 +so, subject to the following conditions:
50 +
51 +The above copyright notice and this permission notice shall be included in all
52 +copies or substantial portions of the Software.
53 +
54 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
55 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
56 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
57 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
58 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
59 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
60 +SOFTWARE.
1 +{
2 + "name" : "isarray",
3 + "description" : "Array#isArray for older browsers",
4 + "version" : "0.0.1",
5 + "repository" : "juliangruber/isarray",
6 + "homepage": "https://github.com/juliangruber/isarray",
7 + "main" : "index.js",
8 + "scripts" : [
9 + "index.js"
10 + ],
11 + "dependencies" : {},
12 + "keywords": ["browser","isarray","array"],
13 + "author": {
14 + "name": "Julian Gruber",
15 + "email": "mail@juliangruber.com",
16 + "url": "http://juliangruber.com"
17 + },
18 + "license": "MIT"
19 +}
1 +var toString = {}.toString;
2 +
3 +module.exports = Array.isArray || function (arr) {
4 + return toString.call(arr) == '[object Array]';
5 +};
1 +{
2 + "_from": "isarray@~1.0.0",
3 + "_id": "isarray@1.0.0",
4 + "_inBundle": false,
5 + "_integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=",
6 + "_location": "/isarray",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "isarray@~1.0.0",
12 + "name": "isarray",
13 + "escapedName": "isarray",
14 + "rawSpec": "~1.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "~1.0.0"
17 + },
18 + "_requiredBy": [
19 + "/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
22 + "_shasum": "bb935d48582cba168c06834957a54a3e07124f11",
23 + "_spec": "isarray@~1.0.0",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/readable-stream",
25 + "author": {
26 + "name": "Julian Gruber",
27 + "email": "mail@juliangruber.com",
28 + "url": "http://juliangruber.com"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/juliangruber/isarray/issues"
32 + },
33 + "bundleDependencies": false,
34 + "dependencies": {},
35 + "deprecated": false,
36 + "description": "Array#isArray for older browsers",
37 + "devDependencies": {
38 + "tape": "~2.13.4"
39 + },
40 + "homepage": "https://github.com/juliangruber/isarray",
41 + "keywords": [
42 + "browser",
43 + "isarray",
44 + "array"
45 + ],
46 + "license": "MIT",
47 + "main": "index.js",
48 + "name": "isarray",
49 + "repository": {
50 + "type": "git",
51 + "url": "git://github.com/juliangruber/isarray.git"
52 + },
53 + "scripts": {
54 + "test": "tape test.js"
55 + },
56 + "testling": {
57 + "files": "test.js",
58 + "browsers": [
59 + "ie/8..latest",
60 + "firefox/17..latest",
61 + "firefox/nightly",
62 + "chrome/22..latest",
63 + "chrome/canary",
64 + "opera/12..latest",
65 + "opera/next",
66 + "safari/5.1..latest",
67 + "ipad/6.0..latest",
68 + "iphone/6.0..latest",
69 + "android-browser/4.2..latest"
70 + ]
71 + },
72 + "version": "1.0.0"
73 +}
1 +var isArray = require('./');
2 +var test = require('tape');
3 +
4 +test('is array', function(t){
5 + t.ok(isArray([]));
6 + t.notOk(isArray({}));
7 + t.notOk(isArray(null));
8 + t.notOk(isArray(false));
9 +
10 + var obj = {};
11 + obj[0] = true;
12 + t.notOk(isArray(obj));
13 +
14 + var arr = [];
15 + arr.foo = 'bar';
16 + t.ok(isArray(arr));
17 +
18 + t.end();
19 +});
20 +
1 +# Changes
2 +
3 +This file is a manually maintained list of changes for each release. Feel free
4 +to add your changes here when sending pull requests. Also send corrections if
5 +you spot any mistakes.
6 +
7 +## v2.16.0 (2018-07-17)
8 +
9 +* Add Amazon RDS GovCloud SSL certificates #1876
10 +* Add new error codes up to MySQL 5.7.21
11 +* Include connection ID in debug output
12 +* Support Node.js 9.x
13 +* Support Node.js 10.x #2003 #2024 #2026 #2034
14 +* Update Amazon RDS SSL certificates
15 +* Update `bignumber.js` to 4.1.0
16 +* Update `readable-stream` to 2.3.6
17 +* Update `sqlstring` to 2.3.1
18 + - Fix incorrectly replacing non-placeholders in SQL
19 +
20 +## v2.15.0 (2017-10-05)
21 +
22 +* Add new Amazon RDS ca-central-1 certificate CA to Amazon RDS SSL profile #1809
23 +* Add new error codes up to MySQL 5.7.19
24 +* Add `mysql.raw()` to generate pre-escaped values #877 #1821
25 +* Fix "changedRows" to work on non-English servers #1819
26 +* Fix error when server sends RST on `QUIT` #1811
27 +* Fix typo in insecure auth error message
28 +* Support `mysql_native_password` auth switch request for Azure #1396 #1729 #1730
29 +* Update `sqlstring` to 2.3.0
30 + - Add `.toSqlString()` escape overriding
31 + - Small performance improvement on `escapeId`
32 +* Update `bignumber.js` to 4.0.4
33 +
34 +## v2.14.1 (2017-08-01)
35 +
36 +* Fix holding first closure for lifetime of connection #1785
37 +
38 +## v2.14.0 (2017-07-25)
39 +
40 +* Add new Amazon RDS ap-south-1 certificate CA to Amazon RDS SSL profile #1780
41 +* Add new Amazon RDS eu-west-2 certificate CA to Amazon RDS SSL profile #1770
42 +* Add `sql` property to query `Error` objects #1462 #1628 #1629
43 +* Add `sqlMessage` property to `Error` objects #1714
44 +* Fix the MySQL 5.7.17 error codes
45 +* Support Node.js 8.x
46 +* Update `bignumber.js` to 4.0.2
47 +* Update `readable-stream` to 2.3.3
48 +* Use `safe-buffer` for improved Buffer API
49 +
50 +## v2.13.0 (2017-01-24)
51 +
52 +* Accept regular expression as pool cluster pattern #1572
53 +* Accept wildcard anywhere in pool cluster pattern #1570
54 +* Add `acquire` and `release` events to `Pool` for tracking #1366 #1449 #1528 #1625
55 +* Add new error codes up to MySQL 5.7.17
56 +* Fix edge cases when determing Query result packets #1547
57 +* Fix memory leak when using long-running domains #1619 #1620
58 +* Remove unnecessary buffer copies when receiving large packets
59 +* Update `bignumber.js` to 3.1.2
60 +* Use a simple buffer list to improve performance #566 #1590
61 +
62 +## v2.12.0 (2016-11-02)
63 +
64 +* Accept array of type names to `dateStrings` option #605 #1481
65 +* Add `query` method to `PoolNamespace` #1256 #1505 #1506
66 + - Used as `cluster.of(...).query(...)`
67 +* Add new error codes up to MySQL 5.7.16
68 +* Fix edge cases writing certain length coded values
69 +* Fix typo in `HANDSHAKE_NO_SSL_SUPPORT` error message #1534
70 +* Support Node.js 7.x
71 +* Update `bignumber.js` to 2.4.0
72 +* Update `sqlstring` to 2.2.0
73 + - Accept numbers and other value types in `escapeId`
74 + - Escape invalid `Date` objects as `NULL`
75 + - Run `buffer.toString()` through escaping
76 +
77 +## v2.11.1 (2016-06-07)
78 +
79 +* Fix writing truncated packets starting with large string/buffer #1438
80 +
81 +## v2.11.0 (2016-06-06)
82 +
83 +* Add `POOL_CLOSED` code to "Pool is closed." error
84 +* Add `POOL_CONNLIMIT` code to "No connections available." error #1332
85 +* Bind underlying connections in pool to same domain as pool #1242
86 +* Bind underlying socket to same domain as connection #1243
87 +* Fix allocation errors receiving many result rows #918 #1265 #1324 #1415
88 +* Fix edge cases constructing long stack traces #1387
89 +* Fix handshake inactivity timeout on Node.js v4.2.0 #1223 #1236 #1239 #1240 #1241 #1252
90 +* Fix Query stream to emit close after ending #1349 #1350
91 +* Fix type cast for BIGINT columns when number is negative #1376
92 +* Performance improvements for array/object escaping in SqlString #1331
93 +* Performance improvements for formatting in SqlString #1431
94 +* Performance improvements for string escaping in SqlString #1390
95 +* Performance improvements for writing packets to network
96 +* Support Node.js 6.x
97 +* Update `bignumber.js` to 2.3.0
98 +* Update `readable-stream` to 1.1.14
99 +* Use the `sqlstring` module for SQL escaping and formatting
100 +
101 +## v2.10.2 (2016-01-12)
102 +
103 +* Fix exception/hang from certain SSL connection errors #1153
104 +* Update `bignumber.js` to 2.1.4
105 +
106 +## v2.10.1 (2016-01-11)
107 +
108 +* Add new Amazon RDS ap-northeast-2 certificate CA to Amazon RDS SSL profile #1329
109 +
110 +## v2.10.0 (2015-12-15)
111 +
112 +* Add new error codes up to MySQL 5.7.9 #1294
113 +* Add new JSON type constant #1295
114 +* Add types for fractional seconds support
115 +* Fix `connection.destroy()` on pool connection creating sequences #1291
116 +* Fix error code 139 `HA_ERR_TO_BIG_ROW` to be `HA_ERR_TOO_BIG_ROW`
117 +* Fix error when call site error is missing stack #1179
118 +* Fix reading password from MySQL URL that has bare colon #1278
119 +* Handle MySQL servers not closing TCP connection after QUIT -> OK exchange #1277
120 +* Minor SqlString Date to string performance improvement #1233
121 +* Support Node.js 4.x
122 +* Support Node.js 5.x
123 +* Update `bignumber.js` to 2.1.2
124 +
125 +## v2.9.0 (2015-08-19)
126 +
127 +* Accept the `ciphers` property in connection `ssl` option #1185
128 +* Fix bad timezone conversion from `Date` to string for certain times #1045 #1155
129 +
130 +## v2.8.0 (2015-07-13)
131 +
132 +* Add `connect` event to `Connection` #1129
133 +* Default `timeout` for `connection.end` to 30 seconds #1057
134 +* Fix a sync callback when sequence enqueue fails #1147
135 +* Provide static require analysis
136 +* Re-use connection from pool after `conn.changeUser` is used #837 #1088
137 +
138 +## v2.7.0 (2015-05-27)
139 +
140 +* Destroy/end connections removed from the pool on error
141 +* Delay implied connect until after `.query` argument validation
142 +* Do not remove connections with non-fatal errors from the pool
143 +* Error early if `callback` argument to `.query` is not a function #1060
144 +* Lazy-load modules from many entry point; reduced memory use
145 +
146 +## v2.6.2 (2015-04-14)
147 +
148 +* Fix `Connection.createQuery` for no SQL #1058
149 +* Update `bignumber.js` to 2.0.7
150 +
151 +## v2.6.1 (2015-03-26)
152 +
153 +* Update `bignumber.js` to 2.0.5 #1037 #1038
154 +
155 +## v2.6.0 (2015-03-24)
156 +
157 +* Add `poolCluster.remove` to remove pools from the cluster #1006 #1007
158 +* Add optional callback to `poolCluster.end`
159 +* Add `restoreNodeTimeout` option to `PoolCluster` #880 #906
160 +* Fix LOAD DATA INFILE handling in multiple statements #1036
161 +* Fix `poolCluster.add` to throw if `PoolCluster` has been closed
162 +* Fix `poolCluster.add` to throw if `id` already defined
163 +* Fix un-catchable error from `PoolCluster` when MySQL server offline #1033
164 +* Improve speed formatting SQL #1019
165 +* Support io.js
166 +
167 +## v2.5.5 (2015-02-23)
168 +
169 +* Store SSL presets in JS instead of JSON #959
170 +* Support Node.js 0.12
171 +* Update Amazon RDS SSL certificates #1001
172 +
173 +## v2.5.4 (2014-12-16)
174 +
175 +* Fix error if falsy error thrown in callback handler #960
176 +* Fix various error code strings #954
177 +
178 +## v2.5.3 (2014-11-06)
179 +
180 +* Fix `pool.query` streaming interface not emitting connection errors #941
181 +
182 +## v2.5.2 (2014-10-10)
183 +
184 +* Fix receiving large text fields #922
185 +
186 +## v2.5.1 (2014-09-22)
187 +
188 +* Fix `pool.end` race conditions #915
189 +* Fix `pool.getConnection` race conditions
190 +
191 +## v2.5.0 (2014-09-07)
192 +
193 +* Add code `POOL_ENQUEUELIMIT` to error reaching `queueLimit`
194 +* Add `enqueue` event to pool #716
195 +* Add `enqueue` event to protocol and connection #381
196 +* Blacklist unsupported connection flags #881
197 +* Make only column names enumerable in `RowDataPacket` #549 #895
198 +* Support Node.js 0.6 #718
199 +
200 +## v2.4.3 (2014-08-25)
201 +
202 +* Fix `pool.query` to use `typeCast` configuration
203 +
204 +## v2.4.2 (2014-08-03)
205 +
206 +* Fix incorrect sequence packet errors to be catchable #867
207 +* Fix stray protocol packet errors to be catchable #867
208 +* Fix timing of fatal protocol errors bubbling to user #879
209 +
210 +## v2.4.1 (2014-07-17)
211 +
212 +* Fix `pool.query` not invoking callback on connection error #872
213 +
214 +## v2.4.0 (2014-07-13)
215 +
216 +* Add code `POOL_NOEXIST` in PoolCluster error #846
217 +* Add `acquireTimeout` pool option to specify a timeout for acquiring a connection #821 #854
218 +* Add `connection.escapeId`
219 +* Add `pool.escapeId`
220 +* Add `timeout` option to all sequences #855 #863
221 +* Default `connectTimeout` to 10 seconds
222 +* Fix domain binding with `conn.connect`
223 +* Fix `packet.default` to actually be a string
224 +* Fix `PARSER_*` errors to be catchable
225 +* Fix `PROTOCOL_PACKETS_OUT_OF_ORDER` error to be catchable #844
226 +* Include packets that failed parsing under `debug`
227 +* Return `Query` object from `pool.query` like `conn.query` #830
228 +* Use `EventEmitter.listenerCount` when possible for faster counting
229 +
230 +## v2.3.2 (2014-05-29)
231 +
232 +* Fix pool leaking connections after `conn.changeUser` #833
233 +
234 +## v2.3.1 (2014-05-26)
235 +
236 +* Add database errors to error constants
237 +* Add global errors to error constants
238 +* Throw when calling `conn.release` multiple times #824 #827
239 +* Update known error codes
240 +
241 +## v2.3.0 (2014-05-16)
242 +
243 +* Accept MySQL charset (like `UTF8` or `UTF8MB4`) in `charset` option #808
244 +* Accept pool options in connection string to `mysql.createPool` #811
245 +* Clone connection config for new pool connections
246 +* Default `connectTimeout` to 2 minutes
247 +* Reject unauthorized SSL connections (use `ssl.rejectUnauthorized` to override) #816
248 +* Return last error when PoolCluster exhausts connection retries #818
249 +* Remove connection from pool after `conn.changeUser` is released #806
250 +* Throw on unknown SSL profile name #817
251 +* User newer TLS functions when available #809
252 +
253 +## v2.2.0 (2014-04-27)
254 +
255 +* Use indexOf instead of for loops removing conn from pool #611
256 +* Make callback to `pool.query` optional like `conn.query` #585
257 +* Prevent enqueuing sequences after fatal error #400
258 +* Fix geometry parser for empty fields #742
259 +* Accept lower-case charset option
260 +* Throw on unknown charset option #789
261 +* Update known charsets
262 +* Remove console.warn from PoolCluster #744
263 +* Fix `pool.end` to handle queued connections #797
264 +* Fix `pool.releaseConnection` to keep connection queue flowing #797
265 +* Fix SSL handshake error to be catchable #800
266 +* Add `connection.threadId` to get MySQL connection ID #602
267 +* Ensure `pool.getConnection` retrieves good connections #434 #557 #778
268 +* Fix pool cluster wildcard matching #627
269 +* Pass query values through to `SqlString.format` #590
270 +
271 +## v2.1.1 (2014-03-13)
272 +
273 +* fix authentication w/password failure for node.js 0.10.5 #746 #752
274 +* fix authentication w/password TypeError exception for node.js 0.10.0-0.10.4 #747
275 +* fix specifying `values` in `conn.query({...}).on(...)` pattern #755
276 +* fix long stack trace to include the `pool.query(...)` call #715
277 +
278 +## v2.1.0 (2014-02-20)
279 +
280 +* crypto.createHash fix for node.js < 11 #735
281 +* Add `connectTimeout` option to specify a timeout for establishing a connection #726
282 +* SSL support #481
283 +
284 +## v2.0.1
285 +
286 +* internal parser speed improvement #702
287 +* domains support
288 +* 'trace' connection option to control if long stack traces are generated #713 #710 #439
289 +
290 +## v2.0.0 (2014-01-09)
291 +
292 +* stream improvements:
293 + - node 0.8 support #692
294 + - Emit 'close' events from query streams #688
295 +* encoding fix in streaming LOAD DATA LOCAL INFILE #670
296 +* Doc improvements
297 +
298 +## v2.0.0-rc2 (2013-12-07)
299 +
300 +* Streaming LOAD DATA LOCAL INFILE #668
301 +* Doc improvements
302 +
303 +## v2.0.0-rc1 (2013-11-30)
304 +
305 +* Transaction support
306 +* Expose SqlString.format as mysql.format()
307 +* Many bug fixes
308 +* Better support for dates in local time zone
309 +* Doc improvements
310 +
311 +## v2.0.0-alpha9 (2013-08-27)
312 +
313 +* Add query to pool to execute queries directly using the pool
314 +* Add `sqlState` property to `Error` objects #556
315 +* Pool option to set queue limit
316 +* Pool sends 'connection' event when it opens a new connection
317 +* Added stringifyObjects option to treat input as strings rather than objects (#501)
318 +* Support for poolClusters
319 +* Datetime improvements
320 +* Bug fixes
321 +
322 +## v2.0.0-alpha8 (2013-04-30)
323 +
324 +* Switch to old mode for Streams 2 (Node.js v 0.10.x)
325 +* Add stream method to Query Wraps events from the query object into a node v0.10.x Readable stream
326 +* DECIMAL should also be treated as big number
327 +* Removed slow unnecessary stack access
328 +* Added charsets
329 +* Added bigNumberStrings option for forcing BIGINT columns as strings
330 +* Changes date parsing to return String if not a valid JS Date
331 +* Adds support for ?? escape sequence to escape identifiers
332 +* Changes Auth.token() to force password to be in binary, not utf8 (#378)
333 +* Restrict debugging by packet types
334 +* Add 'multipleStatements' option tracking to ConnectionConfig. Fixes GH-408
335 +* Changes Pool to handle 'error' events and dispose connection
336 +* Allows db.query({ sql: "..." }, [ val1, ... ], cb); (#390)
337 +* Improved documentation
338 +* Bug fixes
339 +
340 +## v2.0.0-alpha7 (2013-02-03)
341 +
342 +* Add connection pooling (#351)
343 +
344 +## v2.0.0-alpha6 (2013-01-31)
345 +
346 +* Add supportBigNumbers option (#381, #382)
347 +* Accept prebuilt Query object in connection.query
348 +* Bug fixes
349 +
350 +## v2.0.0-alpha5 (2012-12-03)
351 +
352 +* Add mysql.escapeId to escape identifiers (closes #342)
353 +* Allow custom escaping mode (config.queryFormat)
354 +* Convert DATE columns to configured timezone instead of UTC (#332)
355 +* Convert LONGLONG and NEWDECIMAL to numbers (#333)
356 +* Fix Connection.escape() (fixes #330)
357 +* Changed Readme ambiguity about custom type cast fallback
358 +* Change typeCast to receive Connection instead of Connection.config.timezone
359 +* Fix drain event having useless err parameter
360 +* Add Connection.statistics() back from v0.9
361 +* Add Connection.ping() back from v0.9
362 +
363 +## v2.0.0-alpha4 (2012-10-03)
364 +
365 +* Fix some OOB errors on resume()
366 +* Fix quick pause() / resume() usage
367 +* Properly parse host denied / similar errors
368 +* Add Connection.ChangeUser functionality
369 +* Make sure changeUser errors are fatal
370 +* Enable formatting nested arrays for bulk inserts
371 +* Add Connection.escape functionality
372 +* Renamed 'close' to 'end' event
373 +* Return parsed object instead of Buffer for GEOMETRY types
374 +* Allow nestTables inline (using a string instead of a boolean)
375 +* Check for ZEROFILL_FLAG and format number accordingly
376 +* Add timezone support (default: local)
377 +* Add custom typeCast functionality
378 +* Export mysql column types
379 +* Add connection flags functionality (#237)
380 +* Exports drain event when queue finishes processing (#272, #271, #306)
381 +
382 +## v2.0.0-alpha3 (2012-06-12)
383 +
384 +* Implement support for `LOAD DATA LOCAL INFILE` queries (#182).
385 +* Support OLD\_PASSWORD() accounts like 0.9.x did. You should still upgrade any
386 + user accounts in your your MySQL user table that has short (16 byte) Password
387 + values. Connecting to those accounts is not secure. (#204)
388 +* Ignore function values when escaping objects, allows to use RowDataPacket
389 + objects as query arguments. (Alex Gorbatchev, #213)
390 +* Handle initial error packets from server such as `ER_HOST_NOT_PRIVILEGED`.
391 +* Treat `utf8\_bin` as a String, not Buffer. (#214)
392 +* Handle empty strings in first row column value. (#222)
393 +* Honor Connection#nestTables setting for queries. (#221)
394 +* Remove `CLIENT_INTERACTIVE` flag from config. Improves #225.
395 +* Improve docs for connections settings.
396 +* Implement url string support for Connection configs.
397 +
398 +## v2.0.0-alpha2 (2012-05-31)
399 +
400 +* Specify escaping before for NaN / Infinity (they are as unquoted constants).
401 +* Support for unix domain socket connections (use: {socketPath: '...'}).
402 +* Fix type casting for NULL values for Date/Number fields
403 +* Add `fields` argument to `query()` as well as `'fields'` event. This is
404 + similar to what was available in 0.9.x.
405 +* Support connecting to the sphinx searchd daemon as well as MariaDB (#199).
406 +* Implement long stack trace support, will be removed / disabled if the node
407 + core ever supports it natively.
408 +* Implement `nestTables` option for queries, allows fetching JOIN result sets
409 + with overlapping column names.
410 +* Fix ? placeholder mechanism for values containing '?' characters (#205).
411 +* Detect when `connect()` is called more than once on a connection and provide
412 + the user with a good error message for it (#204).
413 +* Switch to `UTF8_GENERAL_CI` (previously `UTF8_UNICODE_CI`) as the default
414 + charset for all connections to avoid strange MySQL performance issues (#200),
415 + and also make the charset user configurable.
416 +* Fix BLOB type casting for `TINY_BLOB`, `MEDIUM_BLOB` and `LONG_BLOB`.
417 +* Add support for sending and receiving large (> 16 MB) packets.
418 +
419 +## v2.0.0-alpha (2012-05-15)
420 +
421 +This release is a rewrite. You should carefully test your application after
422 +upgrading to avoid problems. This release features many improvements, most
423 +importantly:
424 +
425 +* ~5x faster than v0.9.x for parsing query results
426 +* Support for pause() / resume() (for streaming rows)
427 +* Support for multiple statement queries
428 +* Support for stored procedures
429 +* Support for transactions
430 +* Support for binary columns (as blobs)
431 +* Consistent & well documented error handling
432 +* A new Connection class that has well defined semantics (unlike the old Client class).
433 +* Convenient escaping of objects / arrays that allows for simpler query construction
434 +* A significantly simpler code base
435 +* Many bug fixes & other small improvements (Closed 62 out of 66 GitHub issues)
436 +
437 +Below are a few notes on the upgrade process itself:
438 +
439 +The first thing you will run into is that the old `Client` class is gone and
440 +has been replaced with a less ambitious `Connection` class. So instead of
441 +`mysql.createClient()`, you now have to:
442 +
443 +```js
444 +var mysql = require('mysql');
445 +var connection = mysql.createConnection({
446 + host : 'localhost',
447 + user : 'me',
448 + password : 'secret',
449 +});
450 +
451 +connection.query('SELECT 1', function(err, rows) {
452 + if (err) throw err;
453 +
454 + console.log('Query result: ', rows);
455 +});
456 +
457 +connection.end();
458 +```
459 +
460 +The new `Connection` class does not try to handle re-connects, please study the
461 +`Server disconnects` section in the new Readme.
462 +
463 +Other than that, the interface has stayed very similar. Here are a few things
464 +to check out so:
465 +
466 +* BIGINT's are now cast into strings
467 +* Binary data is now cast to buffers
468 +* The `'row'` event on the `Query` object is now called `'result'` and will
469 + also be emitted for queries that produce an OK/Error response.
470 +* Error handling is consistently defined now, check the Readme
471 +* Escaping has become more powerful which may break your code if you are
472 + currently using objects to fill query placeholders.
473 +* Connections can now be established explicitly again, so you may wish to do so
474 + if you want to handle connection errors specifically.
475 +
476 +That should be most of it, if you run into anything else, please send a patch
477 +or open an issue to improve this document.
478 +
479 +## v0.9.6 (2012-03-12)
480 +
481 +* Escape array values so they produce sql arrays (Roger Castells, Colin Smith)
482 +* docs: mention mysql transaction stop gap solution (Blake Miner)
483 +* docs: Mention affectedRows in FAQ (Michael Baldwin)
484 +
485 +## v0.9.5 (2011-11-26)
486 +
487 +* Fix #142 Driver stalls upon reconnect attempt that's immediately closed
488 +* Add travis build
489 +* Switch to urun as a test runner
490 +* Switch to utest for unit tests
491 +* Remove fast-or-slow dependency for tests
492 +* Split integration tests into individual files again
493 +
494 +## v0.9.4 (2011-08-31)
495 +
496 +* Expose package.json as `mysql.PACKAGE` (#104)
497 +
498 +## v0.9.3 (2011-08-22)
499 +
500 +* Set default `client.user` to root
501 +* Fix #91: Client#format should not mutate params array
502 +* Fix #94: TypeError in client.js
503 +* Parse decimals as string (vadimg)
504 +
505 +## v0.9.2 (2011-08-07)
506 +
507 +* The underlaying socket connection is now managed implicitly rather than explicitly.
508 +* Check the [upgrading guide][] for a full list of changes.
509 +
510 +## v0.9.1 (2011-02-20)
511 +
512 +* Fix issue #49 / `client.escape()` throwing exceptions on objects. (Nick Payne)
513 +* Drop < v0.4.x compatibility. From now on you need node v0.4.x to use this module.
514 +
515 +## Older releases
516 +
517 +These releases were done before maintaining this file:
518 +
519 +* [v0.9.0](https://github.com/mysqljs/mysql/compare/v0.8.0...v0.9.0)
520 + (2011-01-04)
521 +* [v0.8.0](https://github.com/mysqljs/mysql/compare/v0.7.0...v0.8.0)
522 + (2010-10-30)
523 +* [v0.7.0](https://github.com/mysqljs/mysql/compare/v0.6.0...v0.7.0)
524 + (2010-10-14)
525 +* [v0.6.0](https://github.com/mysqljs/mysql/compare/v0.5.0...v0.6.0)
526 + (2010-09-28)
527 +* [v0.5.0](https://github.com/mysqljs/mysql/compare/v0.4.0...v0.5.0)
528 + (2010-09-17)
529 +* [v0.4.0](https://github.com/mysqljs/mysql/compare/v0.3.0...v0.4.0)
530 + (2010-09-02)
531 +* [v0.3.0](https://github.com/mysqljs/mysql/compare/v0.2.0...v0.3.0)
532 + (2010-08-25)
533 +* [v0.2.0](https://github.com/mysqljs/mysql/compare/v0.1.0...v0.2.0)
534 + (2010-08-22)
535 +* [v0.1.0](https://github.com/mysqljs/mysql/commits/v0.1.0)
536 + (2010-08-22)
1 +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors
2 +
3 + Permission is hereby granted, free of charge, to any person obtaining a copy
4 + of this software and associated documentation files (the "Software"), to deal
5 + in the Software without restriction, including without limitation the rights
6 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 + copies of the Software, and to permit persons to whom the Software is
8 + furnished to do so, subject to the following conditions:
9 +
10 + The above copyright notice and this permission notice shall be included in
11 + all copies or substantial portions of the Software.
12 +
13 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 + THE SOFTWARE.
1 +# mysql
2 +
3 +[![NPM Version][npm-image]][npm-url]
4 +[![NPM Downloads][downloads-image]][downloads-url]
5 +[![Node.js Version][node-version-image]][node-version-url]
6 +[![Linux Build][travis-image]][travis-url]
7 +[![Windows Build][appveyor-image]][appveyor-url]
8 +[![Test Coverage][coveralls-image]][coveralls-url]
9 +
10 +## Table of Contents
11 +
12 +- [Install](#install)
13 +- [Introduction](#introduction)
14 +- [Contributors](#contributors)
15 +- [Sponsors](#sponsors)
16 +- [Community](#community)
17 +- [Establishing connections](#establishing-connections)
18 +- [Connection options](#connection-options)
19 +- [SSL options](#ssl-options)
20 +- [Terminating connections](#terminating-connections)
21 +- [Pooling connections](#pooling-connections)
22 +- [Pool options](#pool-options)
23 +- [Pool events](#pool-events)
24 +- [Closing all the connections in a pool](#closing-all-the-connections-in-a-pool)
25 +- [PoolCluster](#poolcluster)
26 +- [PoolCluster options](#poolcluster-options)
27 +- [Switching users and altering connection state](#switching-users-and-altering-connection-state)
28 +- [Server disconnects](#server-disconnects)
29 +- [Performing queries](#performing-queries)
30 +- [Escaping query values](#escaping-query-values)
31 +- [Escaping query identifiers](#escaping-query-identifiers)
32 +- [Preparing Queries](#preparing-queries)
33 +- [Custom format](#custom-format)
34 +- [Getting the id of an inserted row](#getting-the-id-of-an-inserted-row)
35 +- [Getting the number of affected rows](#getting-the-number-of-affected-rows)
36 +- [Getting the number of changed rows](#getting-the-number-of-changed-rows)
37 +- [Getting the connection ID](#getting-the-connection-id)
38 +- [Executing queries in parallel](#executing-queries-in-parallel)
39 +- [Streaming query rows](#streaming-query-rows)
40 +- [Piping results with Streams](#piping-results-with-streams)
41 +- [Multiple statement queries](#multiple-statement-queries)
42 +- [Stored procedures](#stored-procedures)
43 +- [Joins with overlapping column names](#joins-with-overlapping-column-names)
44 +- [Transactions](#transactions)
45 +- [Ping](#ping)
46 +- [Timeouts](#timeouts)
47 +- [Error handling](#error-handling)
48 +- [Exception Safety](#exception-safety)
49 +- [Type casting](#type-casting)
50 +- [Connection Flags](#connection-flags)
51 +- [Debugging and reporting problems](#debugging-and-reporting-problems)
52 +- [Security issues](#security-issues)
53 +- [Contributing](#contributing)
54 +- [Running tests](#running-tests)
55 +- [Todo](#todo)
56 +
57 +## Install
58 +
59 +This is a [Node.js](https://nodejs.org/en/) module available through the
60 +[npm registry](https://www.npmjs.com/).
61 +
62 +Before installing, [download and install Node.js](https://nodejs.org/en/download/).
63 +Node.js 0.6 or higher is required.
64 +
65 +Installation is done using the
66 +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
67 +
68 +```sh
69 +$ npm install mysql
70 +```
71 +
72 +For information about the previous 0.9.x releases, visit the [v0.9 branch][].
73 +
74 +Sometimes I may also ask you to install the latest version from Github to check
75 +if a bugfix is working. In this case, please do:
76 +
77 +```sh
78 +$ npm install mysqljs/mysql
79 +```
80 +
81 +[v0.9 branch]: https://github.com/mysqljs/mysql/tree/v0.9
82 +
83 +## Introduction
84 +
85 +This is a node.js driver for mysql. It is written in JavaScript, does not
86 +require compiling, and is 100% MIT licensed.
87 +
88 +Here is an example on how to use it:
89 +
90 +```js
91 +var mysql = require('mysql');
92 +var connection = mysql.createConnection({
93 + host : 'localhost',
94 + user : 'me',
95 + password : 'secret',
96 + database : 'my_db'
97 +});
98 +
99 +connection.connect();
100 +
101 +connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
102 + if (error) throw error;
103 + console.log('The solution is: ', results[0].solution);
104 +});
105 +
106 +connection.end();
107 +```
108 +
109 +From this example, you can learn the following:
110 +
111 +* Every method you invoke on a connection is queued and executed in sequence.
112 +* Closing the connection is done using `end()` which makes sure all remaining
113 + queries are executed before sending a quit packet to the mysql server.
114 +
115 +## Contributors
116 +
117 +Thanks goes to the people who have contributed code to this module, see the
118 +[GitHub Contributors page][].
119 +
120 +[GitHub Contributors page]: https://github.com/mysqljs/mysql/graphs/contributors
121 +
122 +Additionally I'd like to thank the following people:
123 +
124 +* [Andrey Hristov][] (Oracle) - for helping me with protocol questions.
125 +* [Ulf Wendel][] (Oracle) - for helping me with protocol questions.
126 +
127 +[Ulf Wendel]: http://blog.ulf-wendel.de/
128 +[Andrey Hristov]: http://andrey.hristov.com/
129 +
130 +## Sponsors
131 +
132 +The following companies have supported this project financially, allowing me to
133 +spend more time on it (ordered by time of contribution):
134 +
135 +* [Transloadit](http://transloadit.com) (my startup, we do file uploading &
136 + video encoding as a service, check it out)
137 +* [Joyent](http://www.joyent.com/)
138 +* [pinkbike.com](http://pinkbike.com/)
139 +* [Holiday Extras](http://www.holidayextras.co.uk/) (they are [hiring](http://join.holidayextras.co.uk/))
140 +* [Newscope](http://newscope.com/) (they are [hiring](https://newscope.com/unternehmen/jobs/))
141 +
142 +## Community
143 +
144 +If you'd like to discuss this module, or ask questions about it, please use one
145 +of the following:
146 +
147 +* **Mailing list**: https://groups.google.com/forum/#!forum/node-mysql
148 +* **IRC Channel**: #node.js (on freenode.net, I pay attention to any message
149 + including the term `mysql`)
150 +
151 +## Establishing connections
152 +
153 +The recommended way to establish a connection is this:
154 +
155 +```js
156 +var mysql = require('mysql');
157 +var connection = mysql.createConnection({
158 + host : 'example.org',
159 + user : 'bob',
160 + password : 'secret'
161 +});
162 +
163 +connection.connect(function(err) {
164 + if (err) {
165 + console.error('error connecting: ' + err.stack);
166 + return;
167 + }
168 +
169 + console.log('connected as id ' + connection.threadId);
170 +});
171 +```
172 +
173 +However, a connection can also be implicitly established by invoking a query:
174 +
175 +```js
176 +var mysql = require('mysql');
177 +var connection = mysql.createConnection(...);
178 +
179 +connection.query('SELECT 1', function (error, results, fields) {
180 + if (error) throw error;
181 + // connected!
182 +});
183 +```
184 +
185 +Depending on how you like to handle your errors, either method may be
186 +appropriate. Any type of connection error (handshake or network) is considered
187 +a fatal error, see the [Error Handling](#error-handling) section for more
188 +information.
189 +
190 +## Connection options
191 +
192 +When establishing a connection, you can set the following options:
193 +
194 +* `host`: The hostname of the database you are connecting to. (Default:
195 + `localhost`)
196 +* `port`: The port number to connect to. (Default: `3306`)
197 +* `localAddress`: The source IP address to use for TCP connection. (Optional)
198 +* `socketPath`: The path to a unix domain socket to connect to. When used `host`
199 + and `port` are ignored.
200 +* `user`: The MySQL user to authenticate as.
201 +* `password`: The password of that MySQL user.
202 +* `database`: Name of the database to use for this connection (Optional).
203 +* `charset`: The charset for the connection. This is called "collation" in the SQL-level
204 + of MySQL (like `utf8_general_ci`). If a SQL-level charset is specified (like `utf8mb4`)
205 + then the default collation for that charset is used. (Default: `'UTF8_GENERAL_CI'`)
206 +* `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'`)
207 +* `connectTimeout`: The milliseconds before a timeout occurs during the initial connection
208 + to the MySQL server. (Default: `10000`)
209 +* `stringifyObjects`: Stringify objects instead of converting to values. See
210 +issue [#501](https://github.com/mysqljs/mysql/issues/501). (Default: `false`)
211 +* `insecureAuth`: Allow connecting to MySQL instances that ask for the old
212 + (insecure) authentication method. (Default: `false`)
213 +* `typeCast`: Determines if column values should be converted to native
214 + JavaScript types. (Default: `true`)
215 +* `queryFormat`: A custom query format function. See [Custom format](#custom-format).
216 +* `supportBigNumbers`: When dealing with big numbers (BIGINT and DECIMAL columns) in the database,
217 + you should enable this option (Default: `false`).
218 +* `bigNumberStrings`: Enabling both `supportBigNumbers` and `bigNumberStrings` forces big numbers
219 + (BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default: `false`).
220 + Enabling `supportBigNumbers` but leaving `bigNumberStrings` disabled will return big numbers as String
221 + objects only when they cannot be accurately represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5)
222 + (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as
223 + Number objects. This option is ignored if `supportBigNumbers` is disabled.
224 +* `dateStrings`: Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then
225 + inflated into JavaScript Date objects. Can be `true`/`false` or an array of type names to keep as
226 + strings. (Default: `false`)
227 +* `debug`: Prints protocol details to stdout. Can be `true`/`false` or an array of packet type names
228 + that should be printed. (Default: `false`)
229 +* `trace`: Generates stack traces on `Error` to include call site of library
230 + entrance ("long stack traces"). Slight performance penalty for most calls.
231 + (Default: `true`)
232 +* `multipleStatements`: Allow multiple mysql statements per query. Be careful
233 + with this, it could increase the scope of SQL injection attacks. (Default: `false`)
234 +* `flags`: List of connection flags to use other than the default ones. It is
235 + also possible to blacklist default ones. For more information, check
236 + [Connection Flags](#connection-flags).
237 +* `ssl`: object with ssl parameters or a string containing name of ssl profile. See [SSL options](#ssl-options).
238 +
239 +
240 +In addition to passing these options as an object, you can also use a url
241 +string. For example:
242 +
243 +```js
244 +var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700');
245 +```
246 +
247 +Note: The query values are first attempted to be parsed as JSON, and if that
248 +fails assumed to be plaintext strings.
249 +
250 +### SSL options
251 +
252 +The `ssl` option in the connection options takes a string or an object. When given a string,
253 +it uses one of the predefined SSL profiles included. The following profiles are included:
254 +
255 +* `"Amazon RDS"`: this profile is for connecting to an Amazon RDS server and contains the
256 + certificates from https://rds.amazonaws.com/doc/rds-ssl-ca-cert.pem and
257 + https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem
258 +
259 +When connecting to other servers, you will need to provide an object of options, in the
260 +same format as [tls.createSecureContext](https://nodejs.org/api/tls.html#tls_tls_createsecurecontext_options).
261 +Please note the arguments expect a string of the certificate, not a file name to the
262 +certificate. Here is a simple example:
263 +
264 +```js
265 +var connection = mysql.createConnection({
266 + host : 'localhost',
267 + ssl : {
268 + ca : fs.readFileSync(__dirname + '/mysql-ca.crt')
269 + }
270 +});
271 +```
272 +
273 +You can also connect to a MySQL server without properly providing the appropriate
274 +CA to trust. _You should not do this_.
275 +
276 +```js
277 +var connection = mysql.createConnection({
278 + host : 'localhost',
279 + ssl : {
280 + // DO NOT DO THIS
281 + // set up your ca correctly to trust the connection
282 + rejectUnauthorized: false
283 + }
284 +});
285 +```
286 +
287 +## Terminating connections
288 +
289 +There are two ways to end a connection. Terminating a connection gracefully is
290 +done by calling the `end()` method:
291 +
292 +```js
293 +connection.end(function(err) {
294 + // The connection is terminated now
295 +});
296 +```
297 +
298 +This will make sure all previously enqueued queries are still before sending a
299 +`COM_QUIT` packet to the MySQL server. If a fatal error occurs before the
300 +`COM_QUIT` packet can be sent, an `err` argument will be provided to the
301 +callback, but the connection will be terminated regardless of that.
302 +
303 +An alternative way to end the connection is to call the `destroy()` method.
304 +This will cause an immediate termination of the underlying socket.
305 +Additionally `destroy()` guarantees that no more events or callbacks will be
306 +triggered for the connection.
307 +
308 +```js
309 +connection.destroy();
310 +```
311 +
312 +Unlike `end()` the `destroy()` method does not take a callback argument.
313 +
314 +## Pooling connections
315 +
316 +Rather than creating and managing connections one-by-one, this module also
317 +provides built-in connection pooling using `mysql.createPool(config)`.
318 +[Read more about connection pooling](https://en.wikipedia.org/wiki/Connection_pool).
319 +
320 +Create a pool and use it directly:
321 +
322 +```js
323 +var mysql = require('mysql');
324 +var pool = mysql.createPool({
325 + connectionLimit : 10,
326 + host : 'example.org',
327 + user : 'bob',
328 + password : 'secret',
329 + database : 'my_db'
330 +});
331 +
332 +pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
333 + if (error) throw error;
334 + console.log('The solution is: ', results[0].solution);
335 +});
336 +```
337 +
338 +This is a shortcut for the `pool.getConnection()` -> `connection.query()` ->
339 +`connection.release()` code flow. Using `pool.getConnection()` is useful to
340 +share connection state for subsequent queries. This is because two calls to
341 +`pool.query()` may use two different connections and run in parallel. This is
342 +the basic structure:
343 +
344 +```js
345 +var mysql = require('mysql');
346 +var pool = mysql.createPool(...);
347 +
348 +pool.getConnection(function(err, connection) {
349 + if (err) throw err; // not connected!
350 +
351 + // Use the connection
352 + connection.query('SELECT something FROM sometable', function (error, results, fields) {
353 + // When done with the connection, release it.
354 + connection.release();
355 +
356 + // Handle error after the release.
357 + if (error) throw error;
358 +
359 + // Don't use the connection here, it has been returned to the pool.
360 + });
361 +});
362 +```
363 +
364 +If you would like to close the connection and remove it from the pool, use
365 +`connection.destroy()` instead. The pool will create a new connection the next
366 +time one is needed.
367 +
368 +Connections are lazily created by the pool. If you configure the pool to allow
369 +up to 100 connections, but only ever use 5 simultaneously, only 5 connections
370 +will be made. Connections are also cycled round-robin style, with connections
371 +being taken from the top of the pool and returning to the bottom.
372 +
373 +When a previous connection is retrieved from the pool, a ping packet is sent
374 +to the server to check if the connection is still good.
375 +
376 +## Pool options
377 +
378 +Pools accept all the same [options as a connection](#connection-options).
379 +When creating a new connection, the options are simply passed to the connection
380 +constructor. In addition to those options pools accept a few extras:
381 +
382 +* `acquireTimeout`: The milliseconds before a timeout occurs during the connection
383 + acquisition. This is slightly different from `connectTimeout`, because acquiring
384 + a pool connection does not always involve making a connection. (Default: `10000`)
385 +* `waitForConnections`: Determines the pool's action when no connections are
386 + available and the limit has been reached. If `true`, the pool will queue the
387 + connection request and call it when one becomes available. If `false`, the
388 + pool will immediately call back with an error. (Default: `true`)
389 +* `connectionLimit`: The maximum number of connections to create at once.
390 + (Default: `10`)
391 +* `queueLimit`: The maximum number of connection requests the pool will queue
392 + before returning an error from `getConnection`. If set to `0`, there is no
393 + limit to the number of queued connection requests. (Default: `0`)
394 +
395 +## Pool events
396 +
397 +### acquire
398 +
399 +The pool will emit an `acquire` event when a connection is acquired from the pool.
400 +This is called after all acquiring activity has been performed on the connection,
401 +right before the connection is handed to the callback of the acquiring code.
402 +
403 +```js
404 +pool.on('acquire', function (connection) {
405 + console.log('Connection %d acquired', connection.threadId);
406 +});
407 +```
408 +
409 +### connection
410 +
411 +The pool will emit a `connection` event when a new connection is made within the pool.
412 +If you need to set session variables on the connection before it gets used, you can
413 +listen to the `connection` event.
414 +
415 +```js
416 +pool.on('connection', function (connection) {
417 + connection.query('SET SESSION auto_increment_increment=1')
418 +});
419 +```
420 +
421 +### enqueue
422 +
423 +The pool will emit an `enqueue` event when a callback has been queued to wait for
424 +an available connection.
425 +
426 +```js
427 +pool.on('enqueue', function () {
428 + console.log('Waiting for available connection slot');
429 +});
430 +```
431 +
432 +### release
433 +
434 +The pool will emit a `release` event when a connection is released back to the
435 +pool. This is called after all release activity has been performed on the connection,
436 +so the connection will be listed as free at the time of the event.
437 +
438 +```js
439 +pool.on('release', function (connection) {
440 + console.log('Connection %d released', connection.threadId);
441 +});
442 +```
443 +
444 +## Closing all the connections in a pool
445 +
446 +When you are done using the pool, you have to end all the connections or the
447 +Node.js event loop will stay active until the connections are closed by the
448 +MySQL server. This is typically done if the pool is used in a script or when
449 +trying to gracefully shutdown a server. To end all the connections in the
450 +pool, use the `end` method on the pool:
451 +
452 +```js
453 +pool.end(function (err) {
454 + // all connections in the pool have ended
455 +});
456 +```
457 +
458 +The `end` method takes an _optional_ callback that you can use to know when
459 +all the connections are ended.
460 +
461 +**Once `pool.end` is called, `pool.getConnection` and other operations
462 +can no longer be performed.** Wait until all connections in the pool are
463 +released before calling `pool.end`. If you use the shortcut method
464 +`pool.query`, in place of `pool.getConnection``connection.query`
465 +`connection.release`, wait until it completes.
466 +
467 +`pool.end` calls `connection.end` on every active connection in the pool.
468 +This queues a `QUIT` packet on the connection and sets a flag to prevent
469 +`pool.getConnection` from creating new connections. All commands / queries
470 +already in progress will complete, but new commands won't execute.
471 +
472 +## PoolCluster
473 +
474 +PoolCluster provides multiple hosts connection. (group & retry & selector)
475 +
476 +```js
477 +// create
478 +var poolCluster = mysql.createPoolCluster();
479 +
480 +// add configurations (the config is a pool config object)
481 +poolCluster.add(config); // add configuration with automatic name
482 +poolCluster.add('MASTER', masterConfig); // add a named configuration
483 +poolCluster.add('SLAVE1', slave1Config);
484 +poolCluster.add('SLAVE2', slave2Config);
485 +
486 +// remove configurations
487 +poolCluster.remove('SLAVE2'); // By nodeId
488 +poolCluster.remove('SLAVE*'); // By target group : SLAVE1-2
489 +
490 +// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default)
491 +poolCluster.getConnection(function (err, connection) {});
492 +
493 +// Target Group : MASTER, Selector : round-robin
494 +poolCluster.getConnection('MASTER', function (err, connection) {});
495 +
496 +// Target Group : SLAVE1-2, Selector : order
497 +// If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster)
498 +poolCluster.on('remove', function (nodeId) {
499 + console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1
500 +});
501 +
502 +// A pattern can be passed with * as wildcard
503 +poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) {});
504 +
505 +// The pattern can also be a regular expression
506 +poolCluster.getConnection(/^SLAVE[12]$/, function (err, connection) {});
507 +
508 +// of namespace : of(pattern, selector)
509 +poolCluster.of('*').getConnection(function (err, connection) {});
510 +
511 +var pool = poolCluster.of('SLAVE*', 'RANDOM');
512 +pool.getConnection(function (err, connection) {});
513 +pool.getConnection(function (err, connection) {});
514 +pool.query(function (error, results, fields) {});
515 +
516 +// close all connections
517 +poolCluster.end(function (err) {
518 + // all connections in the pool cluster have ended
519 +});
520 +```
521 +
522 +### PoolCluster options
523 +
524 +* `canRetry`: If `true`, `PoolCluster` will attempt to reconnect when connection fails. (Default: `true`)
525 +* `removeNodeErrorCount`: If connection fails, node's `errorCount` increases.
526 + When `errorCount` is greater than `removeNodeErrorCount`, remove a node in the `PoolCluster`. (Default: `5`)
527 +* `restoreNodeTimeout`: If connection fails, specifies the number of milliseconds
528 + before another connection attempt will be made. If set to `0`, then node will be
529 + removed instead and never re-used. (Default: `0`)
530 +* `defaultSelector`: The default selector. (Default: `RR`)
531 + * `RR`: Select one alternately. (Round-Robin)
532 + * `RANDOM`: Select the node by random function.
533 + * `ORDER`: Select the first node available unconditionally.
534 +
535 +```js
536 +var clusterConfig = {
537 + removeNodeErrorCount: 1, // Remove the node immediately when connection fails.
538 + defaultSelector: 'ORDER'
539 +};
540 +
541 +var poolCluster = mysql.createPoolCluster(clusterConfig);
542 +```
543 +
544 +## Switching users and altering connection state
545 +
546 +MySQL offers a changeUser command that allows you to alter the current user and
547 +other aspects of the connection without shutting down the underlying socket:
548 +
549 +```js
550 +connection.changeUser({user : 'john'}, function(err) {
551 + if (err) throw err;
552 +});
553 +```
554 +
555 +The available options for this feature are:
556 +
557 +* `user`: The name of the new user (defaults to the previous one).
558 +* `password`: The password of the new user (defaults to the previous one).
559 +* `charset`: The new charset (defaults to the previous one).
560 +* `database`: The new database (defaults to the previous one).
561 +
562 +A sometimes useful side effect of this functionality is that this function also
563 +resets any connection state (variables, transactions, etc.).
564 +
565 +Errors encountered during this operation are treated as fatal connection errors
566 +by this module.
567 +
568 +## Server disconnects
569 +
570 +You may lose the connection to a MySQL server due to network problems, the
571 +server timing you out, the server being restarted, or crashing. All of these
572 +events are considered fatal errors, and will have the `err.code =
573 +'PROTOCOL_CONNECTION_LOST'`. See the [Error Handling](#error-handling) section
574 +for more information.
575 +
576 +Re-connecting a connection is done by establishing a new connection. Once
577 +terminated, an existing connection object cannot be re-connected by design.
578 +
579 +With Pool, disconnected connections will be removed from the pool freeing up
580 +space for a new connection to be created on the next getConnection call.
581 +
582 +## Performing queries
583 +
584 +The most basic way to perform a query is to call the `.query()` method on an object
585 +(like a `Connection`, `Pool`, or `PoolNamespace` instance).
586 +
587 +The simplest form of .`query()` is `.query(sqlString, callback)`, where a SQL string
588 +is the first argument and the second is a callback:
589 +
590 +```js
591 +connection.query('SELECT * FROM `books` WHERE `author` = "David"', function (error, results, fields) {
592 + // error will be an Error if one occurred during the query
593 + // results will contain the results of the query
594 + // fields will contain information about the returned results fields (if any)
595 +});
596 +```
597 +
598 +The second form `.query(sqlString, values, callback)` comes when using
599 +placeholder values (see [escaping query values](#escaping-query-values)):
600 +
601 +```js
602 +connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
603 + // error will be an Error if one occurred during the query
604 + // results will contain the results of the query
605 + // fields will contain information about the returned results fields (if any)
606 +});
607 +```
608 +
609 +The third form `.query(options, callback)` comes when using various advanced
610 +options on the query, like [escaping query values](#escaping-query-values),
611 +[joins with overlapping column names](#joins-with-overlapping-column-names),
612 +[timeouts](#timeout), and [type casting](#type-casting).
613 +
614 +```js
615 +connection.query({
616 + sql: 'SELECT * FROM `books` WHERE `author` = ?',
617 + timeout: 40000, // 40s
618 + values: ['David']
619 +}, function (error, results, fields) {
620 + // error will be an Error if one occurred during the query
621 + // results will contain the results of the query
622 + // fields will contain information about the returned results fields (if any)
623 +});
624 +```
625 +
626 +Note that a combination of the second and third forms can be used where the
627 +placeholder values are passed as an argument and not in the options object.
628 +The `values` argument will override the `values` in the option object.
629 +
630 +```js
631 +connection.query({
632 + sql: 'SELECT * FROM `books` WHERE `author` = ?',
633 + timeout: 40000, // 40s
634 + },
635 + ['David'],
636 + function (error, results, fields) {
637 + // error will be an Error if one occurred during the query
638 + // results will contain the results of the query
639 + // fields will contain information about the returned results fields (if any)
640 + }
641 +);
642 +```
643 +
644 +If the query only has a single replacement character (`?`), and the value is
645 +not `null`, `undefined`, or an array, it can be passed directly as the second
646 +argument to `.query`:
647 +
648 +```js
649 +connection.query(
650 + 'SELECT * FROM `books` WHERE `author` = ?',
651 + 'David',
652 + function (error, results, fields) {
653 + // error will be an Error if one occurred during the query
654 + // results will contain the results of the query
655 + // fields will contain information about the returned results fields (if any)
656 + }
657 +);
658 +```
659 +
660 +## Escaping query values
661 +
662 +**Caution** These methods of escaping values only works when the
663 +[NO_BACKSLASH_ESCAPES](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_backslash_escapes)
664 +SQL mode is disabled (which is the default state for MySQL servers).
665 +
666 +In order to avoid SQL Injection attacks, you should always escape any user
667 +provided data before using it inside a SQL query. You can do so using the
668 +`mysql.escape()`, `connection.escape()` or `pool.escape()` methods:
669 +
670 +```js
671 +var userId = 'some user provided value';
672 +var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
673 +connection.query(sql, function (error, results, fields) {
674 + if (error) throw error;
675 + // ...
676 +});
677 +```
678 +
679 +Alternatively, you can use `?` characters as placeholders for values you would
680 +like to have escaped like this:
681 +
682 +```js
683 +connection.query('SELECT * FROM users WHERE id = ?', [userId], function (error, results, fields) {
684 + if (error) throw error;
685 + // ...
686 +});
687 +```
688 +
689 +Multiple placeholders are mapped to values in the same order as passed. For example,
690 +in the following query `foo` equals `a`, `bar` equals `b`, `baz` equals `c`, and
691 +`id` will be `userId`:
692 +
693 +```js
694 +connection.query('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', ['a', 'b', 'c', userId], function (error, results, fields) {
695 + if (error) throw error;
696 + // ...
697 +});
698 +```
699 +
700 +This looks similar to prepared statements in MySQL, however it really just uses
701 +the same `connection.escape()` method internally.
702 +
703 +**Caution** This also differs from prepared statements in that all `?` are
704 +replaced, even those contained in comments and strings.
705 +
706 +Different value types are escaped differently, here is how:
707 +
708 +* Numbers are left untouched
709 +* Booleans are converted to `true` / `false`
710 +* Date objects are converted to `'YYYY-mm-dd HH:ii:ss'` strings
711 +* Buffers are converted to hex strings, e.g. `X'0fa5'`
712 +* Strings are safely escaped
713 +* Arrays are turned into list, e.g. `['a', 'b']` turns into `'a', 'b'`
714 +* Nested arrays are turned into grouped lists (for bulk inserts), e.g. `[['a',
715 + 'b'], ['c', 'd']]` turns into `('a', 'b'), ('c', 'd')`
716 +* Objects that have a `toSqlString` method will have `.toSqlString()` called
717 + and the returned value is used as the raw SQL.
718 +* Objects are turned into `key = 'val'` pairs for each enumerable property on
719 + the object. If the property's value is a function, it is skipped; if the
720 + property's value is an object, toString() is called on it and the returned
721 + value is used.
722 +* `undefined` / `null` are converted to `NULL`
723 +* `NaN` / `Infinity` are left as-is. MySQL does not support these, and trying
724 + to insert them as values will trigger MySQL errors until they implement
725 + support.
726 +
727 +This escaping allows you to do neat things like this:
728 +
729 +```js
730 +var post = {id: 1, title: 'Hello MySQL'};
731 +var query = connection.query('INSERT INTO posts SET ?', post, function (error, results, fields) {
732 + if (error) throw error;
733 + // Neat!
734 +});
735 +console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
736 +```
737 +
738 +And the `toSqlString` method allows you to form complex queries with functions:
739 +
740 +```js
741 +var CURRENT_TIMESTAMP = { toSqlString: function() { return 'CURRENT_TIMESTAMP()'; } };
742 +var sql = mysql.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]);
743 +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42
744 +```
745 +
746 +To generate objects with a `toSqlString` method, the `mysql.raw()` method can
747 +be used. This creates an object that will be left un-touched when using in a `?`
748 +placeholder, useful for using functions as dynamic values:
749 +
750 +**Caution** The string provided to `mysql.raw()` will skip all escaping
751 +functions when used, so be careful when passing in unvalidated input.
752 +
753 +```js
754 +var CURRENT_TIMESTAMP = mysql.raw('CURRENT_TIMESTAMP()');
755 +var sql = mysql.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]);
756 +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42
757 +```
758 +
759 +If you feel the need to escape queries by yourself, you can also use the escaping
760 +function directly:
761 +
762 +```js
763 +var query = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL");
764 +
765 +console.log(query); // SELECT * FROM posts WHERE title='Hello MySQL'
766 +```
767 +
768 +## Escaping query identifiers
769 +
770 +If you can't trust an SQL identifier (database / table / column name) because it is
771 +provided by a user, you should escape it with `mysql.escapeId(identifier)`,
772 +`connection.escapeId(identifier)` or `pool.escapeId(identifier)` like this:
773 +
774 +```js
775 +var sorter = 'date';
776 +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter);
777 +connection.query(sql, function (error, results, fields) {
778 + if (error) throw error;
779 + // ...
780 +});
781 +```
782 +
783 +It also supports adding qualified identifiers. It will escape both parts.
784 +
785 +```js
786 +var sorter = 'date';
787 +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId('posts.' + sorter);
788 +// -> SELECT * FROM posts ORDER BY `posts`.`date`
789 +```
790 +
791 +If you do not want to treat `.` as qualified identifiers, you can set the second
792 +argument to `true` in order to keep the string as a literal identifier:
793 +
794 +```js
795 +var sorter = 'date.2';
796 +var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter, true);
797 +// -> SELECT * FROM posts ORDER BY `date.2`
798 +```
799 +
800 +Alternatively, you can use `??` characters as placeholders for identifiers you would
801 +like to have escaped like this:
802 +
803 +```js
804 +var userId = 1;
805 +var columns = ['username', 'email'];
806 +var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId], function (error, results, fields) {
807 + if (error) throw error;
808 + // ...
809 +});
810 +
811 +console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1
812 +```
813 +**Please note that this last character sequence is experimental and syntax might change**
814 +
815 +When you pass an Object to `.escape()` or `.query()`, `.escapeId()` is used to avoid SQL injection in object keys.
816 +
817 +### Preparing Queries
818 +
819 +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:
820 +
821 +```js
822 +var sql = "SELECT * FROM ?? WHERE ?? = ?";
823 +var inserts = ['users', 'id', userId];
824 +sql = mysql.format(sql, inserts);
825 +```
826 +
827 +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.
828 +
829 +### Custom format
830 +
831 +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.
832 +
833 +Here's an example of how to implement another format:
834 +
835 +```js
836 +connection.config.queryFormat = function (query, values) {
837 + if (!values) return query;
838 + return query.replace(/\:(\w+)/g, function (txt, key) {
839 + if (values.hasOwnProperty(key)) {
840 + return this.escape(values[key]);
841 + }
842 + return txt;
843 + }.bind(this));
844 +};
845 +
846 +connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
847 +```
848 +
849 +## Getting the id of an inserted row
850 +
851 +If you are inserting a row into a table with an auto increment primary key, you
852 +can retrieve the insert id like this:
853 +
854 +```js
855 +connection.query('INSERT INTO posts SET ?', {title: 'test'}, function (error, results, fields) {
856 + if (error) throw error;
857 + console.log(results.insertId);
858 +});
859 +```
860 +
861 +When dealing with big numbers (above JavaScript Number precision limit), you should
862 +consider enabling `supportBigNumbers` option to be able to read the insert id as a
863 +string, otherwise it will throw an error.
864 +
865 +This option is also required when fetching big numbers from the database, otherwise
866 +you will get values rounded to hundreds or thousands due to the precision limit.
867 +
868 +## Getting the number of affected rows
869 +
870 +You can get the number of affected rows from an insert, update or delete statement.
871 +
872 +```js
873 +connection.query('DELETE FROM posts WHERE title = "wrong"', function (error, results, fields) {
874 + if (error) throw error;
875 + console.log('deleted ' + results.affectedRows + ' rows');
876 +})
877 +```
878 +
879 +## Getting the number of changed rows
880 +
881 +You can get the number of changed rows from an update statement.
882 +
883 +"changedRows" differs from "affectedRows" in that it does not count updated rows
884 +whose values were not changed.
885 +
886 +```js
887 +connection.query('UPDATE posts SET ...', function (error, results, fields) {
888 + if (error) throw error;
889 + console.log('changed ' + results.changedRows + ' rows');
890 +})
891 +```
892 +
893 +## Getting the connection ID
894 +
895 +You can get the MySQL connection ID ("thread ID") of a given connection using the `threadId`
896 +property.
897 +
898 +```js
899 +connection.connect(function(err) {
900 + if (err) throw err;
901 + console.log('connected as id ' + connection.threadId);
902 +});
903 +```
904 +
905 +## Executing queries in parallel
906 +
907 +The MySQL protocol is sequential, this means that you need multiple connections
908 +to execute queries in parallel. You can use a Pool to manage connections, one
909 +simple approach is to create one connection per incoming http request.
910 +
911 +## Streaming query rows
912 +
913 +Sometimes you may want to select large quantities of rows and process each of
914 +them as they are received. This can be done like this:
915 +
916 +```js
917 +var query = connection.query('SELECT * FROM posts');
918 +query
919 + .on('error', function(err) {
920 + // Handle error, an 'end' event will be emitted after this as well
921 + })
922 + .on('fields', function(fields) {
923 + // the field packets for the rows to follow
924 + })
925 + .on('result', function(row) {
926 + // Pausing the connnection is useful if your processing involves I/O
927 + connection.pause();
928 +
929 + processRow(row, function() {
930 + connection.resume();
931 + });
932 + })
933 + .on('end', function() {
934 + // all rows have been received
935 + });
936 +```
937 +
938 +Please note a few things about the example above:
939 +
940 +* Usually you will want to receive a certain amount of rows before starting to
941 + throttle the connection using `pause()`. This number will depend on the
942 + amount and size of your rows.
943 +* `pause()` / `resume()` operate on the underlying socket and parser. You are
944 + guaranteed that no more `'result'` events will fire after calling `pause()`.
945 +* You MUST NOT provide a callback to the `query()` method when streaming rows.
946 +* The `'result'` event will fire for both rows as well as OK packets
947 + confirming the success of a INSERT/UPDATE query.
948 +* It is very important not to leave the result paused too long, or you may
949 + encounter `Error: Connection lost: The server closed the connection.`
950 + The time limit for this is determined by the
951 + [net_write_timeout setting](https://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_net_write_timeout)
952 + on your MySQL server.
953 +
954 +Additionally you may be interested to know that it is currently not possible to
955 +stream individual row columns, they will always be buffered up entirely. If you
956 +have a good use case for streaming large fields to and from MySQL, I'd love to
957 +get your thoughts and contributions on this.
958 +
959 +### Piping results with Streams
960 +
961 +The query object provides a convenience method `.stream([options])` that wraps
962 +query events into a [Readable Stream](http://nodejs.org/api/stream.html#stream_class_stream_readable)
963 +object. This stream can easily be piped downstream and provides automatic
964 +pause/resume, based on downstream congestion and the optional `highWaterMark`.
965 +The `objectMode` parameter of the stream is set to `true` and cannot be changed
966 +(if you need a byte stream, you will need to use a transform stream, like
967 +[objstream](https://www.npmjs.com/package/objstream) for example).
968 +
969 +For example, piping query results into another stream (with a max buffer of 5
970 +objects) is simply:
971 +
972 +```js
973 +connection.query('SELECT * FROM posts')
974 + .stream({highWaterMark: 5})
975 + .pipe(...);
976 +```
977 +
978 +## Multiple statement queries
979 +
980 +Support for multiple statements is disabled for security reasons (it allows for
981 +SQL injection attacks if values are not properly escaped). To use this feature
982 +you have to enable it for your connection:
983 +
984 +```js
985 +var connection = mysql.createConnection({multipleStatements: true});
986 +```
987 +
988 +Once enabled, you can execute multiple statement queries like any other query:
989 +
990 +```js
991 +connection.query('SELECT 1; SELECT 2', function (error, results, fields) {
992 + if (error) throw error;
993 + // `results` is an array with one element for every statement in the query:
994 + console.log(results[0]); // [{1: 1}]
995 + console.log(results[1]); // [{2: 2}]
996 +});
997 +```
998 +
999 +Additionally you can also stream the results of multiple statement queries:
1000 +
1001 +```js
1002 +var query = connection.query('SELECT 1; SELECT 2');
1003 +
1004 +query
1005 + .on('fields', function(fields, index) {
1006 + // the fields for the result rows that follow
1007 + })
1008 + .on('result', function(row, index) {
1009 + // index refers to the statement this result belongs to (starts at 0)
1010 + });
1011 +```
1012 +
1013 +If one of the statements in your query causes an error, the resulting Error
1014 +object contains a `err.index` property which tells you which statement caused
1015 +it. MySQL will also stop executing any remaining statements when an error
1016 +occurs.
1017 +
1018 +Please note that the interface for streaming multiple statement queries is
1019 +experimental and I am looking forward to feedback on it.
1020 +
1021 +## Stored procedures
1022 +
1023 +You can call stored procedures from your queries as with any other mysql driver.
1024 +If the stored procedure produces several result sets, they are exposed to you
1025 +the same way as the results for multiple statement queries.
1026 +
1027 +## Joins with overlapping column names
1028 +
1029 +When executing joins, you are likely to get result sets with overlapping column
1030 +names.
1031 +
1032 +By default, node-mysql will overwrite colliding column names in the
1033 +order the columns are received from MySQL, causing some of the received values
1034 +to be unavailable.
1035 +
1036 +However, you can also specify that you want your columns to be nested below
1037 +the table name like this:
1038 +
1039 +```js
1040 +var options = {sql: '...', nestTables: true};
1041 +connection.query(options, function (error, results, fields) {
1042 + if (error) throw error;
1043 + /* results will be an array like this now:
1044 + [{
1045 + table1: {
1046 + fieldA: '...',
1047 + fieldB: '...',
1048 + },
1049 + table2: {
1050 + fieldA: '...',
1051 + fieldB: '...',
1052 + },
1053 + }, ...]
1054 + */
1055 +});
1056 +```
1057 +
1058 +Or use a string separator to have your results merged.
1059 +
1060 +```js
1061 +var options = {sql: '...', nestTables: '_'};
1062 +connection.query(options, function (error, results, fields) {
1063 + if (error) throw error;
1064 + /* results will be an array like this now:
1065 + [{
1066 + table1_fieldA: '...',
1067 + table1_fieldB: '...',
1068 + table2_fieldA: '...',
1069 + table2_fieldB: '...',
1070 + }, ...]
1071 + */
1072 +});
1073 +```
1074 +
1075 +## Transactions
1076 +
1077 +Simple transaction support is available at the connection level:
1078 +
1079 +```js
1080 +connection.beginTransaction(function(err) {
1081 + if (err) { throw err; }
1082 + connection.query('INSERT INTO posts SET title=?', title, function (error, results, fields) {
1083 + if (error) {
1084 + return connection.rollback(function() {
1085 + throw error;
1086 + });
1087 + }
1088 +
1089 + var log = 'Post ' + results.insertId + ' added';
1090 +
1091 + connection.query('INSERT INTO log SET data=?', log, function (error, results, fields) {
1092 + if (error) {
1093 + return connection.rollback(function() {
1094 + throw error;
1095 + });
1096 + }
1097 + connection.commit(function(err) {
1098 + if (err) {
1099 + return connection.rollback(function() {
1100 + throw err;
1101 + });
1102 + }
1103 + console.log('success!');
1104 + });
1105 + });
1106 + });
1107 +});
1108 +```
1109 +Please note that beginTransaction(), commit() and rollback() are simply convenience
1110 +functions that execute the START TRANSACTION, COMMIT, and ROLLBACK commands respectively.
1111 +It is important to understand that many commands in MySQL can cause an implicit commit,
1112 +as described [in the MySQL documentation](http://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html)
1113 +
1114 +## Ping
1115 +
1116 +A ping packet can be sent over a connection using the `connection.ping` method. This
1117 +method will send a ping packet to the server and when the server responds, the callback
1118 +will fire. If an error occurred, the callback will fire with an error argument.
1119 +
1120 +```js
1121 +connection.ping(function (err) {
1122 + if (err) throw err;
1123 + console.log('Server responded to ping');
1124 +})
1125 +```
1126 +
1127 +## Timeouts
1128 +
1129 +Every operation takes an optional inactivity timeout option. This allows you to
1130 +specify appropriate timeouts for operations. It is important to note that these
1131 +timeouts are not part of the MySQL protocol, and rather timeout operations through
1132 +the client. This means that when a timeout is reached, the connection it occurred
1133 +on will be destroyed and no further operations can be performed.
1134 +
1135 +```js
1136 +// Kill query after 60s
1137 +connection.query({sql: 'SELECT COUNT(*) AS count FROM big_table', timeout: 60000}, function (error, results, fields) {
1138 + if (error && error.code === 'PROTOCOL_SEQUENCE_TIMEOUT') {
1139 + throw new Error('too long to count table rows!');
1140 + }
1141 +
1142 + if (error) {
1143 + throw error;
1144 + }
1145 +
1146 + console.log(results[0].count + ' rows');
1147 +});
1148 +```
1149 +
1150 +## Error handling
1151 +
1152 +This module comes with a consistent approach to error handling that you should
1153 +review carefully in order to write solid applications.
1154 +
1155 +Most errors created by this module are instances of the JavaScript [Error][]
1156 +object. Additionally they typically come with two extra properties:
1157 +
1158 +* `err.code`: Either a [MySQL server error][] (e.g.
1159 + `'ER_ACCESS_DENIED_ERROR'`), a Node.js error (e.g. `'ECONNREFUSED'`) or an
1160 + internal error (e.g. `'PROTOCOL_CONNECTION_LOST'`).
1161 +* `err.fatal`: Boolean, indicating if this error is terminal to the connection
1162 + object. If the error is not from a MySQL protocol operation, this properly
1163 + will not be defined.
1164 +* `err.sql`: String, contains the full SQL of the failed query. This can be
1165 + useful when using a higher level interface like an ORM that is generating
1166 + the queries.
1167 +* `err.sqlState`: String, contains the five-character SQLSTATE value. Only populated from [MySQL server error][].
1168 +* `err.sqlMessage`: String, contains the message string that provides a
1169 + textual description of the error. Only populated from [MySQL server error][].
1170 +
1171 +[Error]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error
1172 +[MySQL server error]: http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1173 +
1174 +Fatal errors are propagated to *all* pending callbacks. In the example below, a
1175 +fatal error is triggered by trying to connect to an invalid port. Therefore the
1176 +error object is propagated to both pending callbacks:
1177 +
1178 +```js
1179 +var connection = require('mysql').createConnection({
1180 + port: 84943, // WRONG PORT
1181 +});
1182 +
1183 +connection.connect(function(err) {
1184 + console.log(err.code); // 'ECONNREFUSED'
1185 + console.log(err.fatal); // true
1186 +});
1187 +
1188 +connection.query('SELECT 1', function (error, results, fields) {
1189 + console.log(error.code); // 'ECONNREFUSED'
1190 + console.log(error.fatal); // true
1191 +});
1192 +```
1193 +
1194 +Normal errors however are only delegated to the callback they belong to. So in
1195 +the example below, only the first callback receives an error, the second query
1196 +works as expected:
1197 +
1198 +```js
1199 +connection.query('USE name_of_db_that_does_not_exist', function (error, results, fields) {
1200 + console.log(error.code); // 'ER_BAD_DB_ERROR'
1201 +});
1202 +
1203 +connection.query('SELECT 1', function (error, results, fields) {
1204 + console.log(error); // null
1205 + console.log(results.length); // 1
1206 +});
1207 +```
1208 +
1209 +Last but not least: If a fatal errors occurs and there are no pending
1210 +callbacks, or a normal error occurs which has no callback belonging to it, the
1211 +error is emitted as an `'error'` event on the connection object. This is
1212 +demonstrated in the example below:
1213 +
1214 +```js
1215 +connection.on('error', function(err) {
1216 + console.log(err.code); // 'ER_BAD_DB_ERROR'
1217 +});
1218 +
1219 +connection.query('USE name_of_db_that_does_not_exist');
1220 +```
1221 +
1222 +Note: `'error'` events are special in node. If they occur without an attached
1223 +listener, a stack trace is printed and your process is killed.
1224 +
1225 +**tl;dr:** This module does not want you to deal with silent failures. You
1226 +should always provide callbacks to your method calls. If you want to ignore
1227 +this advice and suppress unhandled errors, you can do this:
1228 +
1229 +```js
1230 +// I am Chuck Norris:
1231 +connection.on('error', function() {});
1232 +```
1233 +
1234 +## Exception Safety
1235 +
1236 +This module is exception safe. That means you can continue to use it, even if
1237 +one of your callback functions throws an error which you're catching using
1238 +'uncaughtException' or a domain.
1239 +
1240 +## Type casting
1241 +
1242 +For your convenience, this driver will cast mysql types into native JavaScript
1243 +types by default. The following mappings exist:
1244 +
1245 +### Number
1246 +
1247 +* TINYINT
1248 +* SMALLINT
1249 +* INT
1250 +* MEDIUMINT
1251 +* YEAR
1252 +* FLOAT
1253 +* DOUBLE
1254 +
1255 +### Date
1256 +
1257 +* TIMESTAMP
1258 +* DATE
1259 +* DATETIME
1260 +
1261 +### Buffer
1262 +
1263 +* TINYBLOB
1264 +* MEDIUMBLOB
1265 +* LONGBLOB
1266 +* BLOB
1267 +* BINARY
1268 +* VARBINARY
1269 +* BIT (last byte will be filled with 0 bits as necessary)
1270 +
1271 +### String
1272 +
1273 +**Note** text in the binary character set is returned as `Buffer`, rather
1274 +than a string.
1275 +
1276 +* CHAR
1277 +* VARCHAR
1278 +* TINYTEXT
1279 +* MEDIUMTEXT
1280 +* LONGTEXT
1281 +* TEXT
1282 +* ENUM
1283 +* SET
1284 +* DECIMAL (may exceed float precision)
1285 +* BIGINT (may exceed float precision)
1286 +* TIME (could be mapped to Date, but what date would be set?)
1287 +* GEOMETRY (never used those, get in touch if you do)
1288 +
1289 +It is not recommended (and may go away / change in the future) to disable type
1290 +casting, but you can currently do so on either the connection:
1291 +
1292 +```js
1293 +var connection = require('mysql').createConnection({typeCast: false});
1294 +```
1295 +
1296 +Or on the query level:
1297 +
1298 +```js
1299 +var options = {sql: '...', typeCast: false};
1300 +var query = connection.query(options, function (error, results, fields) {
1301 + if (error) throw error;
1302 + // ...
1303 +});
1304 +```
1305 +
1306 +You can also pass a function and handle type casting yourself. You're given some
1307 +column information like database, table and name and also type and length. If you
1308 +just want to apply a custom type casting to a specific type you can do it and then
1309 +fallback to the default. Here's an example of converting `TINYINT(1)` to boolean:
1310 +
1311 +```js
1312 +connection.query({
1313 + sql: '...',
1314 + typeCast: function (field, next) {
1315 + if (field.type == 'TINY' && field.length == 1) {
1316 + return (field.string() == '1'); // 1 = true, 0 = false
1317 + }
1318 + return next();
1319 + }
1320 +});
1321 +```
1322 +__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)__
1323 +
1324 +```
1325 +field.string()
1326 +field.buffer()
1327 +field.geometry()
1328 +```
1329 +are aliases for
1330 +```
1331 +parser.parseLengthCodedString()
1332 +parser.parseLengthCodedBuffer()
1333 +parser.parseGeometryValue()
1334 +```
1335 +__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)__
1336 +
1337 +
1338 +## Connection Flags
1339 +
1340 +If, for any reason, you would like to change the default connection flags, you
1341 +can use the connection option `flags`. Pass a string with a comma separated list
1342 +of items to add to the default flags. If you don't want a default flag to be used
1343 +prepend the flag with a minus sign. To add a flag that is not in the default list,
1344 +just write the flag name, or prefix it with a plus (case insensitive).
1345 +
1346 +**Please note that some available flags that are not supported (e.g.: Compression),
1347 +are still not allowed to be specified.**
1348 +
1349 +### Example
1350 +
1351 +The next example blacklists FOUND_ROWS flag from default connection flags.
1352 +
1353 +```js
1354 +var connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS");
1355 +```
1356 +
1357 +### Default Flags
1358 +
1359 +The following flags are sent by default on a new connection:
1360 +
1361 +- `CONNECT_WITH_DB` - Ability to specify the database on connection.
1362 +- `FOUND_ROWS` - Send the found rows instead of the affected rows as `affectedRows`.
1363 +- `IGNORE_SIGPIPE` - Old; no effect.
1364 +- `IGNORE_SPACE` - Let the parser ignore spaces before the `(` in queries.
1365 +- `LOCAL_FILES` - Can use `LOAD DATA LOCAL`.
1366 +- `LONG_FLAG`
1367 +- `LONG_PASSWORD` - Use the improved version of Old Password Authentication.
1368 +- `MULTI_RESULTS` - Can handle multiple resultsets for COM_QUERY.
1369 +- `ODBC` Old; no effect.
1370 +- `PROTOCOL_41` - Uses the 4.1 protocol.
1371 +- `PS_MULTI_RESULTS` - Can handle multiple resultsets for COM_STMT_EXECUTE.
1372 +- `RESERVED` - Old flag for the 4.1 protocol.
1373 +- `SECURE_CONNECTION` - Support native 4.1 authentication.
1374 +- `TRANSACTIONS` - Asks for the transaction status flags.
1375 +
1376 +In addition, the following flag will be sent if the option `multipleStatements`
1377 +is set to `true`:
1378 +
1379 +- `MULTI_STATEMENTS` - The client may send multiple statement per query or
1380 + statement prepare.
1381 +
1382 +### Other Available Flags
1383 +
1384 +There are other flags available. They may or may not function, but are still
1385 +available to specify.
1386 +
1387 +- `COMPRESS`
1388 +- `INTERACTIVE`
1389 +- `NO_SCHEMA`
1390 +- `PLUGIN_AUTH`
1391 +- `REMEMBER_OPTIONS`
1392 +- `SSL`
1393 +- `SSL_VERIFY_SERVER_CERT`
1394 +
1395 +## Debugging and reporting problems
1396 +
1397 +If you are running into problems, one thing that may help is enabling the
1398 +`debug` mode for the connection:
1399 +
1400 +```js
1401 +var connection = mysql.createConnection({debug: true});
1402 +```
1403 +
1404 +This will print all incoming and outgoing packets on stdout. You can also restrict debugging to
1405 +packet types by passing an array of types to debug:
1406 +
1407 +```js
1408 +var connection = mysql.createConnection({debug: ['ComQueryPacket', 'RowDataPacket']});
1409 +```
1410 +
1411 +to restrict debugging to the query and data packets.
1412 +
1413 +If that does not help, feel free to open a GitHub issue. A good GitHub issue
1414 +will have:
1415 +
1416 +* The minimal amount of code required to reproduce the problem (if possible)
1417 +* As much debugging output and information about your environment (mysql
1418 + version, node version, os, etc.) as you can gather.
1419 +
1420 +## Security issues
1421 +
1422 +Security issues should not be first reported through GitHub or another public
1423 +forum, but kept private in order for the collaborators to assess the report
1424 +and either (a) devise a fix and plan a release date or (b) assert that it is
1425 +not a security issue (in which case it can be posted in a public forum, like
1426 +a GitHub issue).
1427 +
1428 +The primary private forum is email, either by emailing the module's author or
1429 +opening a GitHub issue simply asking to whom a security issues should be
1430 +addressed to without disclosing the issue or type of issue.
1431 +
1432 +An ideal report would include a clear indication of what the security issue is
1433 +and how it would be exploited, ideally with an accompaning proof of concept
1434 +("PoC") for collaborators to work again and validate potentional fixes against.
1435 +
1436 +## Contributing
1437 +
1438 +This project welcomes contributions from the community. Contributions are
1439 +accepted using GitHub pull requests. If you're not familiar with making
1440 +GitHub pull requests, please refer to the
1441 +[GitHub documentation "Creating a pull request"](https://help.github.com/articles/creating-a-pull-request/).
1442 +
1443 +For a good pull request, we ask you provide the following:
1444 +
1445 +1. Try to include a clear description of your pull request in the description.
1446 + It should include the basic "what" and "why"s for the request.
1447 +2. The tests should pass as best as you can. See the [Running tests](#running-tests)
1448 + section on how to run the different tests. GitHub will automatically run
1449 + the tests as well, to act as a safety net.
1450 +3. The pull request should include tests for the change. A new feature should
1451 + have tests for the new feature and bug fixes should include a test that fails
1452 + without the corresponding code change and passes after they are applied.
1453 + The command `npm run test-cov` will generate a `coverage/` folder that
1454 + contains HTML pages of the code coverage, to better understand if everything
1455 + you're adding is being tested.
1456 +4. If the pull request is a new feature, please be sure to include all
1457 + appropriate documentation additions in the `Readme.md` file as well.
1458 +5. To help ensure that your code is similar in style to the existing code,
1459 + run the command `npm run lint` and fix any displayed issues.
1460 +
1461 +## Running tests
1462 +
1463 +The test suite is split into two parts: unit tests and integration tests.
1464 +The unit tests run on any machine while the integration tests require a
1465 +MySQL server instance to be setup.
1466 +
1467 +### Running unit tests
1468 +
1469 +```sh
1470 +$ FILTER=unit npm test
1471 +```
1472 +
1473 +### Running integration tests
1474 +
1475 +Set the environment variables `MYSQL_DATABASE`, `MYSQL_HOST`, `MYSQL_PORT`,
1476 +`MYSQL_USER` and `MYSQL_PASSWORD`. `MYSQL_SOCKET` can also be used in place
1477 +of `MYSQL_HOST` and `MYSQL_PORT` to connect over a UNIX socket. Then run
1478 +`npm test`.
1479 +
1480 +For example, if you have an installation of mysql running on localhost:3306
1481 +and no password set for the `root` user, run:
1482 +
1483 +```sh
1484 +$ mysql -u root -e "CREATE DATABASE IF NOT EXISTS node_mysql_test"
1485 +$ MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_DATABASE=node_mysql_test MYSQL_USER=root MYSQL_PASSWORD= FILTER=integration npm test
1486 +```
1487 +
1488 +## Todo
1489 +
1490 +* Prepared statements
1491 +* Support for encodings other than UTF-8 / ASCII
1492 +
1493 +[npm-image]: https://img.shields.io/npm/v/mysql.svg
1494 +[npm-url]: https://npmjs.org/package/mysql
1495 +[node-version-image]: https://img.shields.io/node/v/mysql.svg
1496 +[node-version-url]: https://nodejs.org/en/download/
1497 +[travis-image]: https://img.shields.io/travis/mysqljs/mysql/master.svg?label=linux
1498 +[travis-url]: https://travis-ci.org/mysqljs/mysql
1499 +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/node-mysql/master.svg?label=windows
1500 +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/node-mysql
1501 +[coveralls-image]: https://img.shields.io/coveralls/mysqljs/mysql/master.svg
1502 +[coveralls-url]: https://coveralls.io/r/mysqljs/mysql?branch=master
1503 +[downloads-image]: https://img.shields.io/npm/dm/mysql.svg
1504 +[downloads-url]: https://npmjs.org/package/mysql
1 +var Classes = Object.create(null);
2 +
3 +/**
4 + * Create a new Connection instance.
5 + * @param {object|string} config Configuration or connection string for new MySQL connection
6 + * @return {Connection} A new MySQL connection
7 + * @public
8 + */
9 +exports.createConnection = function createConnection(config) {
10 + var Connection = loadClass('Connection');
11 + var ConnectionConfig = loadClass('ConnectionConfig');
12 +
13 + return new Connection({config: new ConnectionConfig(config)});
14 +};
15 +
16 +/**
17 + * Create a new Pool instance.
18 + * @param {object|string} config Configuration or connection string for new MySQL connections
19 + * @return {Pool} A new MySQL pool
20 + * @public
21 + */
22 +exports.createPool = function createPool(config) {
23 + var Pool = loadClass('Pool');
24 + var PoolConfig = loadClass('PoolConfig');
25 +
26 + return new Pool({config: new PoolConfig(config)});
27 +};
28 +
29 +/**
30 + * Create a new PoolCluster instance.
31 + * @param {object} [config] Configuration for pool cluster
32 + * @return {PoolCluster} New MySQL pool cluster
33 + * @public
34 + */
35 +exports.createPoolCluster = function createPoolCluster(config) {
36 + var PoolCluster = loadClass('PoolCluster');
37 +
38 + return new PoolCluster(config);
39 +};
40 +
41 +/**
42 + * Create a new Query instance.
43 + * @param {string} sql The SQL for the query
44 + * @param {array} [values] Any values to insert into placeholders in sql
45 + * @param {function} [callback] The callback to use when query is complete
46 + * @return {Query} New query object
47 + * @public
48 + */
49 +exports.createQuery = function createQuery(sql, values, callback) {
50 + var Connection = loadClass('Connection');
51 +
52 + return Connection.createQuery(sql, values, callback);
53 +};
54 +
55 +/**
56 + * Escape a value for SQL.
57 + * @param {*} value The value to escape
58 + * @param {boolean} [stringifyObjects=false] Setting if objects should be stringified
59 + * @param {string} [timeZone=local] Setting for time zone to use for Date conversion
60 + * @return {string} Escaped string value
61 + * @public
62 + */
63 +exports.escape = function escape(value, stringifyObjects, timeZone) {
64 + var SqlString = loadClass('SqlString');
65 +
66 + return SqlString.escape(value, stringifyObjects, timeZone);
67 +};
68 +
69 +/**
70 + * Escape an identifier for SQL.
71 + * @param {*} value The value to escape
72 + * @param {boolean} [forbidQualified=false] Setting to treat '.' as part of identifier
73 + * @return {string} Escaped string value
74 + * @public
75 + */
76 +exports.escapeId = function escapeId(value, forbidQualified) {
77 + var SqlString = loadClass('SqlString');
78 +
79 + return SqlString.escapeId(value, forbidQualified);
80 +};
81 +
82 +/**
83 + * Format SQL and replacement values into a SQL string.
84 + * @param {string} sql The SQL for the query
85 + * @param {array} [values] Any values to insert into placeholders in sql
86 + * @param {boolean} [stringifyObjects=false] Setting if objects should be stringified
87 + * @param {string} [timeZone=local] Setting for time zone to use for Date conversion
88 + * @return {string} Formatted SQL string
89 + * @public
90 + */
91 +exports.format = function format(sql, values, stringifyObjects, timeZone) {
92 + var SqlString = loadClass('SqlString');
93 +
94 + return SqlString.format(sql, values, stringifyObjects, timeZone);
95 +};
96 +
97 +/**
98 + * Wrap raw SQL strings from escape overriding.
99 + * @param {string} sql The raw SQL
100 + * @return {object} Wrapped object
101 + * @public
102 + */
103 +exports.raw = function raw(sql) {
104 + var SqlString = loadClass('SqlString');
105 +
106 + return SqlString.raw(sql);
107 +};
108 +
109 +/**
110 + * The type constants.
111 + * @public
112 + */
113 +Object.defineProperty(exports, 'Types', {
114 + get: loadClass.bind(null, 'Types')
115 +});
116 +
117 +/**
118 + * Load the given class.
119 + * @param {string} className Name of class to default
120 + * @return {function|object} Class constructor or exports
121 + * @private
122 + */
123 +function loadClass(className) {
124 + var Class = Classes[className];
125 +
126 + if (Class !== undefined) {
127 + return Class;
128 + }
129 +
130 + // This uses a switch for static require analysis
131 + switch (className) {
132 + case 'Connection':
133 + Class = require('./lib/Connection');
134 + break;
135 + case 'ConnectionConfig':
136 + Class = require('./lib/ConnectionConfig');
137 + break;
138 + case 'Pool':
139 + Class = require('./lib/Pool');
140 + break;
141 + case 'PoolCluster':
142 + Class = require('./lib/PoolCluster');
143 + break;
144 + case 'PoolConfig':
145 + Class = require('./lib/PoolConfig');
146 + break;
147 + case 'SqlString':
148 + Class = require('./lib/protocol/SqlString');
149 + break;
150 + case 'Types':
151 + Class = require('./lib/protocol/constants/types');
152 + break;
153 + default:
154 + throw new Error('Cannot find class \'' + className + '\'');
155 + }
156 +
157 + // Store to prevent invoking require()
158 + Classes[className] = Class;
159 +
160 + return Class;
161 +}
1 +var Crypto = require('crypto');
2 +var Events = require('events');
3 +var Net = require('net');
4 +var tls = require('tls');
5 +var ConnectionConfig = require('./ConnectionConfig');
6 +var Protocol = require('./protocol/Protocol');
7 +var SqlString = require('./protocol/SqlString');
8 +var Query = require('./protocol/sequences/Query');
9 +var Util = require('util');
10 +
11 +module.exports = Connection;
12 +Util.inherits(Connection, Events.EventEmitter);
13 +function Connection(options) {
14 + Events.EventEmitter.call(this);
15 +
16 + this.config = options.config;
17 +
18 + this._socket = options.socket;
19 + this._protocol = new Protocol({config: this.config, connection: this});
20 + this._connectCalled = false;
21 + this.state = 'disconnected';
22 + this.threadId = null;
23 +}
24 +
25 +Connection.createQuery = function createQuery(sql, values, callback) {
26 + if (sql instanceof Query) {
27 + return sql;
28 + }
29 +
30 + var cb = wrapCallbackInDomain(null, callback);
31 + var options = {};
32 +
33 + if (typeof sql === 'function') {
34 + cb = wrapCallbackInDomain(null, sql);
35 + return new Query(options, cb);
36 + }
37 +
38 + if (typeof sql === 'object') {
39 + for (var prop in sql) {
40 + options[prop] = sql[prop];
41 + }
42 +
43 + if (typeof values === 'function') {
44 + cb = wrapCallbackInDomain(null, values);
45 + } else if (values !== undefined) {
46 + options.values = values;
47 + }
48 +
49 + return new Query(options, cb);
50 + }
51 +
52 + options.sql = sql;
53 + options.values = values;
54 +
55 + if (typeof values === 'function') {
56 + cb = wrapCallbackInDomain(null, values);
57 + options.values = undefined;
58 + }
59 +
60 + if (cb === undefined && callback !== undefined) {
61 + throw new TypeError('argument callback must be a function when provided');
62 + }
63 +
64 + return new Query(options, cb);
65 +};
66 +
67 +Connection.prototype.connect = function connect(options, callback) {
68 + if (!callback && typeof options === 'function') {
69 + callback = options;
70 + options = {};
71 + }
72 +
73 + if (!this._connectCalled) {
74 + this._connectCalled = true;
75 +
76 + // Connect either via a UNIX domain socket or a TCP socket.
77 + this._socket = (this.config.socketPath)
78 + ? Net.createConnection(this.config.socketPath)
79 + : Net.createConnection(this.config.port, this.config.host);
80 +
81 + // Connect socket to connection domain
82 + if (Events.usingDomains) {
83 + this._socket.domain = this.domain;
84 + }
85 +
86 + var connection = this;
87 + this._protocol.on('data', function(data) {
88 + connection._socket.write(data);
89 + });
90 + this._socket.on('data', wrapToDomain(connection, function (data) {
91 + connection._protocol.write(data);
92 + }));
93 + this._protocol.on('end', function() {
94 + connection._socket.end();
95 + });
96 + this._socket.on('end', wrapToDomain(connection, function () {
97 + connection._protocol.end();
98 + }));
99 +
100 + this._socket.on('error', this._handleNetworkError.bind(this));
101 + this._socket.on('connect', this._handleProtocolConnect.bind(this));
102 + this._protocol.on('handshake', this._handleProtocolHandshake.bind(this));
103 + this._protocol.on('unhandledError', this._handleProtocolError.bind(this));
104 + this._protocol.on('drain', this._handleProtocolDrain.bind(this));
105 + this._protocol.on('end', this._handleProtocolEnd.bind(this));
106 + this._protocol.on('enqueue', this._handleProtocolEnqueue.bind(this));
107 +
108 + if (this.config.connectTimeout) {
109 + var handleConnectTimeout = this._handleConnectTimeout.bind(this);
110 +
111 + this._socket.setTimeout(this.config.connectTimeout, handleConnectTimeout);
112 + this._socket.once('connect', function() {
113 + this.setTimeout(0, handleConnectTimeout);
114 + });
115 + }
116 + }
117 +
118 + this._protocol.handshake(options, wrapCallbackInDomain(this, callback));
119 +};
120 +
121 +Connection.prototype.changeUser = function changeUser(options, callback) {
122 + if (!callback && typeof options === 'function') {
123 + callback = options;
124 + options = {};
125 + }
126 +
127 + this._implyConnect();
128 +
129 + var charsetNumber = (options.charset)
130 + ? ConnectionConfig.getCharsetNumber(options.charset)
131 + : this.config.charsetNumber;
132 +
133 + return this._protocol.changeUser({
134 + user : options.user || this.config.user,
135 + password : options.password || this.config.password,
136 + database : options.database || this.config.database,
137 + timeout : options.timeout,
138 + charsetNumber : charsetNumber,
139 + currentConfig : this.config
140 + }, wrapCallbackInDomain(this, callback));
141 +};
142 +
143 +Connection.prototype.beginTransaction = function beginTransaction(options, callback) {
144 + if (!callback && typeof options === 'function') {
145 + callback = options;
146 + options = {};
147 + }
148 +
149 + options = options || {};
150 + options.sql = 'START TRANSACTION';
151 + options.values = null;
152 +
153 + return this.query(options, callback);
154 +};
155 +
156 +Connection.prototype.commit = function commit(options, callback) {
157 + if (!callback && typeof options === 'function') {
158 + callback = options;
159 + options = {};
160 + }
161 +
162 + options = options || {};
163 + options.sql = 'COMMIT';
164 + options.values = null;
165 +
166 + return this.query(options, callback);
167 +};
168 +
169 +Connection.prototype.rollback = function rollback(options, callback) {
170 + if (!callback && typeof options === 'function') {
171 + callback = options;
172 + options = {};
173 + }
174 +
175 + options = options || {};
176 + options.sql = 'ROLLBACK';
177 + options.values = null;
178 +
179 + return this.query(options, callback);
180 +};
181 +
182 +Connection.prototype.query = function query(sql, values, cb) {
183 + var query = Connection.createQuery(sql, values, cb);
184 + query._connection = this;
185 +
186 + if (!(typeof sql === 'object' && 'typeCast' in sql)) {
187 + query.typeCast = this.config.typeCast;
188 + }
189 +
190 + if (query.sql) {
191 + query.sql = this.format(query.sql, query.values);
192 + }
193 +
194 + if (query._callback) {
195 + query._callback = wrapCallbackInDomain(this, query._callback);
196 + }
197 +
198 + this._implyConnect();
199 +
200 + return this._protocol._enqueue(query);
201 +};
202 +
203 +Connection.prototype.ping = function ping(options, callback) {
204 + if (!callback && typeof options === 'function') {
205 + callback = options;
206 + options = {};
207 + }
208 +
209 + this._implyConnect();
210 + this._protocol.ping(options, wrapCallbackInDomain(this, callback));
211 +};
212 +
213 +Connection.prototype.statistics = function statistics(options, callback) {
214 + if (!callback && typeof options === 'function') {
215 + callback = options;
216 + options = {};
217 + }
218 +
219 + this._implyConnect();
220 + this._protocol.stats(options, wrapCallbackInDomain(this, callback));
221 +};
222 +
223 +Connection.prototype.end = function end(options, callback) {
224 + var cb = callback;
225 + var opts = options;
226 +
227 + if (!callback && typeof options === 'function') {
228 + cb = options;
229 + opts = null;
230 + }
231 +
232 + // create custom options reference
233 + opts = Object.create(opts || null);
234 +
235 + if (opts.timeout === undefined) {
236 + // default timeout of 30 seconds
237 + opts.timeout = 30000;
238 + }
239 +
240 + this._implyConnect();
241 + this._protocol.quit(opts, wrapCallbackInDomain(this, cb));
242 +};
243 +
244 +Connection.prototype.destroy = function() {
245 + this.state = 'disconnected';
246 + this._implyConnect();
247 + this._socket.destroy();
248 + this._protocol.destroy();
249 +};
250 +
251 +Connection.prototype.pause = function() {
252 + this._socket.pause();
253 + this._protocol.pause();
254 +};
255 +
256 +Connection.prototype.resume = function() {
257 + this._socket.resume();
258 + this._protocol.resume();
259 +};
260 +
261 +Connection.prototype.escape = function(value) {
262 + return SqlString.escape(value, false, this.config.timezone);
263 +};
264 +
265 +Connection.prototype.escapeId = function escapeId(value) {
266 + return SqlString.escapeId(value, false);
267 +};
268 +
269 +Connection.prototype.format = function(sql, values) {
270 + if (typeof this.config.queryFormat === 'function') {
271 + return this.config.queryFormat.call(this, sql, values, this.config.timezone);
272 + }
273 + return SqlString.format(sql, values, this.config.stringifyObjects, this.config.timezone);
274 +};
275 +
276 +if (tls.TLSSocket) {
277 + // 0.11+ environment
278 + Connection.prototype._startTLS = function _startTLS(onSecure) {
279 + var connection = this;
280 + var secureContext = tls.createSecureContext({
281 + ca : this.config.ssl.ca,
282 + cert : this.config.ssl.cert,
283 + ciphers : this.config.ssl.ciphers,
284 + key : this.config.ssl.key,
285 + passphrase : this.config.ssl.passphrase
286 + });
287 +
288 + // "unpipe"
289 + this._socket.removeAllListeners('data');
290 + this._protocol.removeAllListeners('data');
291 +
292 + // socket <-> encrypted
293 + var rejectUnauthorized = this.config.ssl.rejectUnauthorized;
294 + var secureEstablished = false;
295 + var secureSocket = new tls.TLSSocket(this._socket, {
296 + rejectUnauthorized : rejectUnauthorized,
297 + requestCert : true,
298 + secureContext : secureContext,
299 + isServer : false
300 + });
301 +
302 + // error handler for secure socket
303 + secureSocket.on('_tlsError', function(err) {
304 + if (secureEstablished) {
305 + connection._handleNetworkError(err);
306 + } else {
307 + onSecure(err);
308 + }
309 + });
310 +
311 + // cleartext <-> protocol
312 + secureSocket.pipe(this._protocol);
313 + this._protocol.on('data', function(data) {
314 + secureSocket.write(data);
315 + });
316 +
317 + secureSocket.on('secure', function() {
318 + secureEstablished = true;
319 +
320 + onSecure(rejectUnauthorized ? this.ssl.verifyError() : null);
321 + });
322 +
323 + // start TLS communications
324 + secureSocket._start();
325 + };
326 +} else {
327 + // pre-0.11 environment
328 + Connection.prototype._startTLS = function _startTLS(onSecure) {
329 + // before TLS:
330 + // _socket <-> _protocol
331 + // after:
332 + // _socket <-> securePair.encrypted <-> securePair.cleartext <-> _protocol
333 +
334 + var connection = this;
335 + var credentials = Crypto.createCredentials({
336 + ca : this.config.ssl.ca,
337 + cert : this.config.ssl.cert,
338 + ciphers : this.config.ssl.ciphers,
339 + key : this.config.ssl.key,
340 + passphrase : this.config.ssl.passphrase
341 + });
342 +
343 + var rejectUnauthorized = this.config.ssl.rejectUnauthorized;
344 + var secureEstablished = false;
345 + var securePair = tls.createSecurePair(credentials, false, true, rejectUnauthorized);
346 +
347 + // error handler for secure pair
348 + securePair.on('error', function(err) {
349 + if (secureEstablished) {
350 + connection._handleNetworkError(err);
351 + } else {
352 + onSecure(err);
353 + }
354 + });
355 +
356 + // "unpipe"
357 + this._socket.removeAllListeners('data');
358 + this._protocol.removeAllListeners('data');
359 +
360 + // socket <-> encrypted
361 + securePair.encrypted.pipe(this._socket);
362 + this._socket.on('data', function(data) {
363 + securePair.encrypted.write(data);
364 + });
365 +
366 + // cleartext <-> protocol
367 + securePair.cleartext.pipe(this._protocol);
368 + this._protocol.on('data', function(data) {
369 + securePair.cleartext.write(data);
370 + });
371 +
372 + // secure established
373 + securePair.on('secure', function() {
374 + secureEstablished = true;
375 +
376 + if (!rejectUnauthorized) {
377 + onSecure();
378 + return;
379 + }
380 +
381 + var verifyError = this.ssl.verifyError();
382 + var err = verifyError;
383 +
384 + // node.js 0.6 support
385 + if (typeof err === 'string') {
386 + err = new Error(verifyError);
387 + err.code = verifyError;
388 + }
389 +
390 + onSecure(err);
391 + });
392 +
393 + // node.js 0.8 bug
394 + securePair._cycle = securePair.cycle;
395 + securePair.cycle = function cycle() {
396 + if (this.ssl && this.ssl.error) {
397 + this.error();
398 + }
399 +
400 + return this._cycle.apply(this, arguments);
401 + };
402 + };
403 +}
404 +
405 +Connection.prototype._handleConnectTimeout = function() {
406 + if (this._socket) {
407 + this._socket.setTimeout(0);
408 + this._socket.destroy();
409 + }
410 +
411 + var err = new Error('connect ETIMEDOUT');
412 + err.errorno = 'ETIMEDOUT';
413 + err.code = 'ETIMEDOUT';
414 + err.syscall = 'connect';
415 +
416 + this._handleNetworkError(err);
417 +};
418 +
419 +Connection.prototype._handleNetworkError = function(err) {
420 + this._protocol.handleNetworkError(err);
421 +};
422 +
423 +Connection.prototype._handleProtocolError = function(err) {
424 + this.state = 'protocol_error';
425 + this.emit('error', err);
426 +};
427 +
428 +Connection.prototype._handleProtocolDrain = function() {
429 + this.emit('drain');
430 +};
431 +
432 +Connection.prototype._handleProtocolConnect = function() {
433 + this.state = 'connected';
434 + this.emit('connect');
435 +};
436 +
437 +Connection.prototype._handleProtocolHandshake = function _handleProtocolHandshake(packet) {
438 + this.state = 'authenticated';
439 + this.threadId = packet.threadId;
440 +};
441 +
442 +Connection.prototype._handleProtocolEnd = function(err) {
443 + this.state = 'disconnected';
444 + this.emit('end', err);
445 +};
446 +
447 +Connection.prototype._handleProtocolEnqueue = function _handleProtocolEnqueue(sequence) {
448 + this.emit('enqueue', sequence);
449 +};
450 +
451 +Connection.prototype._implyConnect = function() {
452 + if (!this._connectCalled) {
453 + this.connect();
454 + }
455 +};
456 +
457 +function unwrapFromDomain(fn) {
458 + return function () {
459 + var domains = [];
460 + var ret;
461 +
462 + while (process.domain) {
463 + domains.shift(process.domain);
464 + process.domain.exit();
465 + }
466 +
467 + try {
468 + ret = fn.apply(this, arguments);
469 + } finally {
470 + for (var i = 0; i < domains.length; i++) {
471 + domains[i].enter();
472 + }
473 + }
474 +
475 + return ret;
476 + };
477 +}
478 +
479 +function wrapCallbackInDomain(ee, fn) {
480 + if (typeof fn !== 'function' || fn.domain) {
481 + return fn;
482 + }
483 +
484 + var domain = process.domain;
485 +
486 + if (domain) {
487 + return domain.bind(fn);
488 + } else if (ee) {
489 + return unwrapFromDomain(wrapToDomain(ee, fn));
490 + } else {
491 + return fn;
492 + }
493 +}
494 +
495 +function wrapToDomain(ee, fn) {
496 + return function () {
497 + if (Events.usingDomains && ee.domain) {
498 + ee.domain.enter();
499 + fn.apply(this, arguments);
500 + ee.domain.exit();
501 + } else {
502 + fn.apply(this, arguments);
503 + }
504 + };
505 +}
1 +var urlParse = require('url').parse;
2 +var ClientConstants = require('./protocol/constants/client');
3 +var Charsets = require('./protocol/constants/charsets');
4 +var SSLProfiles = null;
5 +
6 +module.exports = ConnectionConfig;
7 +function ConnectionConfig(options) {
8 + if (typeof options === 'string') {
9 + options = ConnectionConfig.parseUrl(options);
10 + }
11 +
12 + this.host = options.host || 'localhost';
13 + this.port = options.port || 3306;
14 + this.localAddress = options.localAddress;
15 + this.socketPath = options.socketPath;
16 + this.user = options.user || undefined;
17 + this.password = options.password || undefined;
18 + this.database = options.database;
19 + this.connectTimeout = (options.connectTimeout === undefined)
20 + ? (10 * 1000)
21 + : options.connectTimeout;
22 + this.insecureAuth = options.insecureAuth || false;
23 + this.supportBigNumbers = options.supportBigNumbers || false;
24 + this.bigNumberStrings = options.bigNumberStrings || false;
25 + this.dateStrings = options.dateStrings || false;
26 + this.debug = options.debug;
27 + this.trace = options.trace !== false;
28 + this.stringifyObjects = options.stringifyObjects || false;
29 + this.timezone = options.timezone || 'local';
30 + this.flags = options.flags || '';
31 + this.queryFormat = options.queryFormat;
32 + this.pool = options.pool || undefined;
33 + this.ssl = (typeof options.ssl === 'string')
34 + ? ConnectionConfig.getSSLProfile(options.ssl)
35 + : (options.ssl || false);
36 + this.multipleStatements = options.multipleStatements || false;
37 + this.typeCast = (options.typeCast === undefined)
38 + ? true
39 + : options.typeCast;
40 +
41 + if (this.timezone[0] === ' ') {
42 + // "+" is a url encoded char for space so it
43 + // gets translated to space when giving a
44 + // connection string..
45 + this.timezone = '+' + this.timezone.substr(1);
46 + }
47 +
48 + if (this.ssl) {
49 + // Default rejectUnauthorized to true
50 + this.ssl.rejectUnauthorized = this.ssl.rejectUnauthorized !== false;
51 + }
52 +
53 + this.maxPacketSize = 0;
54 + this.charsetNumber = (options.charset)
55 + ? ConnectionConfig.getCharsetNumber(options.charset)
56 + : options.charsetNumber || Charsets.UTF8_GENERAL_CI;
57 +
58 + // Set the client flags
59 + var defaultFlags = ConnectionConfig.getDefaultFlags(options);
60 + this.clientFlags = ConnectionConfig.mergeFlags(defaultFlags, options.flags);
61 +}
62 +
63 +ConnectionConfig.mergeFlags = function mergeFlags(defaultFlags, userFlags) {
64 + var allFlags = ConnectionConfig.parseFlagList(defaultFlags);
65 + var newFlags = ConnectionConfig.parseFlagList(userFlags);
66 +
67 + // Merge the new flags
68 + for (var flag in newFlags) {
69 + if (allFlags[flag] !== false) {
70 + allFlags[flag] = newFlags[flag];
71 + }
72 + }
73 +
74 + // Build flags
75 + var flags = 0x0;
76 + for (var flag in allFlags) {
77 + if (allFlags[flag]) {
78 + // TODO: Throw here on some future release
79 + flags |= ClientConstants['CLIENT_' + flag] || 0x0;
80 + }
81 + }
82 +
83 + return flags;
84 +};
85 +
86 +ConnectionConfig.getCharsetNumber = function getCharsetNumber(charset) {
87 + var num = Charsets[charset.toUpperCase()];
88 +
89 + if (num === undefined) {
90 + throw new TypeError('Unknown charset \'' + charset + '\'');
91 + }
92 +
93 + return num;
94 +};
95 +
96 +ConnectionConfig.getDefaultFlags = function getDefaultFlags(options) {
97 + var defaultFlags = [
98 + '-COMPRESS', // Compression protocol *NOT* supported
99 + '-CONNECT_ATTRS', // Does *NOT* send connection attributes in Protocol::HandshakeResponse41
100 + '+CONNECT_WITH_DB', // One can specify db on connect in Handshake Response Packet
101 + '+FOUND_ROWS', // Send found rows instead of affected rows
102 + '+IGNORE_SIGPIPE', // Don't issue SIGPIPE if network failures
103 + '+IGNORE_SPACE', // Let the parser ignore spaces before '('
104 + '+LOCAL_FILES', // Can use LOAD DATA LOCAL
105 + '+LONG_FLAG', // Longer flags in Protocol::ColumnDefinition320
106 + '+LONG_PASSWORD', // Use the improved version of Old Password Authentication
107 + '+MULTI_RESULTS', // Can handle multiple resultsets for COM_QUERY
108 + '+ODBC', // Special handling of ODBC behaviour
109 + '-PLUGIN_AUTH', // Does *NOT* support auth plugins
110 + '+PROTOCOL_41', // Uses the 4.1 protocol
111 + '+PS_MULTI_RESULTS', // Can handle multiple resultsets for COM_STMT_EXECUTE
112 + '+RESERVED', // Unused
113 + '+SECURE_CONNECTION', // Supports Authentication::Native41
114 + '+TRANSACTIONS' // Expects status flags
115 + ];
116 +
117 + if (options && options.multipleStatements) {
118 + // May send multiple statements per COM_QUERY and COM_STMT_PREPARE
119 + defaultFlags.push('+MULTI_STATEMENTS');
120 + }
121 +
122 + return defaultFlags;
123 +};
124 +
125 +ConnectionConfig.getSSLProfile = function getSSLProfile(name) {
126 + if (!SSLProfiles) {
127 + SSLProfiles = require('./protocol/constants/ssl_profiles');
128 + }
129 +
130 + var ssl = SSLProfiles[name];
131 +
132 + if (ssl === undefined) {
133 + throw new TypeError('Unknown SSL profile \'' + name + '\'');
134 + }
135 +
136 + return ssl;
137 +};
138 +
139 +ConnectionConfig.parseFlagList = function parseFlagList(flagList) {
140 + var allFlags = Object.create(null);
141 +
142 + if (!flagList) {
143 + return allFlags;
144 + }
145 +
146 + var flags = !Array.isArray(flagList)
147 + ? String(flagList || '').toUpperCase().split(/\s*,+\s*/)
148 + : flagList;
149 +
150 + for (var i = 0; i < flags.length; i++) {
151 + var flag = flags[i];
152 + var offset = 1;
153 + var state = flag[0];
154 +
155 + if (state === undefined) {
156 + // TODO: throw here on some future release
157 + continue;
158 + }
159 +
160 + if (state !== '-' && state !== '+') {
161 + offset = 0;
162 + state = '+';
163 + }
164 +
165 + allFlags[flag.substr(offset)] = state === '+';
166 + }
167 +
168 + return allFlags;
169 +};
170 +
171 +ConnectionConfig.parseUrl = function(url) {
172 + url = urlParse(url, true);
173 +
174 + var options = {
175 + host : url.hostname,
176 + port : url.port,
177 + database : url.pathname.substr(1)
178 + };
179 +
180 + if (url.auth) {
181 + var auth = url.auth.split(':');
182 + options.user = auth.shift();
183 + options.password = auth.join(':');
184 + }
185 +
186 + if (url.query) {
187 + for (var key in url.query) {
188 + var value = url.query[key];
189 +
190 + try {
191 + // Try to parse this as a JSON expression first
192 + options[key] = JSON.parse(value);
193 + } catch (err) {
194 + // Otherwise assume it is a plain string
195 + options[key] = value;
196 + }
197 + }
198 + }
199 +
200 + return options;
201 +};
1 +var mysql = require('../');
2 +var Connection = require('./Connection');
3 +var EventEmitter = require('events').EventEmitter;
4 +var Util = require('util');
5 +var PoolConnection = require('./PoolConnection');
6 +
7 +module.exports = Pool;
8 +
9 +Util.inherits(Pool, EventEmitter);
10 +function Pool(options) {
11 + EventEmitter.call(this);
12 + this.config = options.config;
13 + this.config.connectionConfig.pool = this;
14 +
15 + this._acquiringConnections = [];
16 + this._allConnections = [];
17 + this._freeConnections = [];
18 + this._connectionQueue = [];
19 + this._closed = false;
20 +}
21 +
22 +Pool.prototype.getConnection = function (cb) {
23 +
24 + if (this._closed) {
25 + var err = new Error('Pool is closed.');
26 + err.code = 'POOL_CLOSED';
27 + process.nextTick(function () {
28 + cb(err);
29 + });
30 + return;
31 + }
32 +
33 + var connection;
34 + var pool = this;
35 +
36 + if (this._freeConnections.length > 0) {
37 + connection = this._freeConnections.shift();
38 + this.acquireConnection(connection, cb);
39 + return;
40 + }
41 +
42 + if (this.config.connectionLimit === 0 || this._allConnections.length < this.config.connectionLimit) {
43 + connection = new PoolConnection(this, { config: this.config.newConnectionConfig() });
44 +
45 + this._acquiringConnections.push(connection);
46 + this._allConnections.push(connection);
47 +
48 + connection.connect({timeout: this.config.acquireTimeout}, function onConnect(err) {
49 + spliceConnection(pool._acquiringConnections, connection);
50 +
51 + if (pool._closed) {
52 + err = new Error('Pool is closed.');
53 + err.code = 'POOL_CLOSED';
54 + }
55 +
56 + if (err) {
57 + pool._purgeConnection(connection);
58 + cb(err);
59 + return;
60 + }
61 +
62 + pool.emit('connection', connection);
63 + pool.emit('acquire', connection);
64 + cb(null, connection);
65 + });
66 + return;
67 + }
68 +
69 + if (!this.config.waitForConnections) {
70 + process.nextTick(function(){
71 + var err = new Error('No connections available.');
72 + err.code = 'POOL_CONNLIMIT';
73 + cb(err);
74 + });
75 + return;
76 + }
77 +
78 + this._enqueueCallback(cb);
79 +};
80 +
81 +Pool.prototype.acquireConnection = function acquireConnection(connection, cb) {
82 + if (connection._pool !== this) {
83 + throw new Error('Connection acquired from wrong pool.');
84 + }
85 +
86 + var changeUser = this._needsChangeUser(connection);
87 + var pool = this;
88 +
89 + this._acquiringConnections.push(connection);
90 +
91 + function onOperationComplete(err) {
92 + spliceConnection(pool._acquiringConnections, connection);
93 +
94 + if (pool._closed) {
95 + err = new Error('Pool is closed.');
96 + err.code = 'POOL_CLOSED';
97 + }
98 +
99 + if (err) {
100 + pool._connectionQueue.unshift(cb);
101 + pool._purgeConnection(connection);
102 + return;
103 + }
104 +
105 + if (changeUser) {
106 + pool.emit('connection', connection);
107 + }
108 +
109 + pool.emit('acquire', connection);
110 + cb(null, connection);
111 + }
112 +
113 + if (changeUser) {
114 + // restore user back to pool configuration
115 + connection.config = this.config.newConnectionConfig();
116 + connection.changeUser({timeout: this.config.acquireTimeout}, onOperationComplete);
117 + } else {
118 + // ping connection
119 + connection.ping({timeout: this.config.acquireTimeout}, onOperationComplete);
120 + }
121 +};
122 +
123 +Pool.prototype.releaseConnection = function releaseConnection(connection) {
124 +
125 + if (this._acquiringConnections.indexOf(connection) !== -1) {
126 + // connection is being acquired
127 + return;
128 + }
129 +
130 + if (connection._pool) {
131 + if (connection._pool !== this) {
132 + throw new Error('Connection released to wrong pool');
133 + }
134 +
135 + if (this._freeConnections.indexOf(connection) !== -1) {
136 + // connection already in free connection pool
137 + // this won't catch all double-release cases
138 + throw new Error('Connection already released');
139 + } else {
140 + // add connection to end of free queue
141 + this._freeConnections.push(connection);
142 + this.emit('release', connection);
143 + }
144 + }
145 +
146 + if (this._closed) {
147 + // empty the connection queue
148 + this._connectionQueue.splice(0).forEach(function (cb) {
149 + var err = new Error('Pool is closed.');
150 + err.code = 'POOL_CLOSED';
151 + process.nextTick(function () {
152 + cb(err);
153 + });
154 + });
155 + } else if (this._connectionQueue.length) {
156 + // get connection with next waiting callback
157 + this.getConnection(this._connectionQueue.shift());
158 + }
159 +};
160 +
161 +Pool.prototype.end = function (cb) {
162 + this._closed = true;
163 +
164 + if (typeof cb !== 'function') {
165 + cb = function (err) {
166 + if (err) throw err;
167 + };
168 + }
169 +
170 + var calledBack = false;
171 + var waitingClose = 0;
172 +
173 + function onEnd(err) {
174 + if (!calledBack && (err || --waitingClose <= 0)) {
175 + calledBack = true;
176 + cb(err);
177 + }
178 + }
179 +
180 + while (this._allConnections.length !== 0) {
181 + waitingClose++;
182 + this._purgeConnection(this._allConnections[0], onEnd);
183 + }
184 +
185 + if (waitingClose === 0) {
186 + process.nextTick(onEnd);
187 + }
188 +};
189 +
190 +Pool.prototype.query = function (sql, values, cb) {
191 + var query = Connection.createQuery(sql, values, cb);
192 +
193 + if (!(typeof sql === 'object' && 'typeCast' in sql)) {
194 + query.typeCast = this.config.connectionConfig.typeCast;
195 + }
196 +
197 + if (this.config.connectionConfig.trace) {
198 + // Long stack trace support
199 + query._callSite = new Error();
200 + }
201 +
202 + this.getConnection(function (err, conn) {
203 + if (err) {
204 + query.on('error', function () {});
205 + query.end(err);
206 + return;
207 + }
208 +
209 + // Release connection based off event
210 + query.once('end', function() {
211 + conn.release();
212 + });
213 +
214 + conn.query(query);
215 + });
216 +
217 + return query;
218 +};
219 +
220 +Pool.prototype._enqueueCallback = function _enqueueCallback(callback) {
221 +
222 + if (this.config.queueLimit && this._connectionQueue.length >= this.config.queueLimit) {
223 + process.nextTick(function () {
224 + var err = new Error('Queue limit reached.');
225 + err.code = 'POOL_ENQUEUELIMIT';
226 + callback(err);
227 + });
228 + return;
229 + }
230 +
231 + // Bind to domain, as dequeue will likely occur in a different domain
232 + var cb = process.domain
233 + ? process.domain.bind(callback)
234 + : callback;
235 +
236 + this._connectionQueue.push(cb);
237 + this.emit('enqueue');
238 +};
239 +
240 +Pool.prototype._needsChangeUser = function _needsChangeUser(connection) {
241 + var connConfig = connection.config;
242 + var poolConfig = this.config.connectionConfig;
243 +
244 + // check if changeUser values are different
245 + return connConfig.user !== poolConfig.user
246 + || connConfig.database !== poolConfig.database
247 + || connConfig.password !== poolConfig.password
248 + || connConfig.charsetNumber !== poolConfig.charsetNumber;
249 +};
250 +
251 +Pool.prototype._purgeConnection = function _purgeConnection(connection, callback) {
252 + var cb = callback || function () {};
253 +
254 + if (connection.state === 'disconnected') {
255 + connection.destroy();
256 + }
257 +
258 + this._removeConnection(connection);
259 +
260 + if (connection.state !== 'disconnected' && !connection._protocol._quitSequence) {
261 + connection._realEnd(cb);
262 + return;
263 + }
264 +
265 + process.nextTick(cb);
266 +};
267 +
268 +Pool.prototype._removeConnection = function(connection) {
269 + connection._pool = null;
270 +
271 + // Remove connection from all connections
272 + spliceConnection(this._allConnections, connection);
273 +
274 + // Remove connection from free connections
275 + spliceConnection(this._freeConnections, connection);
276 +
277 + this.releaseConnection(connection);
278 +};
279 +
280 +Pool.prototype.escape = function(value) {
281 + return mysql.escape(value, this.config.connectionConfig.stringifyObjects, this.config.connectionConfig.timezone);
282 +};
283 +
284 +Pool.prototype.escapeId = function escapeId(value) {
285 + return mysql.escapeId(value, false);
286 +};
287 +
288 +function spliceConnection(array, connection) {
289 + var index;
290 + if ((index = array.indexOf(connection)) !== -1) {
291 + // Remove connection from all connections
292 + array.splice(index, 1);
293 + }
294 +}
1 +var Pool = require('./Pool');
2 +var PoolConfig = require('./PoolConfig');
3 +var PoolNamespace = require('./PoolNamespace');
4 +var PoolSelector = require('./PoolSelector');
5 +var Util = require('util');
6 +var EventEmitter = require('events').EventEmitter;
7 +
8 +module.exports = PoolCluster;
9 +
10 +/**
11 + * PoolCluster
12 + * @constructor
13 + * @param {object} [config] The pool cluster configuration
14 + * @public
15 + */
16 +function PoolCluster(config) {
17 + EventEmitter.call(this);
18 +
19 + config = config || {};
20 + this._canRetry = typeof config.canRetry === 'undefined' ? true : config.canRetry;
21 + this._defaultSelector = config.defaultSelector || 'RR';
22 + this._removeNodeErrorCount = config.removeNodeErrorCount || 5;
23 + this._restoreNodeTimeout = config.restoreNodeTimeout || 0;
24 +
25 + this._closed = false;
26 + this._findCaches = Object.create(null);
27 + this._lastId = 0;
28 + this._namespaces = Object.create(null);
29 + this._nodes = Object.create(null);
30 +}
31 +
32 +Util.inherits(PoolCluster, EventEmitter);
33 +
34 +PoolCluster.prototype.add = function add(id, config) {
35 + if (this._closed) {
36 + throw new Error('PoolCluster is closed.');
37 + }
38 +
39 + var nodeId = typeof id === 'object'
40 + ? 'CLUSTER::' + (++this._lastId)
41 + : String(id);
42 +
43 + if (this._nodes[nodeId] !== undefined) {
44 + throw new Error('Node ID "' + nodeId + '" is already defined in PoolCluster.');
45 + }
46 +
47 + var poolConfig = typeof id !== 'object'
48 + ? new PoolConfig(config)
49 + : new PoolConfig(id);
50 +
51 + this._nodes[nodeId] = {
52 + id : nodeId,
53 + errorCount : 0,
54 + pool : new Pool({config: poolConfig}),
55 + _offlineUntil : 0
56 + };
57 +
58 + this._clearFindCaches();
59 +};
60 +
61 +PoolCluster.prototype.end = function end(callback) {
62 + var cb = callback !== undefined
63 + ? callback
64 + : _cb;
65 +
66 + if (typeof cb !== 'function') {
67 + throw TypeError('callback argument must be a function');
68 + }
69 +
70 + if (this._closed) {
71 + process.nextTick(cb);
72 + return;
73 + }
74 +
75 + this._closed = true;
76 +
77 + var calledBack = false;
78 + var nodeIds = Object.keys(this._nodes);
79 + var waitingClose = 0;
80 +
81 + function onEnd(err) {
82 + if (!calledBack && (err || --waitingClose <= 0)) {
83 + calledBack = true;
84 + cb(err);
85 + }
86 + }
87 +
88 + for (var i = 0; i < nodeIds.length; i++) {
89 + var nodeId = nodeIds[i];
90 + var node = this._nodes[nodeId];
91 +
92 + waitingClose++;
93 + node.pool.end(onEnd);
94 + }
95 +
96 + if (waitingClose === 0) {
97 + process.nextTick(onEnd);
98 + }
99 +};
100 +
101 +PoolCluster.prototype.of = function(pattern, selector) {
102 + pattern = pattern || '*';
103 +
104 + selector = selector || this._defaultSelector;
105 + selector = selector.toUpperCase();
106 + if (typeof PoolSelector[selector] === 'undefined') {
107 + selector = this._defaultSelector;
108 + }
109 +
110 + var key = pattern + selector;
111 +
112 + if (typeof this._namespaces[key] === 'undefined') {
113 + this._namespaces[key] = new PoolNamespace(this, pattern, selector);
114 + }
115 +
116 + return this._namespaces[key];
117 +};
118 +
119 +PoolCluster.prototype.remove = function remove(pattern) {
120 + var foundNodeIds = this._findNodeIds(pattern, true);
121 +
122 + for (var i = 0; i < foundNodeIds.length; i++) {
123 + var node = this._getNode(foundNodeIds[i]);
124 +
125 + if (node) {
126 + this._removeNode(node);
127 + }
128 + }
129 +};
130 +
131 +PoolCluster.prototype.getConnection = function(pattern, selector, cb) {
132 + var namespace;
133 + if (typeof pattern === 'function') {
134 + cb = pattern;
135 + namespace = this.of();
136 + } else {
137 + if (typeof selector === 'function') {
138 + cb = selector;
139 + selector = this._defaultSelector;
140 + }
141 +
142 + namespace = this.of(pattern, selector);
143 + }
144 +
145 + namespace.getConnection(cb);
146 +};
147 +
148 +PoolCluster.prototype._clearFindCaches = function _clearFindCaches() {
149 + this._findCaches = Object.create(null);
150 +};
151 +
152 +PoolCluster.prototype._decreaseErrorCount = function _decreaseErrorCount(node) {
153 + var errorCount = node.errorCount;
154 +
155 + if (errorCount > this._removeNodeErrorCount) {
156 + errorCount = this._removeNodeErrorCount;
157 + }
158 +
159 + if (errorCount < 1) {
160 + errorCount = 1;
161 + }
162 +
163 + node.errorCount = errorCount - 1;
164 +
165 + if (node._offlineUntil) {
166 + node._offlineUntil = 0;
167 + this.emit('online', node.id);
168 + }
169 +};
170 +
171 +PoolCluster.prototype._findNodeIds = function _findNodeIds(pattern, includeOffline) {
172 + var currentTime = 0;
173 + var foundNodeIds = this._findCaches[pattern];
174 +
175 + if (foundNodeIds === undefined) {
176 + var expression = patternRegExp(pattern);
177 + var nodeIds = Object.keys(this._nodes);
178 +
179 + foundNodeIds = nodeIds.filter(function (id) {
180 + return id.match(expression);
181 + });
182 +
183 + this._findCaches[pattern] = foundNodeIds;
184 + }
185 +
186 + if (includeOffline) {
187 + return foundNodeIds;
188 + }
189 +
190 + return foundNodeIds.filter(function (nodeId) {
191 + var node = this._getNode(nodeId);
192 +
193 + if (!node._offlineUntil) {
194 + return true;
195 + }
196 +
197 + if (!currentTime) {
198 + currentTime = getMonotonicMilliseconds();
199 + }
200 +
201 + return node._offlineUntil <= currentTime;
202 + }, this);
203 +};
204 +
205 +PoolCluster.prototype._getNode = function _getNode(id) {
206 + return this._nodes[id] || null;
207 +};
208 +
209 +PoolCluster.prototype._increaseErrorCount = function _increaseErrorCount(node) {
210 + var errorCount = ++node.errorCount;
211 +
212 + if (this._removeNodeErrorCount > errorCount) {
213 + return;
214 + }
215 +
216 + if (this._restoreNodeTimeout > 0) {
217 + node._offlineUntil = getMonotonicMilliseconds() + this._restoreNodeTimeout;
218 + this.emit('offline', node.id);
219 + return;
220 + }
221 +
222 + this._removeNode(node);
223 + this.emit('remove', node.id);
224 +};
225 +
226 +PoolCluster.prototype._getConnection = function(node, cb) {
227 + var self = this;
228 +
229 + node.pool.getConnection(function (err, connection) {
230 + if (err) {
231 + self._increaseErrorCount(node);
232 + cb(err);
233 + return;
234 + } else {
235 + self._decreaseErrorCount(node);
236 + }
237 +
238 + connection._clusterId = node.id;
239 +
240 + cb(null, connection);
241 + });
242 +};
243 +
244 +PoolCluster.prototype._removeNode = function _removeNode(node) {
245 + delete this._nodes[node.id];
246 +
247 + this._clearFindCaches();
248 +
249 + node.pool.end(_noop);
250 +};
251 +
252 +function getMonotonicMilliseconds() {
253 + var ms;
254 +
255 + if (typeof process.hrtime === 'function') {
256 + ms = process.hrtime();
257 + ms = ms[0] * 1e3 + ms[1] * 1e-6;
258 + } else {
259 + ms = process.uptime() * 1000;
260 + }
261 +
262 + return Math.floor(ms);
263 +}
264 +
265 +function isRegExp(val) {
266 + return typeof val === 'object'
267 + && Object.prototype.toString.call(val) === '[object RegExp]';
268 +}
269 +
270 +function patternRegExp(pattern) {
271 + if (isRegExp(pattern)) {
272 + return pattern;
273 + }
274 +
275 + var source = pattern
276 + .replace(/([.+?^=!:${}()|\[\]\/\\])/g, '\\$1')
277 + .replace(/\*/g, '.*');
278 +
279 + return new RegExp('^' + source + '$');
280 +}
281 +
282 +function _cb(err) {
283 + if (err) {
284 + throw err;
285 + }
286 +}
287 +
288 +function _noop() {}
1 +
2 +var ConnectionConfig = require('./ConnectionConfig');
3 +
4 +module.exports = PoolConfig;
5 +function PoolConfig(options) {
6 + if (typeof options === 'string') {
7 + options = ConnectionConfig.parseUrl(options);
8 + }
9 +
10 + this.acquireTimeout = (options.acquireTimeout === undefined)
11 + ? 10 * 1000
12 + : Number(options.acquireTimeout);
13 + this.connectionConfig = new ConnectionConfig(options);
14 + this.waitForConnections = (options.waitForConnections === undefined)
15 + ? true
16 + : Boolean(options.waitForConnections);
17 + this.connectionLimit = (options.connectionLimit === undefined)
18 + ? 10
19 + : Number(options.connectionLimit);
20 + this.queueLimit = (options.queueLimit === undefined)
21 + ? 0
22 + : Number(options.queueLimit);
23 +}
24 +
25 +PoolConfig.prototype.newConnectionConfig = function newConnectionConfig() {
26 + var connectionConfig = new ConnectionConfig(this.connectionConfig);
27 +
28 + connectionConfig.clientFlags = this.connectionConfig.clientFlags;
29 + connectionConfig.maxPacketSize = this.connectionConfig.maxPacketSize;
30 +
31 + return connectionConfig;
32 +};
1 +var inherits = require('util').inherits;
2 +var Connection = require('./Connection');
3 +var Events = require('events');
4 +
5 +module.exports = PoolConnection;
6 +inherits(PoolConnection, Connection);
7 +
8 +function PoolConnection(pool, options) {
9 + Connection.call(this, options);
10 + this._pool = pool;
11 +
12 + // Bind connection to pool domain
13 + if (Events.usingDomains) {
14 + this.domain = pool.domain;
15 + }
16 +
17 + // When a fatal error occurs the connection's protocol ends, which will cause
18 + // the connection to end as well, thus we only need to watch for the end event
19 + // and we will be notified of disconnects.
20 + this.on('end', this._removeFromPool);
21 + this.on('error', function (err) {
22 + if (err.fatal) {
23 + this._removeFromPool();
24 + }
25 + });
26 +}
27 +
28 +PoolConnection.prototype.release = function release() {
29 + var pool = this._pool;
30 +
31 + if (!pool || pool._closed) {
32 + return undefined;
33 + }
34 +
35 + return pool.releaseConnection(this);
36 +};
37 +
38 +// TODO: Remove this when we are removing PoolConnection#end
39 +PoolConnection.prototype._realEnd = Connection.prototype.end;
40 +
41 +PoolConnection.prototype.end = function () {
42 + console.warn(
43 + 'Calling conn.end() to release a pooled connection is ' +
44 + 'deprecated. In next version calling conn.end() will be ' +
45 + 'restored to default conn.end() behavior. Use ' +
46 + 'conn.release() instead.'
47 + );
48 + this.release();
49 +};
50 +
51 +PoolConnection.prototype.destroy = function () {
52 + Connection.prototype.destroy.apply(this, arguments);
53 + this._removeFromPool(this);
54 +};
55 +
56 +PoolConnection.prototype._removeFromPool = function _removeFromPool() {
57 + if (!this._pool || this._pool._closed) {
58 + return;
59 + }
60 +
61 + var pool = this._pool;
62 + this._pool = null;
63 +
64 + pool._purgeConnection(this);
65 +};
1 +var Connection = require('./Connection');
2 +var PoolSelector = require('./PoolSelector');
3 +
4 +module.exports = PoolNamespace;
5 +
6 +/**
7 + * PoolNamespace
8 + * @constructor
9 + * @param {PoolCluster} cluster The parent cluster for the namespace
10 + * @param {string} pattern The selection pattern to use
11 + * @param {string} selector The selector name to use
12 + * @public
13 + */
14 +function PoolNamespace(cluster, pattern, selector) {
15 + this._cluster = cluster;
16 + this._pattern = pattern;
17 + this._selector = new PoolSelector[selector]();
18 +}
19 +
20 +PoolNamespace.prototype.getConnection = function(cb) {
21 + var clusterNode = this._getClusterNode();
22 + var cluster = this._cluster;
23 + var namespace = this;
24 +
25 + if (clusterNode === null) {
26 + var err = null;
27 +
28 + if (this._cluster._findNodeIds(this._pattern, true).length !== 0) {
29 + err = new Error('Pool does not have online node.');
30 + err.code = 'POOL_NONEONLINE';
31 + } else {
32 + err = new Error('Pool does not exist.');
33 + err.code = 'POOL_NOEXIST';
34 + }
35 +
36 + cb(err);
37 + return;
38 + }
39 +
40 + cluster._getConnection(clusterNode, function(err, connection) {
41 + var retry = err && cluster._canRetry
42 + && cluster._findNodeIds(namespace._pattern).length !== 0;
43 +
44 + if (retry) {
45 + namespace.getConnection(cb);
46 + return;
47 + }
48 +
49 + if (err) {
50 + cb(err);
51 + return;
52 + }
53 +
54 + cb(null, connection);
55 + });
56 +};
57 +
58 +PoolNamespace.prototype.query = function (sql, values, cb) {
59 + var cluster = this._cluster;
60 + var clusterNode = this._getClusterNode();
61 + var query = Connection.createQuery(sql, values, cb);
62 + var namespace = this;
63 +
64 + if (clusterNode === null) {
65 + var err = null;
66 +
67 + if (this._cluster._findNodeIds(this._pattern, true).length !== 0) {
68 + err = new Error('Pool does not have online node.');
69 + err.code = 'POOL_NONEONLINE';
70 + } else {
71 + err = new Error('Pool does not exist.');
72 + err.code = 'POOL_NOEXIST';
73 + }
74 +
75 + process.nextTick(function () {
76 + query.on('error', function () {});
77 + query.end(err);
78 + });
79 + return query;
80 + }
81 +
82 + if (!(typeof sql === 'object' && 'typeCast' in sql)) {
83 + query.typeCast = clusterNode.pool.config.connectionConfig.typeCast;
84 + }
85 +
86 + if (clusterNode.pool.config.connectionConfig.trace) {
87 + // Long stack trace support
88 + query._callSite = new Error();
89 + }
90 +
91 + cluster._getConnection(clusterNode, function (err, conn) {
92 + var retry = err && cluster._canRetry
93 + && cluster._findNodeIds(namespace._pattern).length !== 0;
94 +
95 + if (retry) {
96 + namespace.query(query);
97 + return;
98 + }
99 +
100 + if (err) {
101 + query.on('error', function () {});
102 + query.end(err);
103 + return;
104 + }
105 +
106 + // Release connection based off event
107 + query.once('end', function() {
108 + conn.release();
109 + });
110 +
111 + conn.query(query);
112 + });
113 +
114 + return query;
115 +};
116 +
117 +PoolNamespace.prototype._getClusterNode = function _getClusterNode() {
118 + var foundNodeIds = this._cluster._findNodeIds(this._pattern);
119 + var nodeId;
120 +
121 + switch (foundNodeIds.length) {
122 + case 0:
123 + nodeId = null;
124 + break;
125 + case 1:
126 + nodeId = foundNodeIds[0];
127 + break;
128 + default:
129 + nodeId = this._selector(foundNodeIds);
130 + break;
131 + }
132 +
133 + return nodeId !== null
134 + ? this._cluster._getNode(nodeId)
135 + : null;
136 +};
1 +
2 +/**
3 + * PoolSelector
4 + */
5 +var PoolSelector = module.exports = {};
6 +
7 +PoolSelector.RR = function PoolSelectorRoundRobin() {
8 + var index = 0;
9 +
10 + return function(clusterIds) {
11 + if (index >= clusterIds.length) {
12 + index = 0;
13 + }
14 +
15 + var clusterId = clusterIds[index++];
16 +
17 + return clusterId;
18 + };
19 +};
20 +
21 +PoolSelector.RANDOM = function PoolSelectorRandom() {
22 + return function(clusterIds) {
23 + return clusterIds[Math.floor(Math.random() * clusterIds.length)];
24 + };
25 +};
26 +
27 +PoolSelector.ORDER = function PoolSelectorOrder() {
28 + return function(clusterIds) {
29 + return clusterIds[0];
30 + };
31 +};
1 +var Buffer = require('safe-buffer').Buffer;
2 +var Crypto = require('crypto');
3 +var Auth = exports;
4 +
5 +function sha1(msg) {
6 + var hash = Crypto.createHash('sha1');
7 + hash.update(msg, 'binary');
8 + return hash.digest('binary');
9 +}
10 +Auth.sha1 = sha1;
11 +
12 +function xor(a, b) {
13 + a = Buffer.from(a, 'binary');
14 + b = Buffer.from(b, 'binary');
15 + var result = Buffer.allocUnsafe(a.length);
16 + for (var i = 0; i < a.length; i++) {
17 + result[i] = (a[i] ^ b[i]);
18 + }
19 + return result;
20 +}
21 +Auth.xor = xor;
22 +
23 +Auth.token = function(password, scramble) {
24 + if (!password) {
25 + return Buffer.alloc(0);
26 + }
27 +
28 + // password must be in binary format, not utf8
29 + var stage1 = sha1((Buffer.from(password, 'utf8')).toString('binary'));
30 + var stage2 = sha1(stage1);
31 + var stage3 = sha1(scramble.toString('binary') + stage2);
32 + return xor(stage3, stage1);
33 +};
34 +
35 +// This is a port of sql/password.c:hash_password which needs to be used for
36 +// pre-4.1 passwords.
37 +Auth.hashPassword = function(password) {
38 + var nr = [0x5030, 0x5735];
39 + var add = 7;
40 + var nr2 = [0x1234, 0x5671];
41 + var result = Buffer.alloc(8);
42 +
43 + if (typeof password === 'string'){
44 + password = Buffer.from(password);
45 + }
46 +
47 + for (var i = 0; i < password.length; i++) {
48 + var c = password[i];
49 + if (c === 32 || c === 9) {
50 + // skip space in password
51 + continue;
52 + }
53 +
54 + // nr^= (((nr & 63)+add)*c)+ (nr << 8);
55 + // nr = xor(nr, add(mul(add(and(nr, 63), add), c), shl(nr, 8)))
56 + nr = this.xor32(nr, this.add32(this.mul32(this.add32(this.and32(nr, [0, 63]), [0, add]), [0, c]), this.shl32(nr, 8)));
57 +
58 + // nr2+=(nr2 << 8) ^ nr;
59 + // nr2 = add(nr2, xor(shl(nr2, 8), nr))
60 + nr2 = this.add32(nr2, this.xor32(this.shl32(nr2, 8), nr));
61 +
62 + // add+=tmp;
63 + add += c;
64 + }
65 +
66 + this.int31Write(result, nr, 0);
67 + this.int31Write(result, nr2, 4);
68 +
69 + return result;
70 +};
71 +
72 +Auth.randomInit = function(seed1, seed2) {
73 + return {
74 + max_value : 0x3FFFFFFF,
75 + max_value_dbl : 0x3FFFFFFF,
76 + seed1 : seed1 % 0x3FFFFFFF,
77 + seed2 : seed2 % 0x3FFFFFFF
78 + };
79 +};
80 +
81 +Auth.myRnd = function(r){
82 + r.seed1 = (r.seed1 * 3 + r.seed2) % r.max_value;
83 + r.seed2 = (r.seed1 + r.seed2 + 33) % r.max_value;
84 +
85 + return r.seed1 / r.max_value_dbl;
86 +};
87 +
88 +Auth.scramble323 = function(message, password) {
89 + var to = Buffer.allocUnsafe(8);
90 + var hashPass = this.hashPassword(password);
91 + var hashMessage = this.hashPassword(message.slice(0, 8));
92 + var seed1 = this.int32Read(hashPass, 0) ^ this.int32Read(hashMessage, 0);
93 + var seed2 = this.int32Read(hashPass, 4) ^ this.int32Read(hashMessage, 4);
94 + var r = this.randomInit(seed1, seed2);
95 +
96 + for (var i = 0; i < 8; i++){
97 + to[i] = Math.floor(this.myRnd(r) * 31) + 64;
98 + }
99 + var extra = (Math.floor(this.myRnd(r) * 31));
100 +
101 + for (var i = 0; i < 8; i++){
102 + to[i] ^= extra;
103 + }
104 +
105 + return to;
106 +};
107 +
108 +Auth.xor32 = function(a, b){
109 + return [a[0] ^ b[0], a[1] ^ b[1]];
110 +};
111 +
112 +Auth.add32 = function(a, b){
113 + var w1 = a[1] + b[1];
114 + var w2 = a[0] + b[0] + ((w1 & 0xFFFF0000) >> 16);
115 +
116 + return [w2 & 0xFFFF, w1 & 0xFFFF];
117 +};
118 +
119 +Auth.mul32 = function(a, b){
120 + // based on this example of multiplying 32b ints using 16b
121 + // http://www.dsprelated.com/showmessage/89790/1.php
122 + var w1 = a[1] * b[1];
123 + var w2 = (((a[1] * b[1]) >> 16) & 0xFFFF) + ((a[0] * b[1]) & 0xFFFF) + (a[1] * b[0] & 0xFFFF);
124 +
125 + return [w2 & 0xFFFF, w1 & 0xFFFF];
126 +};
127 +
128 +Auth.and32 = function(a, b){
129 + return [a[0] & b[0], a[1] & b[1]];
130 +};
131 +
132 +Auth.shl32 = function(a, b){
133 + // assume b is 16 or less
134 + var w1 = a[1] << b;
135 + var w2 = (a[0] << b) | ((w1 & 0xFFFF0000) >> 16);
136 +
137 + return [w2 & 0xFFFF, w1 & 0xFFFF];
138 +};
139 +
140 +Auth.int31Write = function(buffer, number, offset) {
141 + buffer[offset] = (number[0] >> 8) & 0x7F;
142 + buffer[offset + 1] = (number[0]) & 0xFF;
143 + buffer[offset + 2] = (number[1] >> 8) & 0xFF;
144 + buffer[offset + 3] = (number[1]) & 0xFF;
145 +};
146 +
147 +Auth.int32Read = function(buffer, offset){
148 + return (buffer[offset] << 24)
149 + + (buffer[offset + 1] << 16)
150 + + (buffer[offset + 2] << 8)
151 + + (buffer[offset + 3]);
152 +};
1 +
2 +module.exports = BufferList;
3 +function BufferList() {
4 + this.bufs = [];
5 + this.size = 0;
6 +}
7 +
8 +BufferList.prototype.shift = function shift() {
9 + var buf = this.bufs.shift();
10 +
11 + if (buf) {
12 + this.size -= buf.length;
13 + }
14 +
15 + return buf;
16 +};
17 +
18 +BufferList.prototype.push = function push(buf) {
19 + if (!buf || !buf.length) {
20 + return;
21 + }
22 +
23 + this.bufs.push(buf);
24 + this.size += buf.length;
25 +};
1 +module.exports = PacketHeader;
2 +function PacketHeader(length, number) {
3 + this.length = length;
4 + this.number = number;
5 +}
1 +var BIT_16 = Math.pow(2, 16);
2 +var BIT_24 = Math.pow(2, 24);
3 +var BUFFER_ALLOC_SIZE = Math.pow(2, 8);
4 +// The maximum precision JS Numbers can hold precisely
5 +// Don't panic: Good enough to represent byte values up to 8192 TB
6 +var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53);
7 +var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1;
8 +var Buffer = require('safe-buffer').Buffer;
9 +
10 +module.exports = PacketWriter;
11 +function PacketWriter() {
12 + this._buffer = null;
13 + this._offset = 0;
14 +}
15 +
16 +PacketWriter.prototype.toBuffer = function toBuffer(parser) {
17 + if (!this._buffer) {
18 + this._buffer = Buffer.alloc(0);
19 + this._offset = 0;
20 + }
21 +
22 + var buffer = this._buffer;
23 + var length = this._offset;
24 + var packets = Math.floor(length / MAX_PACKET_LENGTH) + 1;
25 +
26 + this._buffer = Buffer.allocUnsafe(length + packets * 4);
27 + this._offset = 0;
28 +
29 + for (var packet = 0; packet < packets; packet++) {
30 + var isLast = (packet + 1 === packets);
31 + var packetLength = (isLast)
32 + ? length % MAX_PACKET_LENGTH
33 + : MAX_PACKET_LENGTH;
34 +
35 + var packetNumber = parser.incrementPacketNumber();
36 +
37 + this.writeUnsignedNumber(3, packetLength);
38 + this.writeUnsignedNumber(1, packetNumber);
39 +
40 + var start = packet * MAX_PACKET_LENGTH;
41 + var end = start + packetLength;
42 +
43 + this.writeBuffer(buffer.slice(start, end));
44 + }
45 +
46 + return this._buffer;
47 +};
48 +
49 +PacketWriter.prototype.writeUnsignedNumber = function(bytes, value) {
50 + this._allocate(bytes);
51 +
52 + for (var i = 0; i < bytes; i++) {
53 + this._buffer[this._offset++] = (value >> (i * 8)) & 0xff;
54 + }
55 +};
56 +
57 +PacketWriter.prototype.writeFiller = function(bytes) {
58 + this._allocate(bytes);
59 +
60 + for (var i = 0; i < bytes; i++) {
61 + this._buffer[this._offset++] = 0x00;
62 + }
63 +};
64 +
65 +PacketWriter.prototype.writeNullTerminatedString = function(value, encoding) {
66 + // Typecast undefined into '' and numbers into strings
67 + value = value || '';
68 + value = value + '';
69 +
70 + var bytes = Buffer.byteLength(value, encoding || 'utf-8') + 1;
71 + this._allocate(bytes);
72 +
73 + this._buffer.write(value, this._offset, encoding);
74 + this._buffer[this._offset + bytes - 1] = 0x00;
75 +
76 + this._offset += bytes;
77 +};
78 +
79 +PacketWriter.prototype.writeString = function(value) {
80 + // Typecast undefined into '' and numbers into strings
81 + value = value || '';
82 + value = value + '';
83 +
84 + var bytes = Buffer.byteLength(value, 'utf-8');
85 + this._allocate(bytes);
86 +
87 + this._buffer.write(value, this._offset, 'utf-8');
88 +
89 + this._offset += bytes;
90 +};
91 +
92 +PacketWriter.prototype.writeBuffer = function(value) {
93 + var bytes = value.length;
94 +
95 + this._allocate(bytes);
96 + value.copy(this._buffer, this._offset);
97 + this._offset += bytes;
98 +};
99 +
100 +PacketWriter.prototype.writeLengthCodedNumber = function(value) {
101 + if (value === null) {
102 + this._allocate(1);
103 + this._buffer[this._offset++] = 251;
104 + return;
105 + }
106 +
107 + if (value <= 250) {
108 + this._allocate(1);
109 + this._buffer[this._offset++] = value;
110 + return;
111 + }
112 +
113 + if (value > IEEE_754_BINARY_64_PRECISION) {
114 + throw new Error(
115 + 'writeLengthCodedNumber: JS precision range exceeded, your ' +
116 + 'number is > 53 bit: "' + value + '"'
117 + );
118 + }
119 +
120 + if (value < BIT_16) {
121 + this._allocate(3);
122 + this._buffer[this._offset++] = 252;
123 + } else if (value < BIT_24) {
124 + this._allocate(4);
125 + this._buffer[this._offset++] = 253;
126 + } else {
127 + this._allocate(9);
128 + this._buffer[this._offset++] = 254;
129 + }
130 +
131 + // 16 Bit
132 + this._buffer[this._offset++] = value & 0xff;
133 + this._buffer[this._offset++] = (value >> 8) & 0xff;
134 +
135 + if (value < BIT_16) {
136 + return;
137 + }
138 +
139 + // 24 Bit
140 + this._buffer[this._offset++] = (value >> 16) & 0xff;
141 +
142 + if (value < BIT_24) {
143 + return;
144 + }
145 +
146 + this._buffer[this._offset++] = (value >> 24) & 0xff;
147 +
148 + // Hack: Get the most significant 32 bit (JS bitwise operators are 32 bit)
149 + value = value.toString(2);
150 + value = value.substr(0, value.length - 32);
151 + value = parseInt(value, 2);
152 +
153 + this._buffer[this._offset++] = value & 0xff;
154 + this._buffer[this._offset++] = (value >> 8) & 0xff;
155 + this._buffer[this._offset++] = (value >> 16) & 0xff;
156 +
157 + // Set last byte to 0, as we can only support 53 bits in JS (see above)
158 + this._buffer[this._offset++] = 0;
159 +};
160 +
161 +PacketWriter.prototype.writeLengthCodedBuffer = function(value) {
162 + var bytes = value.length;
163 + this.writeLengthCodedNumber(bytes);
164 + this.writeBuffer(value);
165 +};
166 +
167 +PacketWriter.prototype.writeNullTerminatedBuffer = function(value) {
168 + this.writeBuffer(value);
169 + this.writeFiller(1); // 0x00 terminator
170 +};
171 +
172 +PacketWriter.prototype.writeLengthCodedString = function(value) {
173 + if (value === null) {
174 + this.writeLengthCodedNumber(null);
175 + return;
176 + }
177 +
178 + value = (value === undefined)
179 + ? ''
180 + : String(value);
181 +
182 + var bytes = Buffer.byteLength(value, 'utf-8');
183 + this.writeLengthCodedNumber(bytes);
184 +
185 + if (!bytes) {
186 + return;
187 + }
188 +
189 + this._allocate(bytes);
190 + this._buffer.write(value, this._offset, 'utf-8');
191 + this._offset += bytes;
192 +};
193 +
194 +PacketWriter.prototype._allocate = function _allocate(bytes) {
195 + if (!this._buffer) {
196 + this._buffer = Buffer.alloc(Math.max(BUFFER_ALLOC_SIZE, bytes));
197 + this._offset = 0;
198 + return;
199 + }
200 +
201 + var bytesRemaining = this._buffer.length - this._offset;
202 + if (bytesRemaining >= bytes) {
203 + return;
204 + }
205 +
206 + var newSize = this._buffer.length + Math.max(BUFFER_ALLOC_SIZE, bytes);
207 + var oldBuffer = this._buffer;
208 +
209 + this._buffer = Buffer.alloc(newSize);
210 + oldBuffer.copy(this._buffer);
211 +};
1 +var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1;
2 +var MUL_32BIT = Math.pow(2, 32);
3 +var PacketHeader = require('./PacketHeader');
4 +var BigNumber = require('bignumber.js');
5 +var Buffer = require('safe-buffer').Buffer;
6 +var BufferList = require('./BufferList');
7 +
8 +module.exports = Parser;
9 +function Parser(options) {
10 + options = options || {};
11 +
12 + this._supportBigNumbers = options.config && options.config.supportBigNumbers;
13 + this._buffer = Buffer.alloc(0);
14 + this._nextBuffers = new BufferList();
15 + this._longPacketBuffers = new BufferList();
16 + this._offset = 0;
17 + this._packetEnd = null;
18 + this._packetHeader = null;
19 + this._packetOffset = null;
20 + this._onError = options.onError || function(err) { throw err; };
21 + this._onPacket = options.onPacket || function() {};
22 + this._nextPacketNumber = 0;
23 + this._encoding = 'utf-8';
24 + this._paused = false;
25 +}
26 +
27 +Parser.prototype.write = function write(chunk) {
28 + this._nextBuffers.push(chunk);
29 +
30 + while (!this._paused) {
31 + if (!this._packetHeader) {
32 + if (!this._combineNextBuffers(4)) {
33 + break;
34 + }
35 +
36 + this._packetHeader = new PacketHeader(
37 + this.parseUnsignedNumber(3),
38 + this.parseUnsignedNumber(1)
39 + );
40 +
41 + if (this._packetHeader.number !== this._nextPacketNumber) {
42 + var err = new Error(
43 + 'Packets out of order. Got: ' + this._packetHeader.number + ' ' +
44 + 'Expected: ' + this._nextPacketNumber
45 + );
46 +
47 + err.code = 'PROTOCOL_PACKETS_OUT_OF_ORDER';
48 + err.fatal = true;
49 +
50 + this._onError(err);
51 + }
52 +
53 + this.incrementPacketNumber();
54 + }
55 +
56 + if (!this._combineNextBuffers(this._packetHeader.length)) {
57 + break;
58 + }
59 +
60 + this._packetEnd = this._offset + this._packetHeader.length;
61 + this._packetOffset = this._offset;
62 +
63 + if (this._packetHeader.length === MAX_PACKET_LENGTH) {
64 + this._longPacketBuffers.push(this._buffer.slice(this._packetOffset, this._packetEnd));
65 +
66 + this._advanceToNextPacket();
67 + continue;
68 + }
69 +
70 + this._combineLongPacketBuffers();
71 +
72 + // Try...finally to ensure exception safety. Unfortunately this is costing
73 + // us up to ~10% performance in some benchmarks.
74 + var hadException = true;
75 + try {
76 + this._onPacket(this._packetHeader);
77 + hadException = false;
78 + } catch (err) {
79 + if (!err || typeof err.code !== 'string' || err.code.substr(0, 7) !== 'PARSER_') {
80 + throw err; // Rethrow non-MySQL errors
81 + }
82 +
83 + // Pass down parser errors
84 + this._onError(err);
85 + hadException = false;
86 + } finally {
87 + this._advanceToNextPacket();
88 +
89 + // If we had an exception, the parser while loop will be broken out
90 + // of after the finally block. So we need to make sure to re-enter it
91 + // to continue parsing any bytes that may already have been received.
92 + if (hadException) {
93 + process.nextTick(this.write.bind(this));
94 + }
95 + }
96 + }
97 +};
98 +
99 +Parser.prototype.append = function append(chunk) {
100 + if (!chunk || chunk.length === 0) {
101 + return;
102 + }
103 +
104 + // Calculate slice ranges
105 + var sliceEnd = this._buffer.length;
106 + var sliceStart = this._packetOffset === null
107 + ? this._offset
108 + : this._packetOffset;
109 + var sliceLength = sliceEnd - sliceStart;
110 +
111 + // Get chunk data
112 + var buffer = null;
113 + var chunks = !(chunk instanceof Array || Array.isArray(chunk)) ? [chunk] : chunk;
114 + var length = 0;
115 + var offset = 0;
116 +
117 + for (var i = 0; i < chunks.length; i++) {
118 + length += chunks[i].length;
119 + }
120 +
121 + if (sliceLength !== 0) {
122 + // Create a new Buffer
123 + buffer = Buffer.allocUnsafe(sliceLength + length);
124 + offset = 0;
125 +
126 + // Copy data slice
127 + offset += this._buffer.copy(buffer, 0, sliceStart, sliceEnd);
128 +
129 + // Copy chunks
130 + for (var i = 0; i < chunks.length; i++) {
131 + offset += chunks[i].copy(buffer, offset);
132 + }
133 + } else if (chunks.length > 1) {
134 + // Create a new Buffer
135 + buffer = Buffer.allocUnsafe(length);
136 + offset = 0;
137 +
138 + // Copy chunks
139 + for (var i = 0; i < chunks.length; i++) {
140 + offset += chunks[i].copy(buffer, offset);
141 + }
142 + } else {
143 + // Buffer is the only chunk
144 + buffer = chunks[0];
145 + }
146 +
147 + // Adjust data-tracking pointers
148 + this._buffer = buffer;
149 + this._offset = this._offset - sliceStart;
150 + this._packetEnd = this._packetEnd !== null
151 + ? this._packetEnd - sliceStart
152 + : null;
153 + this._packetOffset = this._packetOffset !== null
154 + ? this._packetOffset - sliceStart
155 + : null;
156 +};
157 +
158 +Parser.prototype.pause = function() {
159 + this._paused = true;
160 +};
161 +
162 +Parser.prototype.resume = function() {
163 + this._paused = false;
164 +
165 + // nextTick() to avoid entering write() multiple times within the same stack
166 + // which would cause problems as write manipulates the state of the object.
167 + process.nextTick(this.write.bind(this));
168 +};
169 +
170 +Parser.prototype.peak = function peak(offset) {
171 + return this._buffer[this._offset + (offset >>> 0)];
172 +};
173 +
174 +Parser.prototype.parseUnsignedNumber = function parseUnsignedNumber(bytes) {
175 + if (bytes === 1) {
176 + return this._buffer[this._offset++];
177 + }
178 +
179 + var buffer = this._buffer;
180 + var offset = this._offset + bytes - 1;
181 + var value = 0;
182 +
183 + if (bytes > 4) {
184 + var err = new Error('parseUnsignedNumber: Supports only up to 4 bytes');
185 + err.offset = (this._offset - this._packetOffset - 1);
186 + err.code = 'PARSER_UNSIGNED_TOO_LONG';
187 + throw err;
188 + }
189 +
190 + while (offset >= this._offset) {
191 + value = ((value << 8) | buffer[offset]) >>> 0;
192 + offset--;
193 + }
194 +
195 + this._offset += bytes;
196 +
197 + return value;
198 +};
199 +
200 +Parser.prototype.parseLengthCodedString = function() {
201 + var length = this.parseLengthCodedNumber();
202 +
203 + if (length === null) {
204 + return null;
205 + }
206 +
207 + return this.parseString(length);
208 +};
209 +
210 +Parser.prototype.parseLengthCodedBuffer = function() {
211 + var length = this.parseLengthCodedNumber();
212 +
213 + if (length === null) {
214 + return null;
215 + }
216 +
217 + return this.parseBuffer(length);
218 +};
219 +
220 +Parser.prototype.parseLengthCodedNumber = function parseLengthCodedNumber() {
221 + if (this._offset >= this._buffer.length) {
222 + var err = new Error('Parser: read past end');
223 + err.offset = (this._offset - this._packetOffset);
224 + err.code = 'PARSER_READ_PAST_END';
225 + throw err;
226 + }
227 +
228 + var bits = this._buffer[this._offset++];
229 +
230 + if (bits <= 250) {
231 + return bits;
232 + }
233 +
234 + switch (bits) {
235 + case 251:
236 + return null;
237 + case 252:
238 + return this.parseUnsignedNumber(2);
239 + case 253:
240 + return this.parseUnsignedNumber(3);
241 + case 254:
242 + break;
243 + default:
244 + var err = new Error('Unexpected first byte' + (bits ? ': 0x' + bits.toString(16) : ''));
245 + err.offset = (this._offset - this._packetOffset - 1);
246 + err.code = 'PARSER_BAD_LENGTH_BYTE';
247 + throw err;
248 + }
249 +
250 + var low = this.parseUnsignedNumber(4);
251 + var high = this.parseUnsignedNumber(4);
252 + var value;
253 +
254 + if (high >>> 21) {
255 + value = (new BigNumber(low)).plus((new BigNumber(MUL_32BIT)).times(high)).toString();
256 +
257 + if (this._supportBigNumbers) {
258 + return value;
259 + }
260 +
261 + var err = new Error(
262 + 'parseLengthCodedNumber: JS precision range exceeded, ' +
263 + 'number is >= 53 bit: "' + value + '"'
264 + );
265 + err.offset = (this._offset - this._packetOffset - 8);
266 + err.code = 'PARSER_JS_PRECISION_RANGE_EXCEEDED';
267 + throw err;
268 + }
269 +
270 + value = low + (MUL_32BIT * high);
271 +
272 + return value;
273 +};
274 +
275 +Parser.prototype.parseFiller = function(length) {
276 + return this.parseBuffer(length);
277 +};
278 +
279 +Parser.prototype.parseNullTerminatedBuffer = function() {
280 + var end = this._nullByteOffset();
281 + var value = this._buffer.slice(this._offset, end);
282 + this._offset = end + 1;
283 +
284 + return value;
285 +};
286 +
287 +Parser.prototype.parseNullTerminatedString = function() {
288 + var end = this._nullByteOffset();
289 + var value = this._buffer.toString(this._encoding, this._offset, end);
290 + this._offset = end + 1;
291 +
292 + return value;
293 +};
294 +
295 +Parser.prototype._nullByteOffset = function() {
296 + var offset = this._offset;
297 +
298 + while (this._buffer[offset] !== 0x00) {
299 + offset++;
300 +
301 + if (offset >= this._buffer.length) {
302 + var err = new Error('Offset of null terminated string not found.');
303 + err.offset = (this._offset - this._packetOffset);
304 + err.code = 'PARSER_MISSING_NULL_BYTE';
305 + throw err;
306 + }
307 + }
308 +
309 + return offset;
310 +};
311 +
312 +Parser.prototype.parsePacketTerminatedBuffer = function parsePacketTerminatedBuffer() {
313 + var length = this._packetEnd - this._offset;
314 + return this.parseBuffer(length);
315 +};
316 +
317 +Parser.prototype.parsePacketTerminatedString = function() {
318 + var length = this._packetEnd - this._offset;
319 + return this.parseString(length);
320 +};
321 +
322 +Parser.prototype.parseBuffer = function(length) {
323 + var response = Buffer.alloc(length);
324 + this._buffer.copy(response, 0, this._offset, this._offset + length);
325 +
326 + this._offset += length;
327 + return response;
328 +};
329 +
330 +Parser.prototype.parseString = function(length) {
331 + var offset = this._offset;
332 + var end = offset + length;
333 + var value = this._buffer.toString(this._encoding, offset, end);
334 +
335 + this._offset = end;
336 + return value;
337 +};
338 +
339 +Parser.prototype.parseGeometryValue = function() {
340 + var buffer = this.parseLengthCodedBuffer();
341 + var offset = 4;
342 +
343 + if (buffer === null || !buffer.length) {
344 + return null;
345 + }
346 +
347 + function parseGeometry() {
348 + var result = null;
349 + var byteOrder = buffer.readUInt8(offset); offset += 1;
350 + var wkbType = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4;
351 + switch (wkbType) {
352 + case 1: // WKBPoint
353 + var x = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
354 + var y = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
355 + result = {x: x, y: y};
356 + break;
357 + case 2: // WKBLineString
358 + var numPoints = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4;
359 + result = [];
360 + for (var i = numPoints; i > 0; i--) {
361 + var x = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
362 + var y = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
363 + result.push({x: x, y: y});
364 + }
365 + break;
366 + case 3: // WKBPolygon
367 + var numRings = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4;
368 + result = [];
369 + for (var i = numRings; i > 0; i--) {
370 + var numPoints = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4;
371 + var line = [];
372 + for (var j = numPoints; j > 0; j--) {
373 + var x = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
374 + var y = byteOrder ? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
375 + line.push({x: x, y: y});
376 + }
377 + result.push(line);
378 + }
379 + break;
380 + case 4: // WKBMultiPoint
381 + case 5: // WKBMultiLineString
382 + case 6: // WKBMultiPolygon
383 + case 7: // WKBGeometryCollection
384 + var num = byteOrder ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4;
385 + var result = [];
386 + for (var i = num; i > 0; i--) {
387 + result.push(parseGeometry());
388 + }
389 + break;
390 + }
391 + return result;
392 + }
393 + return parseGeometry();
394 +};
395 +
396 +Parser.prototype.reachedPacketEnd = function() {
397 + return this._offset === this._packetEnd;
398 +};
399 +
400 +Parser.prototype.incrementPacketNumber = function() {
401 + var currentPacketNumber = this._nextPacketNumber;
402 + this._nextPacketNumber = (this._nextPacketNumber + 1) % 256;
403 +
404 + return currentPacketNumber;
405 +};
406 +
407 +Parser.prototype.resetPacketNumber = function() {
408 + this._nextPacketNumber = 0;
409 +};
410 +
411 +Parser.prototype.packetLength = function packetLength() {
412 + if (!this._packetHeader) {
413 + return null;
414 + }
415 +
416 + return this._packetHeader.length + this._longPacketBuffers.size;
417 +};
418 +
419 +Parser.prototype._combineNextBuffers = function _combineNextBuffers(bytes) {
420 + var length = this._buffer.length - this._offset;
421 +
422 + if (length >= bytes) {
423 + return true;
424 + }
425 +
426 + if ((length + this._nextBuffers.size) < bytes) {
427 + return false;
428 + }
429 +
430 + var buffers = [];
431 + var bytesNeeded = bytes - length;
432 +
433 + while (bytesNeeded > 0) {
434 + var buffer = this._nextBuffers.shift();
435 + buffers.push(buffer);
436 + bytesNeeded -= buffer.length;
437 + }
438 +
439 + this.append(buffers);
440 + return true;
441 +};
442 +
443 +Parser.prototype._combineLongPacketBuffers = function _combineLongPacketBuffers() {
444 + if (!this._longPacketBuffers.size) {
445 + return;
446 + }
447 +
448 + // Calculate bytes
449 + var remainingBytes = this._buffer.length - this._offset;
450 + var trailingPacketBytes = this._buffer.length - this._packetEnd;
451 +
452 + // Create buffer
453 + var buf = null;
454 + var buffer = Buffer.allocUnsafe(remainingBytes + this._longPacketBuffers.size);
455 + var offset = 0;
456 +
457 + // Copy long buffers
458 + while ((buf = this._longPacketBuffers.shift())) {
459 + offset += buf.copy(buffer, offset);
460 + }
461 +
462 + // Copy remaining bytes
463 + this._buffer.copy(buffer, offset, this._offset);
464 +
465 + this._buffer = buffer;
466 + this._offset = 0;
467 + this._packetEnd = this._buffer.length - trailingPacketBytes;
468 + this._packetOffset = 0;
469 +};
470 +
471 +Parser.prototype._advanceToNextPacket = function() {
472 + this._offset = this._packetEnd;
473 + this._packetHeader = null;
474 + this._packetEnd = null;
475 + this._packetOffset = null;
476 +};
1 +var Parser = require('./Parser');
2 +var Sequences = require('./sequences');
3 +var Packets = require('./packets');
4 +var Stream = require('stream').Stream;
5 +var Util = require('util');
6 +var PacketWriter = require('./PacketWriter');
7 +
8 +module.exports = Protocol;
9 +Util.inherits(Protocol, Stream);
10 +function Protocol(options) {
11 + Stream.call(this);
12 +
13 + options = options || {};
14 +
15 + this.readable = true;
16 + this.writable = true;
17 +
18 + this._config = options.config || {};
19 + this._connection = options.connection;
20 + this._callback = null;
21 + this._fatalError = null;
22 + this._quitSequence = null;
23 + this._handshake = false;
24 + this._handshaked = false;
25 + this._ended = false;
26 + this._destroyed = false;
27 + this._queue = [];
28 + this._handshakeInitializationPacket = null;
29 +
30 + this._parser = new Parser({
31 + onError : this.handleParserError.bind(this),
32 + onPacket : this._parsePacket.bind(this),
33 + config : this._config
34 + });
35 +}
36 +
37 +Protocol.prototype.write = function(buffer) {
38 + this._parser.write(buffer);
39 + return true;
40 +};
41 +
42 +Protocol.prototype.handshake = function handshake(options, callback) {
43 + if (typeof options === 'function') {
44 + callback = options;
45 + options = {};
46 + }
47 +
48 + options = options || {};
49 + options.config = this._config;
50 +
51 + var sequence = this._enqueue(new Sequences.Handshake(options, callback));
52 +
53 + this._handshake = true;
54 +
55 + return sequence;
56 +};
57 +
58 +Protocol.prototype.query = function query(options, callback) {
59 + return this._enqueue(new Sequences.Query(options, callback));
60 +};
61 +
62 +Protocol.prototype.changeUser = function changeUser(options, callback) {
63 + return this._enqueue(new Sequences.ChangeUser(options, callback));
64 +};
65 +
66 +Protocol.prototype.ping = function ping(options, callback) {
67 + if (typeof options === 'function') {
68 + callback = options;
69 + options = {};
70 + }
71 +
72 + return this._enqueue(new Sequences.Ping(options, callback));
73 +};
74 +
75 +Protocol.prototype.stats = function stats(options, callback) {
76 + if (typeof options === 'function') {
77 + callback = options;
78 + options = {};
79 + }
80 +
81 + return this._enqueue(new Sequences.Statistics(options, callback));
82 +};
83 +
84 +Protocol.prototype.quit = function quit(options, callback) {
85 + if (typeof options === 'function') {
86 + callback = options;
87 + options = {};
88 + }
89 +
90 + var self = this;
91 + var sequence = this._enqueue(new Sequences.Quit(options, callback));
92 +
93 + sequence.on('end', function () {
94 + self.end();
95 + });
96 +
97 + return this._quitSequence = sequence;
98 +};
99 +
100 +Protocol.prototype.end = function() {
101 + if (this._ended) {
102 + return;
103 + }
104 + this._ended = true;
105 +
106 + if (this._quitSequence && (this._quitSequence._ended || this._queue[0] === this._quitSequence)) {
107 + this._quitSequence.end();
108 + this.emit('end');
109 + return;
110 + }
111 +
112 + var err = new Error('Connection lost: The server closed the connection.');
113 + err.fatal = true;
114 + err.code = 'PROTOCOL_CONNECTION_LOST';
115 +
116 + this._delegateError(err);
117 +};
118 +
119 +Protocol.prototype.pause = function() {
120 + this._parser.pause();
121 + // Since there is a file stream in query, we must transmit pause/resume event to current sequence.
122 + var seq = this._queue[0];
123 + if (seq && seq.emit) {
124 + seq.emit('pause');
125 + }
126 +};
127 +
128 +Protocol.prototype.resume = function() {
129 + this._parser.resume();
130 + // Since there is a file stream in query, we must transmit pause/resume event to current sequence.
131 + var seq = this._queue[0];
132 + if (seq && seq.emit) {
133 + seq.emit('resume');
134 + }
135 +};
136 +
137 +Protocol.prototype._enqueue = function(sequence) {
138 + if (!this._validateEnqueue(sequence)) {
139 + return sequence;
140 + }
141 +
142 + if (this._config.trace) {
143 + // Long stack trace support
144 + sequence._callSite = sequence._callSite || new Error();
145 + }
146 +
147 + this._queue.push(sequence);
148 + this.emit('enqueue', sequence);
149 +
150 + var self = this;
151 + sequence
152 + .on('error', function(err) {
153 + self._delegateError(err, sequence);
154 + })
155 + .on('packet', function(packet) {
156 + sequence._timer.active();
157 + self._emitPacket(packet);
158 + })
159 + .on('end', function() {
160 + self._dequeue(sequence);
161 + })
162 + .on('timeout', function() {
163 + var err = new Error(sequence.constructor.name + ' inactivity timeout');
164 +
165 + err.code = 'PROTOCOL_SEQUENCE_TIMEOUT';
166 + err.fatal = true;
167 + err.timeout = sequence._timeout;
168 +
169 + self._delegateError(err, sequence);
170 + })
171 + .on('start-tls', function() {
172 + sequence._timer.active();
173 + self._connection._startTLS(function(err) {
174 + if (err) {
175 + // SSL negotiation error are fatal
176 + err.code = 'HANDSHAKE_SSL_ERROR';
177 + err.fatal = true;
178 + sequence.end(err);
179 + return;
180 + }
181 +
182 + sequence._timer.active();
183 + sequence._tlsUpgradeCompleteHandler();
184 + });
185 + });
186 +
187 + if (this._queue.length === 1) {
188 + this._parser.resetPacketNumber();
189 + this._startSequence(sequence);
190 + }
191 +
192 + return sequence;
193 +};
194 +
195 +Protocol.prototype._validateEnqueue = function _validateEnqueue(sequence) {
196 + var err;
197 + var prefix = 'Cannot enqueue ' + sequence.constructor.name;
198 +
199 + if (this._fatalError) {
200 + err = new Error(prefix + ' after fatal error.');
201 + err.code = 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR';
202 + } else if (this._quitSequence) {
203 + err = new Error(prefix + ' after invoking quit.');
204 + err.code = 'PROTOCOL_ENQUEUE_AFTER_QUIT';
205 + } else if (this._destroyed) {
206 + err = new Error(prefix + ' after being destroyed.');
207 + err.code = 'PROTOCOL_ENQUEUE_AFTER_DESTROY';
208 + } else if ((this._handshake || this._handshaked) && sequence.constructor === Sequences.Handshake) {
209 + err = new Error(prefix + ' after already enqueuing a Handshake.');
210 + err.code = 'PROTOCOL_ENQUEUE_HANDSHAKE_TWICE';
211 + } else {
212 + return true;
213 + }
214 +
215 + var self = this;
216 + err.fatal = false;
217 +
218 + // add error handler
219 + sequence.on('error', function (err) {
220 + self._delegateError(err, sequence);
221 + });
222 +
223 + process.nextTick(function () {
224 + sequence.end(err);
225 + });
226 +
227 + return false;
228 +};
229 +
230 +Protocol.prototype._parsePacket = function() {
231 + var sequence = this._queue[0];
232 +
233 + if (!sequence) {
234 + var err = new Error('Received packet with no active sequence.');
235 + err.code = 'PROTOCOL_STRAY_PACKET';
236 + err.fatal = true;
237 +
238 + this._delegateError(err);
239 + return;
240 + }
241 +
242 + var Packet = this._determinePacket(sequence);
243 + var packet = new Packet({protocol41: this._config.protocol41});
244 + var packetName = Packet.name;
245 +
246 + // Special case: Faster dispatch, and parsing done inside sequence
247 + if (Packet === Packets.RowDataPacket) {
248 + sequence.RowDataPacket(packet, this._parser, this._connection);
249 +
250 + if (this._config.debug) {
251 + this._debugPacket(true, packet);
252 + }
253 +
254 + return;
255 + }
256 +
257 + if (this._config.debug) {
258 + this._parsePacketDebug(packet);
259 + } else {
260 + packet.parse(this._parser);
261 + }
262 +
263 + if (Packet === Packets.HandshakeInitializationPacket) {
264 + this._handshakeInitializationPacket = packet;
265 + }
266 +
267 + sequence._timer.active();
268 +
269 + if (!sequence[packetName]) {
270 + var err = new Error('Received packet in the wrong sequence.');
271 + err.code = 'PROTOCOL_INCORRECT_PACKET_SEQUENCE';
272 + err.fatal = true;
273 +
274 + this._delegateError(err);
275 + return;
276 + }
277 +
278 + sequence[packetName](packet);
279 +};
280 +
281 +Protocol.prototype._parsePacketDebug = function _parsePacketDebug(packet) {
282 + try {
283 + packet.parse(this._parser);
284 + } finally {
285 + this._debugPacket(true, packet);
286 + }
287 +};
288 +
289 +Protocol.prototype._emitPacket = function(packet) {
290 + var packetWriter = new PacketWriter();
291 + packet.write(packetWriter);
292 + this.emit('data', packetWriter.toBuffer(this._parser));
293 +
294 + if (this._config.debug) {
295 + this._debugPacket(false, packet);
296 + }
297 +};
298 +
299 +Protocol.prototype._determinePacket = function(sequence) {
300 + var firstByte = this._parser.peak();
301 +
302 + if (sequence.determinePacket) {
303 + var Packet = sequence.determinePacket(firstByte, this._parser);
304 + if (Packet) {
305 + return Packet;
306 + }
307 + }
308 +
309 + switch (firstByte) {
310 + case 0x00:
311 + if (!this._handshaked) {
312 + this._handshaked = true;
313 + this.emit('handshake', this._handshakeInitializationPacket);
314 + }
315 + return Packets.OkPacket;
316 + case 0xfe: return Packets.EofPacket;
317 + case 0xff: return Packets.ErrorPacket;
318 + }
319 +
320 + throw new Error('Could not determine packet, firstByte = ' + firstByte);
321 +};
322 +
323 +Protocol.prototype._dequeue = function(sequence) {
324 + sequence._timer.stop();
325 +
326 + // No point in advancing the queue, we are dead
327 + if (this._fatalError) {
328 + return;
329 + }
330 +
331 + this._queue.shift();
332 +
333 + var sequence = this._queue[0];
334 + if (!sequence) {
335 + this.emit('drain');
336 + return;
337 + }
338 +
339 + this._parser.resetPacketNumber();
340 +
341 + this._startSequence(sequence);
342 +};
343 +
344 +Protocol.prototype._startSequence = function(sequence) {
345 + if (sequence._timeout > 0 && isFinite(sequence._timeout)) {
346 + sequence._timer.start(sequence._timeout);
347 + }
348 +
349 + if (sequence.constructor === Sequences.ChangeUser) {
350 + sequence.start(this._handshakeInitializationPacket);
351 + } else {
352 + sequence.start();
353 + }
354 +};
355 +
356 +Protocol.prototype.handleNetworkError = function(err) {
357 + err.fatal = true;
358 +
359 + var sequence = this._queue[0];
360 + if (sequence) {
361 + sequence.end(err);
362 + } else {
363 + this._delegateError(err);
364 + }
365 +};
366 +
367 +Protocol.prototype.handleParserError = function handleParserError(err) {
368 + var sequence = this._queue[0];
369 + if (sequence) {
370 + sequence.end(err);
371 + } else {
372 + this._delegateError(err);
373 + }
374 +};
375 +
376 +Protocol.prototype._delegateError = function(err, sequence) {
377 + // Stop delegating errors after the first fatal error
378 + if (this._fatalError) {
379 + return;
380 + }
381 +
382 + if (err.fatal) {
383 + this._fatalError = err;
384 + }
385 +
386 + if (this._shouldErrorBubbleUp(err, sequence)) {
387 + // Can't use regular 'error' event here as that always destroys the pipe
388 + // between socket and protocol which is not what we want (unless the
389 + // exception was fatal).
390 + this.emit('unhandledError', err);
391 + } else if (err.fatal) {
392 + // Send fatal error to all sequences in the queue
393 + var queue = this._queue;
394 + process.nextTick(function () {
395 + queue.forEach(function (sequence) {
396 + sequence.end(err);
397 + });
398 + queue.length = 0;
399 + });
400 + }
401 +
402 + // Make sure the stream we are piping to is getting closed
403 + if (err.fatal) {
404 + this.emit('end', err);
405 + }
406 +};
407 +
408 +Protocol.prototype._shouldErrorBubbleUp = function(err, sequence) {
409 + if (sequence) {
410 + if (sequence.hasErrorHandler()) {
411 + return false;
412 + } else if (!err.fatal) {
413 + return true;
414 + }
415 + }
416 +
417 + return (err.fatal && !this._hasPendingErrorHandlers());
418 +};
419 +
420 +Protocol.prototype._hasPendingErrorHandlers = function() {
421 + return this._queue.some(function(sequence) {
422 + return sequence.hasErrorHandler();
423 + });
424 +};
425 +
426 +Protocol.prototype.destroy = function() {
427 + this._destroyed = true;
428 + this._parser.pause();
429 +
430 + if (this._connection.state !== 'disconnected') {
431 + if (!this._ended) {
432 + this.end();
433 + }
434 + }
435 +};
436 +
437 +Protocol.prototype._debugPacket = function(incoming, packet) {
438 + var connection = this._connection;
439 + var headline = incoming
440 + ? '<-- '
441 + : '--> ';
442 +
443 + if (connection && connection.threadId !== null) {
444 + headline += '(' + connection.threadId + ') ';
445 + }
446 +
447 + headline += packet.constructor.name;
448 +
449 + // check for debug packet restriction
450 + if (Array.isArray(this._config.debug) && this._config.debug.indexOf(packet.constructor.name) === -1) {
451 + return;
452 + }
453 +
454 + console.log(headline);
455 + console.log(packet);
456 + console.log('');
457 +};
1 +module.exports = ResultSet;
2 +function ResultSet(resultSetHeaderPacket) {
3 + this.resultSetHeaderPacket = resultSetHeaderPacket;
4 + this.fieldPackets = [];
5 + this.eofPackets = [];
6 + this.rows = [];
7 +}
1 +module.exports = require('sqlstring');
1 +var Timers = require('timers');
2 +
3 +module.exports = Timer;
4 +function Timer(object) {
5 + this._object = object;
6 + this._timeout = null;
7 +}
8 +
9 +Timer.prototype.active = function active() {
10 + if (this._timeout) {
11 + if (this._timeout.refresh) {
12 + this._timeout.refresh();
13 + } else {
14 + Timers.active(this._timeout);
15 + }
16 + }
17 +};
18 +
19 +Timer.prototype.start = function start(msecs) {
20 + this.stop();
21 + this._timeout = Timers.setTimeout(this._onTimeout.bind(this), msecs);
22 +};
23 +
24 +Timer.prototype.stop = function stop() {
25 + if (this._timeout) {
26 + Timers.clearTimeout(this._timeout);
27 + this._timeout = null;
28 + }
29 +};
30 +
31 +Timer.prototype._onTimeout = function _onTimeout() {
32 + return this._object._onTimeout();
33 +};
1 +exports.BIG5_CHINESE_CI = 1;
2 +exports.LATIN2_CZECH_CS = 2;
3 +exports.DEC8_SWEDISH_CI = 3;
4 +exports.CP850_GENERAL_CI = 4;
5 +exports.LATIN1_GERMAN1_CI = 5;
6 +exports.HP8_ENGLISH_CI = 6;
7 +exports.KOI8R_GENERAL_CI = 7;
8 +exports.LATIN1_SWEDISH_CI = 8;
9 +exports.LATIN2_GENERAL_CI = 9;
10 +exports.SWE7_SWEDISH_CI = 10;
11 +exports.ASCII_GENERAL_CI = 11;
12 +exports.UJIS_JAPANESE_CI = 12;
13 +exports.SJIS_JAPANESE_CI = 13;
14 +exports.CP1251_BULGARIAN_CI = 14;
15 +exports.LATIN1_DANISH_CI = 15;
16 +exports.HEBREW_GENERAL_CI = 16;
17 +exports.TIS620_THAI_CI = 18;
18 +exports.EUCKR_KOREAN_CI = 19;
19 +exports.LATIN7_ESTONIAN_CS = 20;
20 +exports.LATIN2_HUNGARIAN_CI = 21;
21 +exports.KOI8U_GENERAL_CI = 22;
22 +exports.CP1251_UKRAINIAN_CI = 23;
23 +exports.GB2312_CHINESE_CI = 24;
24 +exports.GREEK_GENERAL_CI = 25;
25 +exports.CP1250_GENERAL_CI = 26;
26 +exports.LATIN2_CROATIAN_CI = 27;
27 +exports.GBK_CHINESE_CI = 28;
28 +exports.CP1257_LITHUANIAN_CI = 29;
29 +exports.LATIN5_TURKISH_CI = 30;
30 +exports.LATIN1_GERMAN2_CI = 31;
31 +exports.ARMSCII8_GENERAL_CI = 32;
32 +exports.UTF8_GENERAL_CI = 33;
33 +exports.CP1250_CZECH_CS = 34;
34 +exports.UCS2_GENERAL_CI = 35;
35 +exports.CP866_GENERAL_CI = 36;
36 +exports.KEYBCS2_GENERAL_CI = 37;
37 +exports.MACCE_GENERAL_CI = 38;
38 +exports.MACROMAN_GENERAL_CI = 39;
39 +exports.CP852_GENERAL_CI = 40;
40 +exports.LATIN7_GENERAL_CI = 41;
41 +exports.LATIN7_GENERAL_CS = 42;
42 +exports.MACCE_BIN = 43;
43 +exports.CP1250_CROATIAN_CI = 44;
44 +exports.UTF8MB4_GENERAL_CI = 45;
45 +exports.UTF8MB4_BIN = 46;
46 +exports.LATIN1_BIN = 47;
47 +exports.LATIN1_GENERAL_CI = 48;
48 +exports.LATIN1_GENERAL_CS = 49;
49 +exports.CP1251_BIN = 50;
50 +exports.CP1251_GENERAL_CI = 51;
51 +exports.CP1251_GENERAL_CS = 52;
52 +exports.MACROMAN_BIN = 53;
53 +exports.UTF16_GENERAL_CI = 54;
54 +exports.UTF16_BIN = 55;
55 +exports.UTF16LE_GENERAL_CI = 56;
56 +exports.CP1256_GENERAL_CI = 57;
57 +exports.CP1257_BIN = 58;
58 +exports.CP1257_GENERAL_CI = 59;
59 +exports.UTF32_GENERAL_CI = 60;
60 +exports.UTF32_BIN = 61;
61 +exports.UTF16LE_BIN = 62;
62 +exports.BINARY = 63;
63 +exports.ARMSCII8_BIN = 64;
64 +exports.ASCII_BIN = 65;
65 +exports.CP1250_BIN = 66;
66 +exports.CP1256_BIN = 67;
67 +exports.CP866_BIN = 68;
68 +exports.DEC8_BIN = 69;
69 +exports.GREEK_BIN = 70;
70 +exports.HEBREW_BIN = 71;
71 +exports.HP8_BIN = 72;
72 +exports.KEYBCS2_BIN = 73;
73 +exports.KOI8R_BIN = 74;
74 +exports.KOI8U_BIN = 75;
75 +exports.LATIN2_BIN = 77;
76 +exports.LATIN5_BIN = 78;
77 +exports.LATIN7_BIN = 79;
78 +exports.CP850_BIN = 80;
79 +exports.CP852_BIN = 81;
80 +exports.SWE7_BIN = 82;
81 +exports.UTF8_BIN = 83;
82 +exports.BIG5_BIN = 84;
83 +exports.EUCKR_BIN = 85;
84 +exports.GB2312_BIN = 86;
85 +exports.GBK_BIN = 87;
86 +exports.SJIS_BIN = 88;
87 +exports.TIS620_BIN = 89;
88 +exports.UCS2_BIN = 90;
89 +exports.UJIS_BIN = 91;
90 +exports.GEOSTD8_GENERAL_CI = 92;
91 +exports.GEOSTD8_BIN = 93;
92 +exports.LATIN1_SPANISH_CI = 94;
93 +exports.CP932_JAPANESE_CI = 95;
94 +exports.CP932_BIN = 96;
95 +exports.EUCJPMS_JAPANESE_CI = 97;
96 +exports.EUCJPMS_BIN = 98;
97 +exports.CP1250_POLISH_CI = 99;
98 +exports.UTF16_UNICODE_CI = 101;
99 +exports.UTF16_ICELANDIC_CI = 102;
100 +exports.UTF16_LATVIAN_CI = 103;
101 +exports.UTF16_ROMANIAN_CI = 104;
102 +exports.UTF16_SLOVENIAN_CI = 105;
103 +exports.UTF16_POLISH_CI = 106;
104 +exports.UTF16_ESTONIAN_CI = 107;
105 +exports.UTF16_SPANISH_CI = 108;
106 +exports.UTF16_SWEDISH_CI = 109;
107 +exports.UTF16_TURKISH_CI = 110;
108 +exports.UTF16_CZECH_CI = 111;
109 +exports.UTF16_DANISH_CI = 112;
110 +exports.UTF16_LITHUANIAN_CI = 113;
111 +exports.UTF16_SLOVAK_CI = 114;
112 +exports.UTF16_SPANISH2_CI = 115;
113 +exports.UTF16_ROMAN_CI = 116;
114 +exports.UTF16_PERSIAN_CI = 117;
115 +exports.UTF16_ESPERANTO_CI = 118;
116 +exports.UTF16_HUNGARIAN_CI = 119;
117 +exports.UTF16_SINHALA_CI = 120;
118 +exports.UTF16_GERMAN2_CI = 121;
119 +exports.UTF16_CROATIAN_MYSQL561_CI = 122;
120 +exports.UTF16_UNICODE_520_CI = 123;
121 +exports.UTF16_VIETNAMESE_CI = 124;
122 +exports.UCS2_UNICODE_CI = 128;
123 +exports.UCS2_ICELANDIC_CI = 129;
124 +exports.UCS2_LATVIAN_CI = 130;
125 +exports.UCS2_ROMANIAN_CI = 131;
126 +exports.UCS2_SLOVENIAN_CI = 132;
127 +exports.UCS2_POLISH_CI = 133;
128 +exports.UCS2_ESTONIAN_CI = 134;
129 +exports.UCS2_SPANISH_CI = 135;
130 +exports.UCS2_SWEDISH_CI = 136;
131 +exports.UCS2_TURKISH_CI = 137;
132 +exports.UCS2_CZECH_CI = 138;
133 +exports.UCS2_DANISH_CI = 139;
134 +exports.UCS2_LITHUANIAN_CI = 140;
135 +exports.UCS2_SLOVAK_CI = 141;
136 +exports.UCS2_SPANISH2_CI = 142;
137 +exports.UCS2_ROMAN_CI = 143;
138 +exports.UCS2_PERSIAN_CI = 144;
139 +exports.UCS2_ESPERANTO_CI = 145;
140 +exports.UCS2_HUNGARIAN_CI = 146;
141 +exports.UCS2_SINHALA_CI = 147;
142 +exports.UCS2_GERMAN2_CI = 148;
143 +exports.UCS2_CROATIAN_MYSQL561_CI = 149;
144 +exports.UCS2_UNICODE_520_CI = 150;
145 +exports.UCS2_VIETNAMESE_CI = 151;
146 +exports.UCS2_GENERAL_MYSQL500_CI = 159;
147 +exports.UTF32_UNICODE_CI = 160;
148 +exports.UTF32_ICELANDIC_CI = 161;
149 +exports.UTF32_LATVIAN_CI = 162;
150 +exports.UTF32_ROMANIAN_CI = 163;
151 +exports.UTF32_SLOVENIAN_CI = 164;
152 +exports.UTF32_POLISH_CI = 165;
153 +exports.UTF32_ESTONIAN_CI = 166;
154 +exports.UTF32_SPANISH_CI = 167;
155 +exports.UTF32_SWEDISH_CI = 168;
156 +exports.UTF32_TURKISH_CI = 169;
157 +exports.UTF32_CZECH_CI = 170;
158 +exports.UTF32_DANISH_CI = 171;
159 +exports.UTF32_LITHUANIAN_CI = 172;
160 +exports.UTF32_SLOVAK_CI = 173;
161 +exports.UTF32_SPANISH2_CI = 174;
162 +exports.UTF32_ROMAN_CI = 175;
163 +exports.UTF32_PERSIAN_CI = 176;
164 +exports.UTF32_ESPERANTO_CI = 177;
165 +exports.UTF32_HUNGARIAN_CI = 178;
166 +exports.UTF32_SINHALA_CI = 179;
167 +exports.UTF32_GERMAN2_CI = 180;
168 +exports.UTF32_CROATIAN_MYSQL561_CI = 181;
169 +exports.UTF32_UNICODE_520_CI = 182;
170 +exports.UTF32_VIETNAMESE_CI = 183;
171 +exports.UTF8_UNICODE_CI = 192;
172 +exports.UTF8_ICELANDIC_CI = 193;
173 +exports.UTF8_LATVIAN_CI = 194;
174 +exports.UTF8_ROMANIAN_CI = 195;
175 +exports.UTF8_SLOVENIAN_CI = 196;
176 +exports.UTF8_POLISH_CI = 197;
177 +exports.UTF8_ESTONIAN_CI = 198;
178 +exports.UTF8_SPANISH_CI = 199;
179 +exports.UTF8_SWEDISH_CI = 200;
180 +exports.UTF8_TURKISH_CI = 201;
181 +exports.UTF8_CZECH_CI = 202;
182 +exports.UTF8_DANISH_CI = 203;
183 +exports.UTF8_LITHUANIAN_CI = 204;
184 +exports.UTF8_SLOVAK_CI = 205;
185 +exports.UTF8_SPANISH2_CI = 206;
186 +exports.UTF8_ROMAN_CI = 207;
187 +exports.UTF8_PERSIAN_CI = 208;
188 +exports.UTF8_ESPERANTO_CI = 209;
189 +exports.UTF8_HUNGARIAN_CI = 210;
190 +exports.UTF8_SINHALA_CI = 211;
191 +exports.UTF8_GERMAN2_CI = 212;
192 +exports.UTF8_CROATIAN_MYSQL561_CI = 213;
193 +exports.UTF8_UNICODE_520_CI = 214;
194 +exports.UTF8_VIETNAMESE_CI = 215;
195 +exports.UTF8_GENERAL_MYSQL500_CI = 223;
196 +exports.UTF8MB4_UNICODE_CI = 224;
197 +exports.UTF8MB4_ICELANDIC_CI = 225;
198 +exports.UTF8MB4_LATVIAN_CI = 226;
199 +exports.UTF8MB4_ROMANIAN_CI = 227;
200 +exports.UTF8MB4_SLOVENIAN_CI = 228;
201 +exports.UTF8MB4_POLISH_CI = 229;
202 +exports.UTF8MB4_ESTONIAN_CI = 230;
203 +exports.UTF8MB4_SPANISH_CI = 231;
204 +exports.UTF8MB4_SWEDISH_CI = 232;
205 +exports.UTF8MB4_TURKISH_CI = 233;
206 +exports.UTF8MB4_CZECH_CI = 234;
207 +exports.UTF8MB4_DANISH_CI = 235;
208 +exports.UTF8MB4_LITHUANIAN_CI = 236;
209 +exports.UTF8MB4_SLOVAK_CI = 237;
210 +exports.UTF8MB4_SPANISH2_CI = 238;
211 +exports.UTF8MB4_ROMAN_CI = 239;
212 +exports.UTF8MB4_PERSIAN_CI = 240;
213 +exports.UTF8MB4_ESPERANTO_CI = 241;
214 +exports.UTF8MB4_HUNGARIAN_CI = 242;
215 +exports.UTF8MB4_SINHALA_CI = 243;
216 +exports.UTF8MB4_GERMAN2_CI = 244;
217 +exports.UTF8MB4_CROATIAN_MYSQL561_CI = 245;
218 +exports.UTF8MB4_UNICODE_520_CI = 246;
219 +exports.UTF8MB4_VIETNAMESE_CI = 247;
220 +exports.UTF8_GENERAL50_CI = 253;
221 +
222 +// short aliases
223 +exports.ARMSCII8 = exports.ARMSCII8_GENERAL_CI;
224 +exports.ASCII = exports.ASCII_GENERAL_CI;
225 +exports.BIG5 = exports.BIG5_CHINESE_CI;
226 +exports.BINARY = exports.BINARY;
227 +exports.CP1250 = exports.CP1250_GENERAL_CI;
228 +exports.CP1251 = exports.CP1251_GENERAL_CI;
229 +exports.CP1256 = exports.CP1256_GENERAL_CI;
230 +exports.CP1257 = exports.CP1257_GENERAL_CI;
231 +exports.CP866 = exports.CP866_GENERAL_CI;
232 +exports.CP850 = exports.CP850_GENERAL_CI;
233 +exports.CP852 = exports.CP852_GENERAL_CI;
234 +exports.CP932 = exports.CP932_JAPANESE_CI;
235 +exports.DEC8 = exports.DEC8_SWEDISH_CI;
236 +exports.EUCJPMS = exports.EUCJPMS_JAPANESE_CI;
237 +exports.EUCKR = exports.EUCKR_KOREAN_CI;
238 +exports.GB2312 = exports.GB2312_CHINESE_CI;
239 +exports.GBK = exports.GBK_CHINESE_CI;
240 +exports.GEOSTD8 = exports.GEOSTD8_GENERAL_CI;
241 +exports.GREEK = exports.GREEK_GENERAL_CI;
242 +exports.HEBREW = exports.HEBREW_GENERAL_CI;
243 +exports.HP8 = exports.HP8_ENGLISH_CI;
244 +exports.KEYBCS2 = exports.KEYBCS2_GENERAL_CI;
245 +exports.KOI8R = exports.KOI8R_GENERAL_CI;
246 +exports.KOI8U = exports.KOI8U_GENERAL_CI;
247 +exports.LATIN1 = exports.LATIN1_SWEDISH_CI;
248 +exports.LATIN2 = exports.LATIN2_GENERAL_CI;
249 +exports.LATIN5 = exports.LATIN5_TURKISH_CI;
250 +exports.LATIN7 = exports.LATIN7_GENERAL_CI;
251 +exports.MACCE = exports.MACCE_GENERAL_CI;
252 +exports.MACROMAN = exports.MACROMAN_GENERAL_CI;
253 +exports.SJIS = exports.SJIS_JAPANESE_CI;
254 +exports.SWE7 = exports.SWE7_SWEDISH_CI;
255 +exports.TIS620 = exports.TIS620_THAI_CI;
256 +exports.UCS2 = exports.UCS2_GENERAL_CI;
257 +exports.UJIS = exports.UJIS_JAPANESE_CI;
258 +exports.UTF16 = exports.UTF16_GENERAL_CI;
259 +exports.UTF16LE = exports.UTF16LE_GENERAL_CI;
260 +exports.UTF8 = exports.UTF8_GENERAL_CI;
261 +exports.UTF8MB4 = exports.UTF8MB4_GENERAL_CI;
262 +exports.UTF32 = exports.UTF32_GENERAL_CI;
1 +// Manually extracted from mysql-5.5.23/include/mysql_com.h
2 +exports.CLIENT_LONG_PASSWORD = 1; /* new more secure passwords */
3 +exports.CLIENT_FOUND_ROWS = 2; /* Found instead of affected rows */
4 +exports.CLIENT_LONG_FLAG = 4; /* Get all column flags */
5 +exports.CLIENT_CONNECT_WITH_DB = 8; /* One can specify db on connect */
6 +exports.CLIENT_NO_SCHEMA = 16; /* Don't allow database.table.column */
7 +exports.CLIENT_COMPRESS = 32; /* Can use compression protocol */
8 +exports.CLIENT_ODBC = 64; /* Odbc client */
9 +exports.CLIENT_LOCAL_FILES = 128; /* Can use LOAD DATA LOCAL */
10 +exports.CLIENT_IGNORE_SPACE = 256; /* Ignore spaces before '(' */
11 +exports.CLIENT_PROTOCOL_41 = 512; /* New 4.1 protocol */
12 +exports.CLIENT_INTERACTIVE = 1024; /* This is an interactive client */
13 +exports.CLIENT_SSL = 2048; /* Switch to SSL after handshake */
14 +exports.CLIENT_IGNORE_SIGPIPE = 4096; /* IGNORE sigpipes */
15 +exports.CLIENT_TRANSACTIONS = 8192; /* Client knows about transactions */
16 +exports.CLIENT_RESERVED = 16384; /* Old flag for 4.1 protocol */
17 +exports.CLIENT_SECURE_CONNECTION = 32768; /* New 4.1 authentication */
18 +
19 +exports.CLIENT_MULTI_STATEMENTS = 65536; /* Enable/disable multi-stmt support */
20 +exports.CLIENT_MULTI_RESULTS = 131072; /* Enable/disable multi-results */
21 +exports.CLIENT_PS_MULTI_RESULTS = 262144; /* Multi-results in PS-protocol */
22 +
23 +exports.CLIENT_PLUGIN_AUTH = 524288; /* Client supports plugin authentication */
24 +
25 +exports.CLIENT_SSL_VERIFY_SERVER_CERT = 1073741824;
26 +exports.CLIENT_REMEMBER_OPTIONS = 2147483648;
This diff could not be displayed because it is too large.
1 +// Manually extracted from mysql-5.5.23/include/mysql_com.h
2 +exports.NOT_NULL_FLAG = 1; /* Field can't be NULL */
3 +exports.PRI_KEY_FLAG = 2; /* Field is part of a primary key */
4 +exports.UNIQUE_KEY_FLAG = 4; /* Field is part of a unique key */
5 +exports.MULTIPLE_KEY_FLAG = 8; /* Field is part of a key */
6 +exports.BLOB_FLAG = 16; /* Field is a blob */
7 +exports.UNSIGNED_FLAG = 32; /* Field is unsigned */
8 +exports.ZEROFILL_FLAG = 64; /* Field is zerofill */
9 +exports.BINARY_FLAG = 128; /* Field is binary */
10 +
11 +/* The following are only sent to new clients */
12 +exports.ENUM_FLAG = 256; /* field is an enum */
13 +exports.AUTO_INCREMENT_FLAG = 512; /* field is a autoincrement field */
14 +exports.TIMESTAMP_FLAG = 1024; /* Field is a timestamp */
15 +exports.SET_FLAG = 2048; /* field is a set */
16 +exports.NO_DEFAULT_VALUE_FLAG = 4096; /* Field doesn't have default value */
17 +exports.ON_UPDATE_NOW_FLAG = 8192; /* Field is set to NOW on UPDATE */
18 +exports.NUM_FLAG = 32768; /* Field is num (for clients) */
1 +// Manually extracted from mysql-5.5.23/include/mysql_com.h
2 +
3 +/**
4 + Is raised when a multi-statement transaction
5 + has been started, either explicitly, by means
6 + of BEGIN or COMMIT AND CHAIN, or
7 + implicitly, by the first transactional
8 + statement, when autocommit=off.
9 +*/
10 +exports.SERVER_STATUS_IN_TRANS = 1;
11 +exports.SERVER_STATUS_AUTOCOMMIT = 2; /* Server in auto_commit mode */
12 +exports.SERVER_MORE_RESULTS_EXISTS = 8; /* Multi query - next query exists */
13 +exports.SERVER_QUERY_NO_GOOD_INDEX_USED = 16;
14 +exports.SERVER_QUERY_NO_INDEX_USED = 32;
15 +/**
16 + The server was able to fulfill the clients request and opened a
17 + read-only non-scrollable cursor for a query. This flag comes
18 + in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands.
19 +*/
20 +exports.SERVER_STATUS_CURSOR_EXISTS = 64;
21 +/**
22 + This flag is sent when a read-only cursor is exhausted, in reply to
23 + COM_STMT_FETCH command.
24 +*/
25 +exports.SERVER_STATUS_LAST_ROW_SENT = 128;
26 +exports.SERVER_STATUS_DB_DROPPED = 256; /* A database was dropped */
27 +exports.SERVER_STATUS_NO_BACKSLASH_ESCAPES = 512;
28 +/**
29 + Sent to the client if after a prepared statement reprepare
30 + we discovered that the new statement returns a different
31 + number of result set columns.
32 +*/
33 +exports.SERVER_STATUS_METADATA_CHANGED = 1024;
34 +exports.SERVER_QUERY_WAS_SLOW = 2048;
35 +
36 +/**
37 + To mark ResultSet containing output parameter values.
38 +*/
39 +exports.SERVER_PS_OUT_PARAMS = 4096;
1 +// Certificates for Amazon RDS
2 +exports['Amazon RDS'] = {
3 + ca: [
4 + /**
5 + * Amazon RDS global certificate 2010 to 2015
6 + *
7 + * CN = aws.amazon.com/rds/
8 + * OU = RDS
9 + * O = Amazon.com
10 + * L = Seattle
11 + * ST = Washington
12 + * C = US
13 + * P = 2010-04-05T22:44:31Z/2015-04-04T22:41:31Z
14 + * F = 7F:09:8D:A5:7D:BB:A6:EF:7C:70:D8:CA:4E:49:11:55:7E:89:A7:D3
15 + */
16 + '-----BEGIN CERTIFICATE-----\n'
17 + + 'MIIDQzCCAqygAwIBAgIJAOd1tlfiGoEoMA0GCSqGSIb3DQEBBQUAMHUxCzAJBgNV\n'
18 + + 'BAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdTZWF0dGxlMRMw\n'
19 + + 'EQYDVQQKEwpBbWF6b24uY29tMQwwCgYDVQQLEwNSRFMxHDAaBgNVBAMTE2F3cy5h\n'
20 + + 'bWF6b24uY29tL3Jkcy8wHhcNMTAwNDA1MjI0NDMxWhcNMTUwNDA0MjI0NDMxWjB1\n'
21 + + 'MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHU2Vh\n'
22 + + 'dHRsZTETMBEGA1UEChMKQW1hem9uLmNvbTEMMAoGA1UECxMDUkRTMRwwGgYDVQQD\n'
23 + + 'ExNhd3MuYW1hem9uLmNvbS9yZHMvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n'
24 + + 'gQDKhXGU7tizxUR5WaFoMTFcxNxa05PEjZaIOEN5ctkWrqYSRov0/nOMoZjqk8bC\n'
25 + + 'med9vPFoQGD0OTakPs0jVe3wwmR735hyVwmKIPPsGlaBYj1O6llIpZeQVyupNx56\n'
26 + + 'UzqtiLaDzh1KcmfqP3qP2dInzBfJQKjiRudo1FWnpPt33QIDAQABo4HaMIHXMB0G\n'
27 + + 'A1UdDgQWBBT/H3x+cqSkR/ePSIinPtc4yWKe3DCBpwYDVR0jBIGfMIGcgBT/H3x+\n'
28 + + 'cqSkR/ePSIinPtc4yWKe3KF5pHcwdTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldh\n'
29 + + 'c2hpbmd0b24xEDAOBgNVBAcTB1NlYXR0bGUxEzARBgNVBAoTCkFtYXpvbi5jb20x\n'
30 + + 'DDAKBgNVBAsTA1JEUzEcMBoGA1UEAxMTYXdzLmFtYXpvbi5jb20vcmRzL4IJAOd1\n'
31 + + 'tlfiGoEoMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAvguZy/BDT66x\n'
32 + + 'GfgnJlyQwnFSeVLQm9u/FIvz4huGjbq9dqnD6h/Gm56QPFdyMEyDiZWaqY6V08lY\n'
33 + + 'LTBNb4kcIc9/6pc0/ojKciP5QJRm6OiZ4vgG05nF4fYjhU7WClUx7cxq1fKjNc2J\n'
34 + + 'UCmmYqgiVkAGWRETVo+byOSDZ4swb10=\n'
35 + + '-----END CERTIFICATE-----\n',
36 +
37 + /**
38 + * Amazon RDS global root CA 2015 to 2020
39 + *
40 + * CN = Amazon RDS Root CA
41 + * OU = Amazon RDS
42 + * O = Amazon Web Services, Inc.
43 + * L = Seattle
44 + * ST = Washington
45 + * C = US
46 + * P = 2015-02-05T09:11:31Z/2020-03-05T09:11:31Z
47 + * F = E8:11:88:56:E7:A7:CE:3E:5E:DC:9A:31:25:1B:93:AC:DC:43:CE:B0
48 + */
49 + '-----BEGIN CERTIFICATE-----\n'
50 + + 'MIID9DCCAtygAwIBAgIBQjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
51 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
52 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
53 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUwOTExMzFaFw0y\n'
54 + + 'MDAzMDUwOTExMzFaMIGKMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
55 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
56 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEbMBkGA1UEAwwSQW1hem9uIFJE\n'
57 + + 'UyBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuD8nrZ8V\n'
58 + + 'u+VA8yVlUipCZIKPTDcOILYpUe8Tct0YeQQr0uyl018StdBsa3CjBgvwpDRq1HgF\n'
59 + + 'Ji2N3+39+shCNspQeE6aYU+BHXhKhIIStt3r7gl/4NqYiDDMWKHxHq0nsGDFfArf\n'
60 + + 'AOcjZdJagOMqb3fF46flc8k2E7THTm9Sz4L7RY1WdABMuurpICLFE3oHcGdapOb9\n'
61 + + 'T53pQR+xpHW9atkcf3pf7gbO0rlKVSIoUenBlZipUlp1VZl/OD/E+TtRhDDNdI2J\n'
62 + + 'P/DSMM3aEsq6ZQkfbz/Ilml+Lx3tJYXUDmp+ZjzMPLk/+3beT8EhrwtcG3VPpvwp\n'
63 + + 'BIOqsqVVTvw/CwIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw\n'
64 + + 'AwEB/zAdBgNVHQ4EFgQUTgLurD72FchM7Sz1BcGPnIQISYMwHwYDVR0jBBgwFoAU\n'
65 + + 'TgLurD72FchM7Sz1BcGPnIQISYMwDQYJKoZIhvcNAQEFBQADggEBAHZcgIio8pAm\n'
66 + + 'MjHD5cl6wKjXxScXKtXygWH2BoDMYBJF9yfyKO2jEFxYKbHePpnXB1R04zJSWAw5\n'
67 + + '2EUuDI1pSBh9BA82/5PkuNlNeSTB3dXDD2PEPdzVWbSKvUB8ZdooV+2vngL0Zm4r\n'
68 + + '47QPyd18yPHrRIbtBtHR/6CwKevLZ394zgExqhnekYKIqqEX41xsUV0Gm6x4vpjf\n'
69 + + '2u6O/+YE2U+qyyxHE5Wd5oqde0oo9UUpFETJPVb6Q2cEeQib8PBAyi0i6KnF+kIV\n'
70 + + 'A9dY7IHSubtCK/i8wxMVqfd5GtbA8mmpeJFwnDvm9rBEsHybl08qlax9syEwsUYr\n'
71 + + '/40NawZfTUU=\n'
72 + + '-----END CERTIFICATE-----\n',
73 +
74 + /**
75 + * Amazon RDS ap-northeast-1 certificate CA 2015 to 2020
76 + *
77 + * CN = Amazon RDS ap-northeast-1 CA
78 + * OU = Amazon RDS
79 + * O = Amazon Web Services, Inc.
80 + * L = Seattle
81 + * ST = Washington
82 + * C = US
83 + * P = 2015-02-05T22:03:06Z/2020-03-05T22:03:06Z
84 + * F = 4B:2D:8A:E0:C1:A3:A9:AF:A7:BB:65:0C:5A:16:8A:39:3C:03:F2:C5
85 + */
86 + '-----BEGIN CERTIFICATE-----\n'
87 + + 'MIIEATCCAumgAwIBAgIBRDANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
88 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
89 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
90 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMDZaFw0y\n'
91 + + 'MDAzMDUyMjAzMDZaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
92 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
93 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n'
94 + + 'UyBhcC1ub3J0aGVhc3QtMSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n'
95 + + 'ggEBAMmM2B4PfTXCZjbZMWiDPyxvk/eeNwIRJAhfzesiGUiLozX6CRy3rwC1ZOPV\n'
96 + + 'AcQf0LB+O8wY88C/cV+d4Q2nBDmnk+Vx7o2MyMh343r5rR3Na+4izd89tkQVt0WW\n'
97 + + 'vO21KRH5i8EuBjinboOwAwu6IJ+HyiQiM0VjgjrmEr/YzFPL8MgHD/YUHehqjACn\n'
98 + + 'C0+B7/gu7W4qJzBL2DOf7ub2qszGtwPE+qQzkCRDwE1A4AJmVE++/FLH2Zx78Egg\n'
99 + + 'fV1sUxPtYgjGH76VyyO6GNKM6rAUMD/q5mnPASQVIXgKbupr618bnH+SWHFjBqZq\n'
100 + + 'HvDGPMtiiWII41EmGUypyt5AbysCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n'
101 + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFIiKM0Q6n1K4EmLxs3ZXxINbwEwR\n'
102 + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n'
103 + + 'A4IBAQBezGbE9Rw/k2e25iGjj5n8r+M3dlye8ORfCE/dijHtxqAKasXHgKX8I9Tw\n'
104 + + 'JkBiGWiuzqn7gO5MJ0nMMro1+gq29qjZnYX1pDHPgsRjUX8R+juRhgJ3JSHijRbf\n'
105 + + '4qNJrnwga7pj94MhcLq9u0f6dxH6dXbyMv21T4TZMTmcFduf1KgaiVx1PEyJjC6r\n'
106 + + 'M+Ru+A0eM+jJ7uCjUoZKcpX8xkj4nmSnz9NMPog3wdOSB9cAW7XIc5mHa656wr7I\n'
107 + + 'WJxVcYNHTXIjCcng2zMKd1aCcl2KSFfy56sRfT7J5Wp69QSr+jq8KM55gw8uqAwi\n'
108 + + 'VPrXn2899T1rcTtFYFP16WXjGuc0\n'
109 + + '-----END CERTIFICATE-----\n',
110 +
111 + /**
112 + * Amazon RDS ap-northeast-2 certificate CA 2015 to 2020
113 + *
114 + * CN = Amazon RDS ap-northeast-2 CA
115 + * OU = Amazon RDS
116 + * O = Amazon Web Services, Inc.
117 + * L = Seattle
118 + * ST = Washington
119 + * C = US
120 + * P = 2015-11-06T00:05:46Z/2020-03-05T00:05:46Z
121 + * F = 77:D9:33:4E:CE:56:FC:42:7B:29:57:8D:67:59:ED:29:4E:18:CB:6B
122 + */
123 + '-----BEGIN CERTIFICATE-----\n'
124 + + 'MIIEATCCAumgAwIBAgIBTDANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
125 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
126 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
127 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTExMDYwMDA1NDZaFw0y\n'
128 + + 'MDAzMDUwMDA1NDZaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
129 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
130 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n'
131 + + 'UyBhcC1ub3J0aGVhc3QtMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n'
132 + + 'ggEBAKSwd+RVUzTRH0FgnbwoTK8TMm/zMT4+2BvALpAUe6YXbkisg2goycWuuWLg\n'
133 + + 'jOpFBB3GtyvXZnkqi7MkDWUmj1a2kf8l2oLyoaZ+Hm9x/sV+IJzOqPvj1XVUGjP6\n'
134 + + 'yYYnPJmUYqvZeI7fEkIGdFkP2m4/sgsSGsFvpD9FK1bL1Kx2UDpYX0kHTtr18Zm/\n'
135 + + '1oN6irqWALSmXMDydb8hE0FB2A1VFyeKE6PnoDj/Y5cPHwPPdEi6/3gkDkSaOG30\n'
136 + + 'rWeQfL3pOcKqzbHaWTxMphd0DSL/quZ64Nr+Ly65Q5PRcTrtr55ekOUziuqXwk+o\n'
137 + + '9QpACMwcJ7ROqOznZTqTzSFVXFECAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n'
138 + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFM6Nox/QWbhzWVvzoJ/y0kGpNPK+\n'
139 + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n'
140 + + 'A4IBAQCTkWBqNvyRf3Y/W21DwFx3oT/AIWrHt0BdGZO34tavummXemTH9LZ/mqv9\n'
141 + + 'aljt6ZuDtf5DEQjdsAwXMsyo03ffnP7doWm8iaF1+Mui77ot0TmTsP/deyGwukvJ\n'
142 + + 'tkxX8bZjDh+EaNauWKr+CYnniNxCQLfFtXYJsfOdVBzK3xNL+Z3ucOQRhr2helWc\n'
143 + + 'CDQgwfhP1+3pRVKqHvWCPC4R3fT7RZHuRmZ38kndv476GxRntejh+ePffif78bFI\n'
144 + + '3rIZCPBGobrrUMycafSbyXteoGca/kA+/IqrAPlk0pWQ4aEL0yTWN2h2dnjoD7oX\n'
145 + + 'byIuL/g9AGRh97+ssn7D6bDRPTbW\n'
146 + + '-----END CERTIFICATE-----\n',
147 +
148 + /**
149 + * Amazon RDS ap-southeast-1 certificate CA 2015 to 2020
150 + *
151 + * CN = Amazon RDS ap-southeast-1 CA
152 + * OU = Amazon RDS
153 + * O = Amazon Web Services, Inc.
154 + * L = Seattle
155 + * ST = Washington
156 + * C = US
157 + * P = 2015-02-05T22:03:19Z/2020-03-05T22:03:19Z
158 + * F = 0E:EC:5D:BD:F9:80:EE:A9:A0:8D:81:AC:37:D9:8D:34:1C:CD:27:D1
159 + */
160 + '-----BEGIN CERTIFICATE-----\n'
161 + + 'MIIEATCCAumgAwIBAgIBRTANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
162 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
163 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
164 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMTlaFw0y\n'
165 + + 'MDAzMDUyMjAzMTlaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
166 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
167 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n'
168 + + 'UyBhcC1zb3V0aGVhc3QtMSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n'
169 + + 'ggEBANaXElmSEYt/UtxHFsARFhSUahTf1KNJzR0Dmay6hqOXQuRVbKRwPd19u5vx\n'
170 + + 'DdF1sLT7D69IK3VDnUiQScaCv2Dpu9foZt+rLx+cpx1qiQd1UHrvqq8xPzQOqCdC\n'
171 + + 'RFStq6yVYZ69yfpfoI67AjclMOjl2Vph3ftVnqP0IgVKZdzeC7fd+umGgR9xY0Qr\n'
172 + + 'Ubhd/lWdsbNvzK3f1TPWcfIKQnpvSt85PIEDJir6/nuJUKMtmJRwTymJf0i+JZ4x\n'
173 + + '7dJa341p2kHKcHMgOPW7nJQklGBA70ytjUV6/qebS3yIugr/28mwReflg3TJzVDl\n'
174 + + 'EOvi6pqbqNbkMuEwGDCmEQIVqgkCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n'
175 + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFAu93/4k5xbWOsgdCdn+/KdiRuit\n'
176 + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n'
177 + + 'A4IBAQBlcjSyscpPjf5+MgzMuAsCxByqUt+WFspwcMCpwdaBeHOPSQrXNqX2Sk6P\n'
178 + + 'kth6oCivA64trWo8tFMvPYlUA1FYVD5WpN0kCK+P5pD4KHlaDsXhuhClJzp/OP8t\n'
179 + + 'pOyUr5109RHLxqoKB5J5m1XA7rgcFjnMxwBSWFe3/4uMk/+4T53YfCVXuc6QV3i7\n'
180 + + 'I/2LAJwFf//pTtt6fZenYfCsahnr2nvrNRNyAxcfvGZ/4Opn/mJtR6R/AjvQZHiR\n'
181 + + 'bkRNKF2GW0ueK5W4FkZVZVhhX9xh1Aj2Ollb+lbOqADaVj+AT3PoJPZ3MPQHKCXm\n'
182 + + 'xwG0LOLlRr/TfD6li1AfOVTAJXv9\n'
183 + + '-----END CERTIFICATE-----\n',
184 +
185 + /**
186 + * Amazon RDS ap-southeast-2 certificate CA 2015 to 2020
187 + *
188 + * CN = Amazon RDS ap-southeast-2 CA
189 + * OU = Amazon RDS
190 + * O = Amazon Web Services, Inc.
191 + * L = Seattle
192 + * ST = Washington
193 + * C = US
194 + * P = 2015-02-05T22:03:24Z/2020-03-05T22:03:24Z
195 + * F = 20:D9:A8:82:23:AB:B9:E5:C5:24:10:D3:4D:0F:3D:B1:31:DF:E5:14
196 + */
197 + '-----BEGIN CERTIFICATE-----\n'
198 + + 'MIIEATCCAumgAwIBAgIBRjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
199 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
200 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
201 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMjRaFw0y\n'
202 + + 'MDAzMDUyMjAzMjRaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
203 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
204 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n'
205 + + 'UyBhcC1zb3V0aGVhc3QtMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n'
206 + + 'ggEBAJqBAJutz69hFOh3BtLHZTbwE8eejGGKayn9hu98YMDPzWzGXWCmW+ZYWELA\n'
207 + + 'cY3cNWNF8K4FqKXFr2ssorBYim1UtYFX8yhydT2hMD5zgQ2sCGUpuidijuPA6zaq\n'
208 + + 'Z3tdhVR94f0q8mpwpv2zqR9PcqaGDx2VR1x773FupRPRo7mEW1vC3IptHCQlP/zE\n'
209 + + '7jQiLl28bDIH2567xg7e7E9WnZToRnhlYdTaDaJsHTzi5mwILi4cihSok7Shv/ME\n'
210 + + 'hnukvxeSPUpaVtFaBhfBqq055ePq9I+Ns4KGreTKMhU0O9fkkaBaBmPaFgmeX/XO\n'
211 + + 'n2AX7gMouo3mtv34iDTZ0h6YCGkCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n'
212 + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFIlQnY0KHYWn1jYumSdJYfwj/Nfw\n'
213 + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n'
214 + + 'A4IBAQA0wVU6/l41cTzHc4azc4CDYY2Wd90DFWiH9C/mw0SgToYfCJ/5Cfi0NT/Y\n'
215 + + 'PRnk3GchychCJgoPA/k9d0//IhYEAIiIDjyFVgjbTkKV3sh4RbdldKVOUB9kumz/\n'
216 + + 'ZpShplsGt3z4QQiVnKfrAgqxWDjR0I0pQKkxXa6Sjkicos9LQxVtJ0XA4ieG1E7z\n'
217 + + 'zJr+6t80wmzxvkInSaWP3xNJK9azVRTrgQZQlvkbpDbExl4mNTG66VD3bAp6t3Wa\n'
218 + + 'B49//uDdfZmPkqqbX+hsxp160OH0rxJppwO3Bh869PkDnaPEd/Pxw7PawC+li0gi\n'
219 + + 'NRV8iCEx85aFxcyOhqn0WZOasxee\n'
220 + + '-----END CERTIFICATE-----\n',
221 +
222 + /**
223 + * Amazon RDS eu-central-1 certificate CA 2015 to 2020
224 + *
225 + * CN = Amazon RDS eu-central-1 CA
226 + * OU = Amazon RDS
227 + * O = Amazon Web Services, Inc.
228 + * L = Seattle
229 + * ST = Washington
230 + * C = US
231 + * P = 2015-02-05T22:03:31Z/2020-03-05T22:03:31Z
232 + * F = 94:B4:DF:B9:6D:7E:F7:C3:B7:BF:51:E9:A6:B7:44:A0:D0:82:11:84
233 + */
234 + '-----BEGIN CERTIFICATE-----\n'
235 + + 'MIID/zCCAuegAwIBAgIBRzANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
236 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
237 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
238 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMzFaFw0y\n'
239 + + 'MDAzMDUyMjAzMzFaMIGSMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
240 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
241 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEjMCEGA1UEAwwaQW1hem9uIFJE\n'
242 + + 'UyBldS1jZW50cmFsLTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n'
243 + + 'AQDFtP2dhSLuaPOI4ZrrPWsK4OY9ocQBp3yApH1KJYmI9wpQKZG/KCH2E6Oo7JAw\n'
244 + + 'QORU519r033T+FO2Z7pFPlmz1yrxGXyHpJs8ySx3Yo5S8ncDCdZJCLmtPiq/hahg\n'
245 + + '5/0ffexMFUCQaYicFZsrJ/cStdxUV+tSw2JQLD7UxS9J97LQWUPyyG+ZrjYVTVq+\n'
246 + + 'zudnFmNSe4QoecXMhAFTGJFQXxP7nhSL9Ao5FGgdXy7/JWeWdQIAj8ku6cBDKPa6\n'
247 + + 'Y6kP+ak+In+Lye8z9qsCD/afUozfWjPR2aA4JoIZVF8dNRShIMo8l0XfgfM2q0+n\n'
248 + + 'ApZWZ+BjhIO5XuoUgHS3D2YFAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNV\n'
249 + + 'HRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBRm4GsWIA/M6q+tK8WGHWDGh2gcyTAf\n'
250 + + 'BgNVHSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOC\n'
251 + + 'AQEAHpMmeVQNqcxgfQdbDIi5UIy+E7zZykmtAygN1XQrvga9nXTis4kOTN6g5/+g\n'
252 + + 'HCx7jIXeNJzAbvg8XFqBN84Quqgpl/tQkbpco9Jh1HDs558D5NnZQxNqH5qXQ3Mm\n'
253 + + 'uPgCw0pYcPOa7bhs07i+MdVwPBsX27CFDtsgAIru8HvKxY1oTZrWnyIRo93tt/pk\n'
254 + + 'WuItVMVHjaQZVfTCow0aDUbte6Vlw82KjUFq+n2NMSCJDiDKsDDHT6BJc4AJHIq3\n'
255 + + '/4Z52MSC9KMr0yAaaoWfW/yMEj9LliQauAgwVjArF4q78rxpfKTG9Rfd8U1BZANP\n'
256 + + '7FrFMN0ThjfA1IvmOYcgskY5bQ==\n'
257 + + '-----END CERTIFICATE-----\n',
258 +
259 + /**
260 + * Amazon RDS eu-west-1 certificate CA 2015 to 2020
261 + *
262 + * CN = Amazon RDS eu-west-1 CA
263 + * OU = Amazon RDS
264 + * O = Amazon Web Services, Inc.
265 + * L = Seattle
266 + * ST = Washington
267 + * C = US
268 + * P = 2015-02-05T22:03:35Z/2020-03-05T22:03:35Z
269 + * F = 1A:95:F0:43:82:D2:5D:A6:AD:F5:13:27:0B:40:8A:72:D9:92:F3:E0
270 + */
271 + '-----BEGIN CERTIFICATE-----\n'
272 + + 'MIID/DCCAuSgAwIBAgIBSDANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
273 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
274 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
275 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzMzVaFw0y\n'
276 + + 'MDAzMDUyMjAzMzVaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
277 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
278 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n'
279 + + 'UyBldS13ZXN0LTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCx\n'
280 + + 'PdbqQ0HKRj79Pmocxvjc+P6i4Ux24kgFIl+ckiir1vzkmesc3a58gjrMlCksEObt\n'
281 + + 'Yihs5IhzEq1ePT0gbfS9GYFp34Uj/MtPwlrfCBWG4d2TcrsKRHr1/EXUYhWqmdrb\n'
282 + + 'RhX8XqoRhVkbF/auzFSBhTzcGGvZpQ2KIaxRcQfcXlMVhj/pxxAjh8U4F350Fb0h\n'
283 + + 'nX1jw4/KvEreBL0Xb2lnlGTkwVxaKGSgXEnOgIyOFdOQc61vdome0+eeZsP4jqeR\n'
284 + + 'TGYJA9izJsRbe2YJxHuazD+548hsPlM3vFzKKEVURCha466rAaYAHy3rKur3HYQx\n'
285 + + 'Yt+SoKcEz9PXuSGj96ejAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n'
286 + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBTebg//h2oeXbZjQ4uuoiuLYzuiPDAfBgNV\n'
287 + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n'
288 + + 'TikPaGeZasTPw+4RBemlsyPAjtFFQLo7ddaFdORLgdEysVf8aBqndvbA6MT/v4lj\n'
289 + + 'GtEtUdF59ZcbWOrVm+fBZ2h/jYJ59dYF/xzb09nyRbdMSzB9+mkSsnOMqluq5y8o\n'
290 + + 'DY/PfP2vGhEg/2ZncRC7nlQU1Dm8F4lFWEiQ2fi7O1cW852Vmbq61RIfcYsH/9Ma\n'
291 + + 'kpgk10VZ75b8m3UhmpZ/2uRY+JEHImH5WpcTJ7wNiPNJsciZMznGtrgOnPzYco8L\n'
292 + + 'cDleOASIZifNMQi9PKOJKvi0ITz0B/imr8KBsW0YjZVJ54HMa7W1lwugSM7aMAs+\n'
293 + + 'E3Sd5lS+SHwWaOCHwhOEVA==\n'
294 + + '-----END CERTIFICATE-----\n',
295 +
296 + /**
297 + * Amazon RDS sa-east-1 certificate CA 2015 to 2020
298 + *
299 + * CN = Amazon RDS sa-east-1 CA
300 + * OU = Amazon RDS
301 + * O = Amazon Web Services, Inc.
302 + * L = Seattle
303 + * ST = Washington
304 + * C = US
305 + * P = 2015-02-05T22:03:40Z/2020-03-05T22:03:40Z
306 + * F = 32:10:3D:FA:6D:42:F5:35:98:40:15:F4:4C:74:74:27:CB:CE:D4:B5
307 + */
308 + '-----BEGIN CERTIFICATE-----\n'
309 + + 'MIID/DCCAuSgAwIBAgIBSTANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
310 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
311 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
312 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzNDBaFw0y\n'
313 + + 'MDAzMDUyMjAzNDBaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
314 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
315 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n'
316 + + 'UyBzYS1lYXN0LTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCU\n'
317 + + 'X4OBnQ5xA6TLJAiFEI6l7bUWjoVJBa/VbMdCCSs2i2dOKmqUaXu2ix2zcPILj3lZ\n'
318 + + 'GMk3d/2zvTK/cKhcFrewHUBamTeVHdEmynhMQamqNmkM4ptYzFcvEUw1TGxHT4pV\n'
319 + + 'Q6gSN7+/AJewQvyHexHo8D0+LDN0/Wa9mRm4ixCYH2CyYYJNKaZt9+EZfNu+PPS4\n'
320 + + '8iB0TWH0DgQkbWMBfCRgolLLitAZklZ4dvdlEBS7evN1/7ttBxUK6SvkeeSx3zBl\n'
321 + + 'ww3BlXqc3bvTQL0A+RRysaVyFbvtp9domFaDKZCpMmDFAN/ntx215xmQdrSt+K3F\n'
322 + + 'cXdGQYHx5q410CAclGnbAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n'
323 + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBT6iVWnm/uakS+tEX2mzIfw+8JL0zAfBgNV\n'
324 + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n'
325 + + 'FmDD+QuDklXn2EgShwQxV13+txPRuVdOSrutHhoCgMwFWCMtPPtBAKs6KPY7Guvw\n'
326 + + 'DpJoZSehDiOfsgMirjOWjvfkeWSNvKfjWTVneX7pZD9W5WPnsDBvTbCGezm+v87z\n'
327 + + 'b+ZM2ZMo98m/wkMcIEAgdSKilR2fuw8rLkAjhYFfs0A7tDgZ9noKwgHvoE4dsrI0\n'
328 + + 'KZYco6DlP/brASfHTPa2puBLN9McK3v+h0JaSqqm5Ro2Bh56tZkQh8AWy/miuDuK\n'
329 + + '3+hNEVdxosxlkM1TPa1DGj0EzzK0yoeerXuH2HX7LlCrrxf6/wdKnjR12PMrLQ4A\n'
330 + + 'pCqkcWw894z6bV9MAvKe6A==\n'
331 + + '-----END CERTIFICATE-----\n',
332 +
333 + /**
334 + * Amazon RDS us-east-1 certificate CA 2015 to 2020
335 + *
336 + * CN = Amazon RDS us-east-1 CA
337 + * OU = Amazon RDS
338 + * O = Amazon Web Services, Inc.
339 + * L = Seattle
340 + * ST = Washington
341 + * C = US
342 + * P = 2015-02-05T21:54:04Z/2020-03-05T21:54:04Z
343 + * F = 34:47:8A:90:8A:83:AE:45:DC:B6:16:76:D2:35:EC:E9:75:C6:2C:63
344 + */
345 + '-----BEGIN CERTIFICATE-----\n'
346 + + 'MIID/DCCAuSgAwIBAgIBQzANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
347 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
348 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
349 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMTU0MDRaFw0y\n'
350 + + 'MDAzMDUyMTU0MDRaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
351 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
352 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n'
353 + + 'UyB1cy1lYXN0LTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDI\n'
354 + + 'UIuwh8NusKHk1SqPXcP7OqxY3S/M2ZyQWD3w7Bfihpyyy/fc1w0/suIpX3kbMhAV\n'
355 + + '2ESwged2/2zSx4pVnjp/493r4luhSqQYzru78TuPt9bhJIJ51WXunZW2SWkisSaf\n'
356 + + 'USYUzVN9ezR/bjXTumSUQaLIouJt3OHLX49s+3NAbUyOI8EdvgBQWD68H1epsC0n\n'
357 + + 'CI5s+pIktyOZ59c4DCDLQcXErQ+tNbDC++oct1ANd/q8p9URonYwGCGOBy7sbCYq\n'
358 + + '9eVHh1Iy2M+SNXddVOGw5EuruvHoCIQyOz5Lz4zSuZA9dRbrfztNOpezCNYu6NKM\n'
359 + + 'n+hzcvdiyxv77uNm8EaxAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n'
360 + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBQSQG3TmMe6Sa3KufaPBa72v4QFDzAfBgNV\n'
361 + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n'
362 + + 'L/mOZfB3187xTmjOHMqN2G2oSKHBKiQLM9uv8+97qT+XR+TVsBT6b3yoPpMAGhHA\n'
363 + + 'Pc7nxAF5gPpuzatx0OTLPcmYucFmfqT/1qA5WlgCnMNtczyNMH97lKFTNV7Njtek\n'
364 + + 'jWEzAEQSyEWrkNpNlC4j6kMYyPzVXQeXUeZTgJ9FNnVZqmvfjip2N22tawMjrCn5\n'
365 + + '7KN/zN65EwY2oO9XsaTwwWmBu3NrDdMbzJnbxoWcFWj4RBwanR1XjQOVNhDwmCOl\n'
366 + + '/1Et13b8CPyj69PC8BOVU6cfTSx8WUVy0qvYOKHNY9Bqa5BDnIL3IVmUkeTlM1mt\n'
367 + + 'enRpyBj+Bk9rh/ICdiRKmA==\n'
368 + + '-----END CERTIFICATE-----\n',
369 +
370 + /**
371 + * Amazon RDS us-west-1 certificate CA 2015 to 2020
372 + *
373 + * CN = Amazon RDS us-west-1 CA
374 + * OU = Amazon RDS
375 + * O = Amazon Web Services, Inc.
376 + * L = Seattle
377 + * ST = Washington
378 + * C = US
379 + * P = 2015-02-05T22:03:45Z/2020-03-05T22:03:45Z
380 + * F = EF:94:2F:E3:58:0E:09:D6:79:C2:16:97:91:FB:37:EA:D7:70:A8:4B
381 + */
382 + '-----BEGIN CERTIFICATE-----\n'
383 + + 'MIID/DCCAuSgAwIBAgIBSjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
384 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
385 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
386 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzNDVaFw0y\n'
387 + + 'MDAzMDUyMjAzNDVaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
388 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
389 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n'
390 + + 'UyB1cy13ZXN0LTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDE\n'
391 + + 'Dhw+uw/ycaiIhhyu2pXFRimq0DlB8cNtIe8hdqndH8TV/TFrljNgR8QdzOgZtZ9C\n'
392 + + 'zzQ2GRpInN/qJF6slEd6wO+6TaDBQkPY+07TXNt52POFUhdVkhJXHpE2BS7Xn6J7\n'
393 + + '7RFAOeG1IZmc2DDt+sR1BgXzUqHslQGfFYNS0/MBO4P+ya6W7IhruB1qfa4HiYQS\n'
394 + + 'dbe4MvGWnv0UzwAqdR7OF8+8/5c58YXZIXCO9riYF2ql6KNSL5cyDPcYK5VK0+Q9\n'
395 + + 'VI6vuJHSMYcF7wLePw8jtBktqAFE/wbdZiIHhZvNyiNWPPNTGUmQbaJ+TzQEHDs5\n'
396 + + '8en+/W7JKnPyBOkxxENbAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n'
397 + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBS0nw/tFR9bCjgqWTPJkyy4oOD8bzAfBgNV\n'
398 + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n'
399 + + 'CXGAY3feAak6lHdqj6+YWjy6yyUnLK37bRxZDsyDVXrPRQaXRzPTzx79jvDwEb/H\n'
400 + + 'Q/bdQ7zQRWqJcbivQlwhuPJ4kWPUZgSt3JUUuqkMsDzsvj/bwIjlrEFDOdHGh0mi\n'
401 + + 'eVIngFEjUXjMh+5aHPEF9BlQnB8LfVtKj18e15UDTXFa+xJPFxUR7wDzCfo4WI1m\n'
402 + + 'sUMG4q1FkGAZgsoyFPZfF8IVvgCuGdR8z30VWKklFxttlK0eGLlPAyIO0CQxPQlo\n'
403 + + 'saNJrHf4tLOgZIWk+LpDhNd9Et5EzvJ3aURUsKY4pISPPF5WdvM9OE59bERwUErd\n'
404 + + 'nuOuQWQeeadMceZnauRzJQ==\n'
405 + + '-----END CERTIFICATE-----\n',
406 +
407 + /**
408 + * Amazon RDS us-west-2 certificate CA 2015 to 2020
409 + *
410 + * CN = Amazon RDS us-west-2 CA
411 + * OU = Amazon RDS
412 + * O = Amazon Web Services, Inc.
413 + * L = Seattle
414 + * ST = Washington
415 + * C = US
416 + * P = 2015-02-05T22:03:50Z/2020-03-05T22:03:50Z
417 + * F = 94:2C:A8:B0:23:48:17:F0:CD:2F:19:7F:C1:E0:21:7C:65:79:13:3A
418 + */
419 + '-----BEGIN CERTIFICATE-----\n'
420 + + 'MIID/DCCAuSgAwIBAgIBSzANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
421 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
422 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
423 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNTAyMDUyMjAzNTBaFw0y\n'
424 + + 'MDAzMDUyMjAzNTBaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
425 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
426 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n'
427 + + 'UyB1cy13ZXN0LTIgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDM\n'
428 + + 'H58SR48U6jyERC1vYTnub34smf5EQVXyzaTmspWGWGzT31NLNZGSDFaa7yef9kdO\n'
429 + + 'mzJsgebR5tXq6LdwlIoWkKYQ7ycUaadtVKVYdI40QcI3cHn0qLFlg2iBXmWp/B+i\n'
430 + + 'Z34VuVlCh31Uj5WmhaBoz8t/GRqh1V/aCsf3Wc6jCezH3QfuCjBpzxdOOHN6Ie2v\n'
431 + + 'xX09O5qmZTvMoRBAvPkxdaPg/Mi7fxueWTbEVk78kuFbF1jHYw8U1BLILIAhcqlq\n'
432 + + 'x4u8nl73t3O3l/soNUcIwUDK0/S+Kfqhwn9yQyPlhb4Wy3pfnZLJdkyHldktnQav\n'
433 + + '9TB9u7KH5Lk0aAYslMLxAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n'
434 + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBT8roM4lRnlFHWMPWRz0zkwFZog1jAfBgNV\n'
435 + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQUFAAOCAQEA\n'
436 + + 'JwrxwgwmPtcdaU7O7WDdYa4hprpOMamI49NDzmE0s10oGrqmLwZygcWU0jT+fJ+Y\n'
437 + + 'pJe1w0CVfKaeLYNsOBVW3X4ZPmffYfWBheZiaiEflq/P6t7/Eg81gaKYnZ/x1Dfa\n'
438 + + 'sUYkzPvCkXe9wEz5zdUTOCptDt89rBR9CstL9vE7WYUgiVVmBJffWbHQLtfjv6OF\n'
439 + + 'NMb0QME981kGRzc2WhgP71YS2hHd1kXtsoYP1yTu4vThSKsoN4bkiHsaC1cRkLoy\n'
440 + + '0fFA4wpB3WloMEvCDaUvvH1LZlBXTNlwi9KtcwD4tDxkkBt4tQczKLGpQ/nF/W9n\n'
441 + + '8YDWk3IIc1sd0bkZqoau2Q==\n'
442 + + '-----END CERTIFICATE-----\n',
443 +
444 + /**
445 + * Amazon RDS ap-south-1 certificate CA 2016 to 2020
446 + *
447 + * CN = Amazon RDS ap-south-1 CA
448 + * OU = Amazon RDS
449 + * O = Amazon Web Services, Inc.
450 + * L = Seattle
451 + * ST = Washington
452 + * C = US
453 + * P = 2016-05-03T21:29:22Z/2020-03-05T21:29:22Z
454 + * F = F3:A3:C2:52:D9:82:20:AC:8C:62:31:2A:8C:AD:5D:7B:1C:31:F1:DD
455 + */
456 + '-----BEGIN CERTIFICATE-----\n'
457 + + 'MIID/TCCAuWgAwIBAgIBTTANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n'
458 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
459 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
460 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjA1MDMyMTI5MjJaFw0y\n'
461 + + 'MDAzMDUyMTI5MjJaMIGQMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
462 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
463 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEhMB8GA1UEAwwYQW1hem9uIFJE\n'
464 + + 'UyBhcC1zb3V0aC0xIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\n'
465 + + '06eWGLE0TeqL9kyWOLkS8q0fXO97z+xyBV3DKSB2lg2GkgBz3B98MkmkeB0SZy3G\n'
466 + + 'Ce4uCpCPbFKiFEdiUclOlhZsrBuCeaimxLM3Ig2wuenElO/7TqgaYHYUbT3d+VQW\n'
467 + + 'GUbLn5GRZJZe1OAClYdOWm7A1CKpuo+cVV1vxbY2nGUQSJPpVn2sT9gnwvjdE60U\n'
468 + + 'JGYU/RLCTm8zmZBvlWaNIeKDnreIc4rKn6gUnJ2cQn1ryCVleEeyc3xjYDSrjgdn\n'
469 + + 'FLYGcp9mphqVT0byeQMOk0c7RHpxrCSA0V5V6/CreFV2LteK50qcDQzDSM18vWP/\n'
470 + + 'p09FoN8O7QrtOeZJzH/lmwIDAQABo2YwZDAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0T\n'
471 + + 'AQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU2i83QHuEl/d0keXF+69HNJph7cMwHwYD\n'
472 + + 'VR0jBBgwFoAUTgLurD72FchM7Sz1BcGPnIQISYMwDQYJKoZIhvcNAQELBQADggEB\n'
473 + + 'ACqnH2VjApoDqoSQOky52QBwsGaj+xWYHW5Gm7EvCqvQuhWMkeBuD6YJmMvNyA9G\n'
474 + + 'I2lh6/o+sUk/RIsbYbxPRdhNPTOgDR9zsNRw6qxaHztq/CEC+mxDCLa3O1hHBaDV\n'
475 + + 'BmB3nCZb93BvO0EQSEk7aytKq/f+sjyxqOcs385gintdHGU9uM7gTZHnU9vByJsm\n'
476 + + '/TL07Miq67X0NlhIoo3jAk+xHaeKJdxdKATQp0448P5cY20q4b8aMk1twcNaMvCP\n'
477 + + 'dG4M5doaoUA8OQ/0ukLLae/LBxLeTw04q1/a2SyFaVUX2Twbb1S3xVWwLA8vsyGr\n'
478 + + 'igXx7B5GgP+IHb6DTjPJAi0=\n'
479 + + '-----END CERTIFICATE-----\n',
480 +
481 + /**
482 + * Amazon RDS us-east-2 certificate CA 2016 to 2020
483 + *
484 + * CN = Amazon RDS us-east-2 CA
485 + * OU = Amazon RDS
486 + * O = Amazon Web Services, Inc.
487 + * L = Seattle
488 + * ST = Washington
489 + * C = US
490 + * P = 2016-08-11T19:58:45Z/2020-03-05T19:58:45Z
491 + * F = 9B:78:E3:64:7F:74:BC:B2:52:18:CF:13:C3:62:B8:35:9D:3D:5F:B6
492 + */
493 + '-----BEGIN CERTIFICATE-----\n'
494 + + 'MIID/DCCAuSgAwIBAgIBTjANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n'
495 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
496 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
497 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjA4MTExOTU4NDVaFw0y\n'
498 + + 'MDAzMDUxOTU4NDVaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
499 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
500 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n'
501 + + 'UyB1cy1lYXN0LTIgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCp\n'
502 + + 'WnnUX7wM0zzstccX+4iXKJa9GR0a2PpvB1paEX4QRCgfhEdQWDaSqyrWNgdVCKkt\n'
503 + + '1aQkWu5j6VAC2XIG7kKoonm1ZdBVyBLqW5lXNywlaiU9yhJkwo8BR+/OqgE+PLt/\n'
504 + + 'EO1mlN0PQudja/XkExCXTO29TG2j7F/O7hox6vTyHNHc0H88zS21uPuBE+jivViS\n'
505 + + 'yzj/BkyoQ85hnkues3f9R6gCGdc+J51JbZnmgzUkvXjAEuKhAm9JksVOxcOKUYe5\n'
506 + + 'ERhn0U9zjzpfbAITIkul97VVa5IxskFFTHIPJbvRKHJkiF6wTJww/tc9wm+fSCJ1\n'
507 + + '+DbQTGZgkQ3bJrqRN29/AgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n'
508 + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBSAHQzUYYZbepwKEMvGdHp8wzHnfDAfBgNV\n'
509 + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQsFAAOCAQEA\n'
510 + + 'MbaEzSYZ+aZeTBxf8yi0ta8K4RdwEJsEmP6IhFFQHYUtva2Cynl4Q9tZg3RMsybT\n'
511 + + '9mlnSQQlbN/wqIIXbkrcgFcHoXG9Odm/bDtUwwwDaiEhXVfeQom3G77QHOWMTCGK\n'
512 + + 'qadwuh5msrb17JdXZoXr4PYHDKP7j0ONfAyFNER2+uecblHfRSpVq5UeF3L6ZJb8\n'
513 + + 'fSw/GtAV6an+/0r+Qm+PiI2H5XuZ4GmRJYnGMhqWhBYrY7p3jtVnKcsh39wgfUnW\n'
514 + + 'AvZEZG/yhFyAZW0Essa39LiL5VSq14Y1DOj0wgnhSY/9WHxaAo1HB1T9OeZknYbD\n'
515 + + 'fl/EGSZ0TEvZkENrXcPlVA==\n'
516 + + '-----END CERTIFICATE-----\n',
517 +
518 + /**
519 + * Amazon RDS ca-central-1 certificate CA 2016 to 2020
520 + *
521 + * CN = Amazon RDS ca-central-1 CA
522 + * OU = Amazon RDS
523 + * O = Amazon Web Services, Inc.
524 + * L = Seattle
525 + * ST = Washington
526 + * C = US
527 + * P = 2016-09-15T00:10:11Z/2020-03-05T00:10:11Z
528 + * F = D7:E0:16:AB:8A:0B:63:9F:67:1F:16:87:42:F4:0A:EE:73:A6:FC:04
529 + */
530 + '-----BEGIN CERTIFICATE-----\n'
531 + + 'MIID/zCCAuegAwIBAgIBTzANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n'
532 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
533 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
534 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjA5MTUwMDEwMTFaFw0y\n'
535 + + 'MDAzMDUwMDEwMTFaMIGSMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
536 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
537 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEjMCEGA1UEAwwaQW1hem9uIFJE\n'
538 + + 'UyBjYS1jZW50cmFsLTEgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n'
539 + + 'AQCZYI/iQ6DrS3ny3t1EwX1wAD+3LMgh7Fd01EW5LIuaK2kYIIQpsVKhxLCit/V5\n'
540 + + 'AGc/1qiJS1Qz9ODLTh0Na6bZW6EakRzuHJLe32KJtoFYPC7Z09UqzXrpA/XL+1hM\n'
541 + + 'P0ZmCWsU7Nn/EmvfBp9zX3dZp6P6ATrvDuYaVFr+SA7aT3FXpBroqBS1fyzUPs+W\n'
542 + + 'c6zTR6+yc4zkHX0XQxC5RH6xjgpeRkoOajA/sNo7AQF7KlWmKHbdVF44cvvAhRKZ\n'
543 + + 'XaoVs/C4GjkaAEPTCbopYdhzg+KLx9eB2BQnYLRrIOQZtRfbQI2Nbj7p3VsRuOW1\n'
544 + + 'tlcks2w1Gb0YC6w6SuIMFkl1AgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNV\n'
545 + + 'HRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBToYWxE1lawl6Ks6NsvpbHQ3GKEtzAf\n'
546 + + 'BgNVHSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQsFAAOC\n'
547 + + 'AQEAG/8tQ0ooi3hoQpa5EJz0/E5VYBsAz3YxA2HoIonn0jJyG16bzB4yZt4vNQMA\n'
548 + + 'KsNlQ1uwDWYL1nz63axieUUFIxqxl1KmwfhsmLgZ0Hd2mnTPIl2Hw3uj5+wdgGBg\n'
549 + + 'agnAZ0bajsBYgD2VGQbqjdk2Qn7Fjy3LEWIvGZx4KyZ99OJ2QxB7JOPdauURAtWA\n'
550 + + 'DKYkP4LLJxtj07DSzG8kuRWb9B47uqUD+eKDIyjfjbnzGtd9HqqzYFau7EX3HVD9\n'
551 + + '9Qhnjl7bTZ6YfAEZ3nH2t3Vc0z76XfGh47rd0pNRhMV+xpok75asKf/lNh5mcUrr\n'
552 + + 'VKwflyMkQpSbDCmcdJ90N2xEXQ==\n'
553 + + '-----END CERTIFICATE-----\n',
554 +
555 + /**
556 + * Amazon RDS eu-west-2 certificate CA 2016 to 2020
557 + *
558 + * CN = Amazon RDS eu-west-2 CA
559 + * OU = Amazon RDS
560 + * O = Amazon Web Services, Inc.
561 + * L = Seattle
562 + * ST = Washington
563 + * C = US
564 + * P = 2016-10-10T17:44:42Z/2020-03-05T17:44:42Z
565 + * F = 47:79:51:9F:FF:07:D3:F4:27:D3:AB:64:56:7F:00:45:BB:84:C1:71
566 + */
567 + '-----BEGIN CERTIFICATE-----\n'
568 + + 'MIID/DCCAuSgAwIBAgIBUDANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n'
569 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
570 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
571 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNjEwMTAxNzQ0NDJaFw0y\n'
572 + + 'MDAzMDUxNzQ0NDJaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
573 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
574 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n'
575 + + 'UyBldS13ZXN0LTIgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDO\n'
576 + + 'cttLJfubB4XMMIGWNfJISkIdCMGJyOzLiMJaiWB5GYoXKhEl7YGotpy0qklwW3BQ\n'
577 + + 'a0fmVdcCLX+dIuVQ9iFK+ZcK7zwm7HtdDTCHOCKeOh2IcnU4c/VIokFi6Gn8udM6\n'
578 + + 'N/Zi5M5OGpVwLVALQU7Yctsn3c95el6MdVx6mJiIPVu7tCVZn88Z2koBQ2gq9P4O\n'
579 + + 'Sb249SHFqOb03lYDsaqy1NDsznEOhaRBw7DPJFpvmw1lA3/Y6qrExRI06H2VYR2i\n'
580 + + '7qxwDV50N58fs10n7Ye1IOxTVJsgEA7X6EkRRXqYaM39Z76R894548WHfwXWjUsi\n'
581 + + 'MEX0RS0/t1GmnUQjvevDAgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n'
582 + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBQBxmcuRSxERYCtNnSr5xNfySokHjAfBgNV\n'
583 + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQsFAAOCAQEA\n'
584 + + 'UyCUQjsF3nUAABjfEZmpksTuUo07aT3KGYt+EMMFdejnBQ0+2lJJFGtT+CDAk1SD\n'
585 + + 'RSgfEBon5vvKEtlnTf9a3pv8WXOAkhfxnryr9FH6NiB8obISHNQNPHn0ljT2/T+I\n'
586 + + 'Y6ytfRvKHa0cu3V0NXbJm2B4KEOt4QCDiFxUIX9z6eB4Kditwu05OgQh6KcogOiP\n'
587 + + 'JesWxBMXXGoDC1rIYTFO7szwDyOHlCcVXJDNsTJhc32oDWYdeIbW7o/5I+aQsrXZ\n'
588 + + 'C96HykZcgWzz6sElrQxUaT3IoMw/5nmw4uWKKnZnxgI9bY4fpQwMeBZ96iHfFxvH\n'
589 + + 'mqfEEuC7uUoPofXdBp2ObQ==\n'
590 + + '-----END CERTIFICATE-----\n',
591 +
592 + /**
593 + * Amazon RDS us-gov-west-1 CA 2017 to 2022
594 + *
595 + * CN = Amazon RDS us-gov-west-1 CA
596 + * OU = Amazon RDS
597 + * O = Amazon Web Services, Inc.
598 + * L = Seattle
599 + * ST = Washington
600 + * C = US
601 + * P = 2017-05-19T22:31:19Z/2022-05-18T12:00:00Z
602 + * F = 77:55:8C:C4:5E:71:1F:1B:57:E3:DA:6E:5B:74:27:12:4E:E8:69:E8
603 + */
604 + '-----BEGIN CERTIFICATE-----\n'
605 + + 'MIIECjCCAvKgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwgZMxCzAJBgNVBAYTAlVT\n'
606 + + 'MRAwDgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQK\n'
607 + + 'DBlBbWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRT\n'
608 + + 'MSQwIgYDVQQDDBtBbWF6b24gUkRTIEdvdkNsb3VkIFJvb3QgQ0EwHhcNMTcwNTE5\n'
609 + + 'MjIzMTE5WhcNMjIwNTE4MTIwMDAwWjCBkzELMAkGA1UEBhMCVVMxEzARBgNVBAgM\n'
610 + + 'Cldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoMGUFtYXpvbiBX\n'
611 + + 'ZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMxJDAiBgNVBAMM\n'
612 + + 'G0FtYXpvbiBSRFMgdXMtZ292LXdlc3QtMSBDQTCCASIwDQYJKoZIhvcNAQEBBQAD\n'
613 + + 'ggEPADCCAQoCggEBAM8YZLKAzzOdNnoi7Klih26Zkj+OCpDfwx4ZYB6f8L8UoQi5\n'
614 + + '8z9ZtIwMjiJ/kO08P1yl4gfc7YZcNFvhGruQZNat3YNpxwUpQcr4mszjuffbL4uz\n'
615 + + '+/8FBxALdqCVOJ5Q0EVSfz3d9Bd1pUPL7ARtSpy7bn/tUPyQeI+lODYO906C0TQ3\n'
616 + + 'b9bjOsgAdBKkHfjLdsknsOZYYIzYWOJyFJJa0B11XjDUNBy/3IuC0KvDl6At0V5b\n'
617 + + '8M6cWcKhte2hgjwTYepV+/GTadeube1z5z6mWsN5arOAQUtYDLH6Aztq9mCJzLHm\n'
618 + + 'RccBugnGl3fRLJ2VjioN8PoGoN9l9hFBy5fnFgsCAwEAAaNmMGQwDgYDVR0PAQH/\n'
619 + + 'BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFEG7+br8KkvwPd5g\n'
620 + + '71Rvh2stclJbMB8GA1UdIwQYMBaAFEkQz6S4NS5lOYKcDjBSuCcVpdzjMA0GCSqG\n'
621 + + 'SIb3DQEBCwUAA4IBAQBMA327u5ABmhX+aPxljoIbxnydmAFWxW6wNp5+rZrvPig8\n'
622 + + 'zDRqGQWWr7wWOIjfcWugSElYtf/m9KZHG/Z6+NG7nAoUrdcd1h/IQhb+lFQ2b5g9\n'
623 + + 'sVzQv/H2JNkfZA8fL/Ko/Tm/f9tcqe0zrGCtT+5u0Nvz35Wl8CEUKLloS5xEb3k5\n'
624 + + '7D9IhG3fsE3vHWlWrGCk1cKry3j12wdPG5cUsug0vt34u6rdhP+FsM0tHI15Kjch\n'
625 + + 'RuUCvyQecy2ZFNAa3jmd5ycNdL63RWe8oayRBpQBxPPCbHfILxGZEdJbCH9aJ2D/\n'
626 + + 'l8oHIDnvOLdv7/cBjyYuvmprgPtu3QEkbre5Hln/\n'
627 + + '-----END CERTIFICATE-----\n',
628 +
629 + /**
630 + * Amazon RDS eu-west-3 certificate CA 2017 to 2020
631 + *
632 + * CN = Amazon RDS eu-west-3 CA
633 + * OU = Amazon RDS
634 + * O = Amazon Web Services, Inc.
635 + * L = Seattle
636 + * ST = Washington
637 + * C = US
638 + * P = 2017-08-25T21:39:26Z/2020-03-05T21:39:26Z
639 + * F = FD:35:A7:84:60:68:98:00:12:54:ED:34:26:8C:66:0F:72:DD:B2:F4
640 + */
641 + '-----BEGIN CERTIFICATE-----\n'
642 + + 'MIID/DCCAuSgAwIBAgIBUTANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCVVMx\n'
643 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
644 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
645 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNzA4MjUyMTM5MjZaFw0y\n'
646 + + 'MDAzMDUyMTM5MjZaMIGPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
647 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
648 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJE\n'
649 + + 'UyBldS13ZXN0LTMgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC+\n'
650 + + 'xmlEC/3a4cJH+UPwXCE02lC7Zq5NHd0dn6peMeLN8agb6jW4VfSY0NydjRj2DJZ8\n'
651 + + 'K7wV6sub5NUGT1NuFmvSmdbNR2T59KX0p2dVvxmXHHtIpQ9Y8Aq3ZfhmC5q5Bqgw\n'
652 + + 'tMA1xayDi7HmoPX3R8kk9ktAZQf6lDeksCvok8idjTu9tiSpDiMwds5BjMsWfyjZ\n'
653 + + 'd13PTGGNHYVdP692BSyXzSP1Vj84nJKnciW8tAqwIiadreJt5oXyrCXi8ekUMs80\n'
654 + + 'cUTuGm3aA3Q7PB5ljJMPqz0eVddaiIvmTJ9O3Ez3Du/HpImyMzXjkFaf+oNXf/Hx\n'
655 + + '/EW5jCRR6vEiXJcDRDS7AgMBAAGjZjBkMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB\n'
656 + + 'Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBRZ9mRtS5fHk3ZKhG20Oack4cAqMTAfBgNV\n'
657 + + 'HSMEGDAWgBROAu6sPvYVyEztLPUFwY+chAhJgzANBgkqhkiG9w0BAQsFAAOCAQEA\n'
658 + + 'F/u/9L6ExQwD73F/bhCw7PWcwwqsK1mypIdrjdIsu0JSgwWwGCXmrIspA3n3Dqxq\n'
659 + + 'sMhAJD88s9Em7337t+naar2VyLO63MGwjj+vA4mtvQRKq8ScIpiEc7xN6g8HUMsd\n'
660 + + 'gPG9lBGfNjuAZsrGJflrko4HyuSM7zHExMjXLH+CXcv/m3lWOZwnIvlVMa4x0Tz0\n'
661 + + 'A4fklaawryngzeEjuW6zOiYCzjZtPlP8Fw0SpzppJ8VpQfrZ751RDo4yudmPqoPK\n'
662 + + '5EUe36L8U+oYBXnC5TlYs9bpVv9o5wJQI5qA9oQE2eFWxF1E0AyZ4V5sgGUBStaX\n'
663 + + 'BjDDWul0wSo7rt1Tq7XpnA==\n'
664 + + '-----END CERTIFICATE-----\n',
665 +
666 + /**
667 + * Amazon RDS ap-northeast-3 certificate CA 2017 to 2020
668 + *
669 + * CN = Amazon RDS ap-northeast-3 CA
670 + * OU = Amazon RDS
671 + * O = Amazon Web Services, Inc.
672 + * L = Seattle
673 + * ST = Washington
674 + * C = US
675 + * P = 2017-12-01T00:55:42Z/2020-03-05T00:55:42Z
676 + * F = C0:C7:D4:B3:91:40:A0:77:43:28:BF:AF:77:57:DF:FD:98:FB:10:3F
677 + */
678 + '-----BEGIN CERTIFICATE-----\n'
679 + + 'MIIEATCCAumgAwIBAgIBTjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCVVMx\n'
680 + + 'EzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxIjAgBgNVBAoM\n'
681 + + 'GUFtYXpvbiBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMx\n'
682 + + 'GzAZBgNVBAMMEkFtYXpvbiBSRFMgUm9vdCBDQTAeFw0xNzEyMDEwMDU1NDJaFw0y\n'
683 + + 'MDAzMDUwMDU1NDJaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3Rv\n'
684 + + 'bjEQMA4GA1UEBwwHU2VhdHRsZTEiMCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNl\n'
685 + + 'cywgSW5jLjETMBEGA1UECwwKQW1hem9uIFJEUzElMCMGA1UEAwwcQW1hem9uIFJE\n'
686 + + 'UyBhcC1ub3J0aGVhc3QtMyBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n'
687 + + 'ggEBAMZtQNnm/XT19mTa10ftHLzg5UhajoI65JHv4TQNdGXdsv+CQdGYU49BJ9Eu\n'
688 + + '3bYgiEtTzR2lQe9zGMvtuJobLhOWuavzp7IixoIQcHkFHN6wJ1CvqrxgvJfBq6Hy\n'
689 + + 'EuCDCiU+PPDLUNA6XM6Qx3IpHd1wrJkjRB80dhmMSpxmRmx849uFafhN+P1QybsM\n'
690 + + 'TI0o48VON2+vj+mNuQTyLMMP8D4odSQHjaoG+zyJfJGZeAyqQyoOUOFEyQaHC3TT\n'
691 + + '3IDSNCQlpxb9LerbCoKu79WFBBq3CS5cYpg8/fsnV2CniRBFFUumBt5z4dhw9RJU\n'
692 + + 'qlUXXO1ZyzpGd+c5v6FtrfXtnIUCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIG\n'
693 + + 'A1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFETv7ELNplYy/xTeIOInl6nzeiHg\n'
694 + + 'MB8GA1UdIwQYMBaAFE4C7qw+9hXITO0s9QXBj5yECEmDMA0GCSqGSIb3DQEBBQUA\n'
695 + + 'A4IBAQCpKxOQcd0tEKb3OtsOY8q/MPwTyustGk2Rt7t9G68idADp8IytB7M0SDRo\n'
696 + + 'wWZqynEq7orQVKdVOanhEWksNDzGp0+FPAf/KpVvdYCd7ru3+iI+V4ZEp2JFdjuZ\n'
697 + + 'Zz0PIjS6AgsZqE5Ri1J+NmfmjGZCPhsHnGZiBaenX6K5VRwwwmLN6xtoqrrfR5zL\n'
698 + + 'QfBeeZNJG6KiM3R/DxJ5rAa6Fz+acrhJ60L7HprhB7SFtj1RCijau3+ZwiGmUOMr\n'
699 + + 'yKlMv+VgmzSw7o4Hbxy1WVrA6zQsTHHSGf+vkQn2PHvnFMUEu/ZLbTDYFNmTLK91\n'
700 + + 'K6o4nMsEvhBKgo4z7H1EqqxXhvN2\n'
701 + + '-----END CERTIFICATE-----\n',
702 +
703 + /**
704 + * Amazon RDS GovCloud Root CA 2017 to 2022
705 + *
706 + * CN = Amazon RDS GovCloud Root CA
707 + * OU = Amazon RDS
708 + * O = Amazon Web Services, Inc.
709 + * L = Seattle
710 + * ST = Washington
711 + * C = US
712 + * P = 2017-05-19T22:29:11Z/2022-05-18T22:29:11Z
713 + * F = A3:61:F9:C9:A2:5B:91:FE:73:A6:52:E3:59:14:8E:CE:35:12:0F:FD
714 + */
715 + '-----BEGIN CERTIFICATE-----\n'
716 + + 'MIIEDjCCAvagAwIBAgIJAMM61RQn3/kdMA0GCSqGSIb3DQEBCwUAMIGTMQswCQYD\n'
717 + + 'VQQGEwJVUzEQMA4GA1UEBwwHU2VhdHRsZTETMBEGA1UECAwKV2FzaGluZ3RvbjEi\n'
718 + + 'MCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1h\n'
719 + + 'em9uIFJEUzEkMCIGA1UEAwwbQW1hem9uIFJEUyBHb3ZDbG91ZCBSb290IENBMB4X\n'
720 + + 'DTE3MDUxOTIyMjkxMVoXDTIyMDUxODIyMjkxMVowgZMxCzAJBgNVBAYTAlVTMRAw\n'
721 + + 'DgYDVQQHDAdTZWF0dGxlMRMwEQYDVQQIDApXYXNoaW5ndG9uMSIwIAYDVQQKDBlB\n'
722 + + 'bWF6b24gV2ViIFNlcnZpY2VzLCBJbmMuMRMwEQYDVQQLDApBbWF6b24gUkRTMSQw\n'
723 + + 'IgYDVQQDDBtBbWF6b24gUkRTIEdvdkNsb3VkIFJvb3QgQ0EwggEiMA0GCSqGSIb3\n'
724 + + 'DQEBAQUAA4IBDwAwggEKAoIBAQDGS9bh1FGiJPT+GRb3C5aKypJVDC1H2gbh6n3u\n'
725 + + 'j8cUiyMXfmm+ak402zdLpSYMaxiQ7oL/B3wEmumIpRDAsQrSp3B/qEeY7ipQGOfh\n'
726 + + 'q2TXjXGIUjiJ/FaoGqkymHRLG+XkNNBtb7MRItsjlMVNELXECwSiMa3nJL2/YyHW\n'
727 + + 'nTr1+11/weeZEKgVbCUrOugFkMXnfZIBSn40j6EnRlO2u/NFU5ksK5ak2+j8raZ7\n'
728 + + 'xW7VXp9S1Tgf1IsWHjGZZZguwCkkh1tHOlHC9gVA3p63WecjrIzcrR/V27atul4m\n'
729 + + 'tn56s5NwFvYPUIx1dbC8IajLUrepVm6XOwdQCfd02DmOyjWJAgMBAAGjYzBhMA4G\n'
730 + + 'A1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRJEM+kuDUu\n'
731 + + 'ZTmCnA4wUrgnFaXc4zAfBgNVHSMEGDAWgBRJEM+kuDUuZTmCnA4wUrgnFaXc4zAN\n'
732 + + 'BgkqhkiG9w0BAQsFAAOCAQEAcfA7uirXsNZyI2j4AJFVtOTKOZlQwqbyNducnmlg\n'
733 + + '/5nug9fAkwM4AgvF5bBOD1Hw6khdsccMwIj+1S7wpL+EYb/nSc8G0qe1p/9lZ/mZ\n'
734 + + 'ff5g4JOa26lLuCrZDqAk4TzYnt6sQKfa5ZXVUUn0BK3okhiXS0i+NloMyaBCL7vk\n'
735 + + 'kDwkHwEqflRKfZ9/oFTcCfoiHPA7AdBtaPVr0/Kj9L7k+ouz122huqG5KqX0Zpo8\n'
736 + + 'S0IGvcd2FZjNSNPttNAK7YuBVsZ0m2nIH1SLp//00v7yAHIgytQwwB17PBcp4NXD\n'
737 + + 'pCfTa27ng9mMMC2YLqWQpW4TkqjDin2ZC+5X/mbrjzTvVg==\n'
738 + + '-----END CERTIFICATE-----\n'
739 + ]
740 +};
1 +// Manually extracted from mysql-5.7.9/include/mysql.h.pp
2 +// some more info here: http://dev.mysql.com/doc/refman/5.5/en/c-api-prepared-statement-type-codes.html
3 +exports.DECIMAL = 0x00; // aka DECIMAL (http://dev.mysql.com/doc/refman/5.0/en/precision-math-decimal-changes.html)
4 +exports.TINY = 0x01; // aka TINYINT, 1 byte
5 +exports.SHORT = 0x02; // aka SMALLINT, 2 bytes
6 +exports.LONG = 0x03; // aka INT, 4 bytes
7 +exports.FLOAT = 0x04; // aka FLOAT, 4-8 bytes
8 +exports.DOUBLE = 0x05; // aka DOUBLE, 8 bytes
9 +exports.NULL = 0x06; // NULL (used for prepared statements, I think)
10 +exports.TIMESTAMP = 0x07; // aka TIMESTAMP
11 +exports.LONGLONG = 0x08; // aka BIGINT, 8 bytes
12 +exports.INT24 = 0x09; // aka MEDIUMINT, 3 bytes
13 +exports.DATE = 0x0a; // aka DATE
14 +exports.TIME = 0x0b; // aka TIME
15 +exports.DATETIME = 0x0c; // aka DATETIME
16 +exports.YEAR = 0x0d; // aka YEAR, 1 byte (don't ask)
17 +exports.NEWDATE = 0x0e; // aka ?
18 +exports.VARCHAR = 0x0f; // aka VARCHAR (?)
19 +exports.BIT = 0x10; // aka BIT, 1-8 byte
20 +exports.TIMESTAMP2 = 0x11; // aka TIMESTAMP with fractional seconds
21 +exports.DATETIME2 = 0x12; // aka DATETIME with fractional seconds
22 +exports.TIME2 = 0x13; // aka TIME with fractional seconds
23 +exports.JSON = 0xf5; // aka JSON
24 +exports.NEWDECIMAL = 0xf6; // aka DECIMAL
25 +exports.ENUM = 0xf7; // aka ENUM
26 +exports.SET = 0xf8; // aka SET
27 +exports.TINY_BLOB = 0xf9; // aka TINYBLOB, TINYTEXT
28 +exports.MEDIUM_BLOB = 0xfa; // aka MEDIUMBLOB, MEDIUMTEXT
29 +exports.LONG_BLOB = 0xfb; // aka LONGBLOG, LONGTEXT
30 +exports.BLOB = 0xfc; // aka BLOB, TEXT
31 +exports.VAR_STRING = 0xfd; // aka VARCHAR, VARBINARY
32 +exports.STRING = 0xfe; // aka CHAR, BINARY
33 +exports.GEOMETRY = 0xff; // aka GEOMETRY
1 +module.exports = AuthSwitchRequestPacket;
2 +function AuthSwitchRequestPacket(options) {
3 + options = options || {};
4 +
5 + this.status = 0xfe;
6 + this.authMethodName = options.authMethodName;
7 + this.authMethodData = options.authMethodData;
8 +}
9 +
10 +AuthSwitchRequestPacket.prototype.parse = function parse(parser) {
11 + this.status = parser.parseUnsignedNumber(1);
12 + this.authMethodName = parser.parseNullTerminatedString();
13 + this.authMethodData = parser.parsePacketTerminatedBuffer();
14 +};
15 +
16 +AuthSwitchRequestPacket.prototype.write = function write(writer) {
17 + writer.writeUnsignedNumber(1, this.status);
18 + writer.writeNullTerminatedString(this.authMethodName);
19 + writer.writeBuffer(this.authMethodData);
20 +};
1 +module.exports = AuthSwitchResponsePacket;
2 +function AuthSwitchResponsePacket(options) {
3 + options = options || {};
4 +
5 + this.data = options.data;
6 +}
7 +
8 +AuthSwitchResponsePacket.prototype.parse = function parse(parser) {
9 + this.data = parser.parsePacketTerminatedBuffer();
10 +};
11 +
12 +AuthSwitchResponsePacket.prototype.write = function write(writer) {
13 + writer.writeBuffer(this.data);
14 +};
1 +var Buffer = require('safe-buffer').Buffer;
2 +
3 +module.exports = ClientAuthenticationPacket;
4 +function ClientAuthenticationPacket(options) {
5 + options = options || {};
6 +
7 + this.clientFlags = options.clientFlags;
8 + this.maxPacketSize = options.maxPacketSize;
9 + this.charsetNumber = options.charsetNumber;
10 + this.filler = undefined;
11 + this.user = options.user;
12 + this.scrambleBuff = options.scrambleBuff;
13 + this.database = options.database;
14 + this.protocol41 = options.protocol41;
15 +}
16 +
17 +ClientAuthenticationPacket.prototype.parse = function(parser) {
18 + if (this.protocol41) {
19 + this.clientFlags = parser.parseUnsignedNumber(4);
20 + this.maxPacketSize = parser.parseUnsignedNumber(4);
21 + this.charsetNumber = parser.parseUnsignedNumber(1);
22 + this.filler = parser.parseFiller(23);
23 + this.user = parser.parseNullTerminatedString();
24 + this.scrambleBuff = parser.parseLengthCodedBuffer();
25 + this.database = parser.parseNullTerminatedString();
26 + } else {
27 + this.clientFlags = parser.parseUnsignedNumber(2);
28 + this.maxPacketSize = parser.parseUnsignedNumber(3);
29 + this.user = parser.parseNullTerminatedString();
30 + this.scrambleBuff = parser.parseBuffer(8);
31 + this.database = parser.parseLengthCodedBuffer();
32 + }
33 +};
34 +
35 +ClientAuthenticationPacket.prototype.write = function(writer) {
36 + if (this.protocol41) {
37 + writer.writeUnsignedNumber(4, this.clientFlags);
38 + writer.writeUnsignedNumber(4, this.maxPacketSize);
39 + writer.writeUnsignedNumber(1, this.charsetNumber);
40 + writer.writeFiller(23);
41 + writer.writeNullTerminatedString(this.user);
42 + writer.writeLengthCodedBuffer(this.scrambleBuff);
43 + writer.writeNullTerminatedString(this.database);
44 + } else {
45 + writer.writeUnsignedNumber(2, this.clientFlags);
46 + writer.writeUnsignedNumber(3, this.maxPacketSize);
47 + writer.writeNullTerminatedString(this.user);
48 + writer.writeBuffer(this.scrambleBuff);
49 + if (this.database && this.database.length) {
50 + writer.writeFiller(1);
51 + writer.writeBuffer(Buffer.from(this.database));
52 + }
53 + }
54 +};
1 +module.exports = ComChangeUserPacket;
2 +function ComChangeUserPacket(options) {
3 + options = options || {};
4 +
5 + this.command = 0x11;
6 + this.user = options.user;
7 + this.scrambleBuff = options.scrambleBuff;
8 + this.database = options.database;
9 + this.charsetNumber = options.charsetNumber;
10 +}
11 +
12 +ComChangeUserPacket.prototype.parse = function(parser) {
13 + this.command = parser.parseUnsignedNumber(1);
14 + this.user = parser.parseNullTerminatedString();
15 + this.scrambleBuff = parser.parseLengthCodedBuffer();
16 + this.database = parser.parseNullTerminatedString();
17 + this.charsetNumber = parser.parseUnsignedNumber(1);
18 +};
19 +
20 +ComChangeUserPacket.prototype.write = function(writer) {
21 + writer.writeUnsignedNumber(1, this.command);
22 + writer.writeNullTerminatedString(this.user);
23 + writer.writeLengthCodedBuffer(this.scrambleBuff);
24 + writer.writeNullTerminatedString(this.database);
25 + writer.writeUnsignedNumber(2, this.charsetNumber);
26 +};
1 +module.exports = ComPingPacket;
2 +function ComPingPacket() {
3 + this.command = 0x0e;
4 +}
5 +
6 +ComPingPacket.prototype.write = function(writer) {
7 + writer.writeUnsignedNumber(1, this.command);
8 +};
9 +
10 +ComPingPacket.prototype.parse = function(parser) {
11 + this.command = parser.parseUnsignedNumber(1);
12 +};
1 +module.exports = ComQueryPacket;
2 +function ComQueryPacket(sql) {
3 + this.command = 0x03;
4 + this.sql = sql;
5 +}
6 +
7 +ComQueryPacket.prototype.write = function(writer) {
8 + writer.writeUnsignedNumber(1, this.command);
9 + writer.writeString(this.sql);
10 +};
11 +
12 +ComQueryPacket.prototype.parse = function(parser) {
13 + this.command = parser.parseUnsignedNumber(1);
14 + this.sql = parser.parsePacketTerminatedString();
15 +};
1 +module.exports = ComQuitPacket;
2 +function ComQuitPacket() {
3 + this.command = 0x01;
4 +}
5 +
6 +ComQuitPacket.prototype.parse = function parse(parser) {
7 + this.command = parser.parseUnsignedNumber(1);
8 +};
9 +
10 +ComQuitPacket.prototype.write = function write(writer) {
11 + writer.writeUnsignedNumber(1, this.command);
12 +};
1 +module.exports = ComStatisticsPacket;
2 +function ComStatisticsPacket() {
3 + this.command = 0x09;
4 +}
5 +
6 +ComStatisticsPacket.prototype.write = function(writer) {
7 + writer.writeUnsignedNumber(1, this.command);
8 +};
9 +
10 +ComStatisticsPacket.prototype.parse = function(parser) {
11 + this.command = parser.parseUnsignedNumber(1);
12 +};
1 +module.exports = EmptyPacket;
2 +function EmptyPacket() {
3 +}
4 +
5 +EmptyPacket.prototype.write = function write() {
6 +};
1 +module.exports = EofPacket;
2 +function EofPacket(options) {
3 + options = options || {};
4 +
5 + this.fieldCount = undefined;
6 + this.warningCount = options.warningCount;
7 + this.serverStatus = options.serverStatus;
8 + this.protocol41 = options.protocol41;
9 +}
10 +
11 +EofPacket.prototype.parse = function(parser) {
12 + this.fieldCount = parser.parseUnsignedNumber(1);
13 + if (this.protocol41) {
14 + this.warningCount = parser.parseUnsignedNumber(2);
15 + this.serverStatus = parser.parseUnsignedNumber(2);
16 + }
17 +};
18 +
19 +EofPacket.prototype.write = function(writer) {
20 + writer.writeUnsignedNumber(1, 0xfe);
21 + if (this.protocol41) {
22 + writer.writeUnsignedNumber(2, this.warningCount);
23 + writer.writeUnsignedNumber(2, this.serverStatus);
24 + }
25 +};
1 +module.exports = ErrorPacket;
2 +function ErrorPacket(options) {
3 + options = options || {};
4 +
5 + this.fieldCount = options.fieldCount;
6 + this.errno = options.errno;
7 + this.sqlStateMarker = options.sqlStateMarker;
8 + this.sqlState = options.sqlState;
9 + this.message = options.message;
10 +}
11 +
12 +ErrorPacket.prototype.parse = function(parser) {
13 + this.fieldCount = parser.parseUnsignedNumber(1);
14 + this.errno = parser.parseUnsignedNumber(2);
15 +
16 + // sqlStateMarker ('#' = 0x23) indicates error packet format
17 + if (parser.peak() === 0x23) {
18 + this.sqlStateMarker = parser.parseString(1);
19 + this.sqlState = parser.parseString(5);
20 + }
21 +
22 + this.message = parser.parsePacketTerminatedString();
23 +};
24 +
25 +ErrorPacket.prototype.write = function(writer) {
26 + writer.writeUnsignedNumber(1, 0xff);
27 + writer.writeUnsignedNumber(2, this.errno);
28 +
29 + if (this.sqlStateMarker) {
30 + writer.writeString(this.sqlStateMarker);
31 + writer.writeString(this.sqlState);
32 + }
33 +
34 + writer.writeString(this.message);
35 +};
1 +var Types = require('../constants/types');
2 +
3 +module.exports = Field;
4 +function Field(options) {
5 + options = options || {};
6 +
7 + this.parser = options.parser;
8 + this.packet = options.packet;
9 + this.db = options.packet.db;
10 + this.table = options.packet.table;
11 + this.name = options.packet.name;
12 + this.type = typeToString(options.packet.type);
13 + this.length = options.packet.length;
14 +}
15 +
16 +Field.prototype.string = function () {
17 + return this.parser.parseLengthCodedString();
18 +};
19 +
20 +Field.prototype.buffer = function () {
21 + return this.parser.parseLengthCodedBuffer();
22 +};
23 +
24 +Field.prototype.geometry = function () {
25 + return this.parser.parseGeometryValue();
26 +};
27 +
28 +function typeToString(t) {
29 + for (var k in Types) {
30 + if (Types[k] === t) return k;
31 + }
32 +
33 + return undefined;
34 +}
1 +module.exports = FieldPacket;
2 +function FieldPacket(options) {
3 + options = options || {};
4 +
5 + this.catalog = options.catalog;
6 + this.db = options.db;
7 + this.table = options.table;
8 + this.orgTable = options.orgTable;
9 + this.name = options.name;
10 + this.orgName = options.orgName;
11 + this.charsetNr = options.charsetNr;
12 + this.length = options.length;
13 + this.type = options.type;
14 + this.flags = options.flags;
15 + this.decimals = options.decimals;
16 + this.default = options.default;
17 + this.zeroFill = options.zeroFill;
18 + this.protocol41 = options.protocol41;
19 +}
20 +
21 +FieldPacket.prototype.parse = function(parser) {
22 + if (this.protocol41) {
23 + this.catalog = parser.parseLengthCodedString();
24 + this.db = parser.parseLengthCodedString();
25 + this.table = parser.parseLengthCodedString();
26 + this.orgTable = parser.parseLengthCodedString();
27 + this.name = parser.parseLengthCodedString();
28 + this.orgName = parser.parseLengthCodedString();
29 +
30 + if (parser.parseLengthCodedNumber() !== 0x0c) {
31 + var err = new TypeError('Received invalid field length');
32 + err.code = 'PARSER_INVALID_FIELD_LENGTH';
33 + throw err;
34 + }
35 +
36 + this.charsetNr = parser.parseUnsignedNumber(2);
37 + this.length = parser.parseUnsignedNumber(4);
38 + this.type = parser.parseUnsignedNumber(1);
39 + this.flags = parser.parseUnsignedNumber(2);
40 + this.decimals = parser.parseUnsignedNumber(1);
41 +
42 + var filler = parser.parseBuffer(2);
43 + if (filler[0] !== 0x0 || filler[1] !== 0x0) {
44 + var err = new TypeError('Received invalid filler');
45 + err.code = 'PARSER_INVALID_FILLER';
46 + throw err;
47 + }
48 +
49 + // parsed flags
50 + this.zeroFill = (this.flags & 0x0040 ? true : false);
51 +
52 + if (parser.reachedPacketEnd()) {
53 + return;
54 + }
55 +
56 + this.default = parser.parseLengthCodedString();
57 + } else {
58 + this.table = parser.parseLengthCodedString();
59 + this.name = parser.parseLengthCodedString();
60 + this.length = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1));
61 + this.type = parser.parseUnsignedNumber(parser.parseUnsignedNumber(1));
62 + }
63 +};
64 +
65 +FieldPacket.prototype.write = function(writer) {
66 + if (this.protocol41) {
67 + writer.writeLengthCodedString(this.catalog);
68 + writer.writeLengthCodedString(this.db);
69 + writer.writeLengthCodedString(this.table);
70 + writer.writeLengthCodedString(this.orgTable);
71 + writer.writeLengthCodedString(this.name);
72 + writer.writeLengthCodedString(this.orgName);
73 +
74 + writer.writeLengthCodedNumber(0x0c);
75 + writer.writeUnsignedNumber(2, this.charsetNr || 0);
76 + writer.writeUnsignedNumber(4, this.length || 0);
77 + writer.writeUnsignedNumber(1, this.type || 0);
78 + writer.writeUnsignedNumber(2, this.flags || 0);
79 + writer.writeUnsignedNumber(1, this.decimals || 0);
80 + writer.writeFiller(2);
81 +
82 + if (this.default !== undefined) {
83 + writer.writeLengthCodedString(this.default);
84 + }
85 + } else {
86 + writer.writeLengthCodedString(this.table);
87 + writer.writeLengthCodedString(this.name);
88 + writer.writeUnsignedNumber(1, 0x01);
89 + writer.writeUnsignedNumber(1, this.length);
90 + writer.writeUnsignedNumber(1, 0x01);
91 + writer.writeUnsignedNumber(1, this.type);
92 + }
93 +};
1 +var Buffer = require('safe-buffer').Buffer;
2 +var Client = require('../constants/client');
3 +
4 +module.exports = HandshakeInitializationPacket;
5 +function HandshakeInitializationPacket(options) {
6 + options = options || {};
7 +
8 + this.protocolVersion = options.protocolVersion;
9 + this.serverVersion = options.serverVersion;
10 + this.threadId = options.threadId;
11 + this.scrambleBuff1 = options.scrambleBuff1;
12 + this.filler1 = options.filler1;
13 + this.serverCapabilities1 = options.serverCapabilities1;
14 + this.serverLanguage = options.serverLanguage;
15 + this.serverStatus = options.serverStatus;
16 + this.serverCapabilities2 = options.serverCapabilities2;
17 + this.scrambleLength = options.scrambleLength;
18 + this.filler2 = options.filler2;
19 + this.scrambleBuff2 = options.scrambleBuff2;
20 + this.filler3 = options.filler3;
21 + this.pluginData = options.pluginData;
22 + this.protocol41 = options.protocol41;
23 +
24 + if (this.protocol41) {
25 + // force set the bit in serverCapabilities1
26 + this.serverCapabilities1 |= Client.CLIENT_PROTOCOL_41;
27 + }
28 +}
29 +
30 +HandshakeInitializationPacket.prototype.parse = function(parser) {
31 + this.protocolVersion = parser.parseUnsignedNumber(1);
32 + this.serverVersion = parser.parseNullTerminatedString();
33 + this.threadId = parser.parseUnsignedNumber(4);
34 + this.scrambleBuff1 = parser.parseBuffer(8);
35 + this.filler1 = parser.parseFiller(1);
36 + this.serverCapabilities1 = parser.parseUnsignedNumber(2);
37 + this.serverLanguage = parser.parseUnsignedNumber(1);
38 + this.serverStatus = parser.parseUnsignedNumber(2);
39 +
40 + this.protocol41 = (this.serverCapabilities1 & (1 << 9)) > 0;
41 +
42 + if (this.protocol41) {
43 + this.serverCapabilities2 = parser.parseUnsignedNumber(2);
44 + this.scrambleLength = parser.parseUnsignedNumber(1);
45 + this.filler2 = parser.parseFiller(10);
46 + // scrambleBuff2 should be 0x00 terminated, but sphinx does not do this
47 + // so we assume scrambleBuff2 to be 12 byte and treat the next byte as a
48 + // filler byte.
49 + this.scrambleBuff2 = parser.parseBuffer(12);
50 + this.filler3 = parser.parseFiller(1);
51 + } else {
52 + this.filler2 = parser.parseFiller(13);
53 + }
54 +
55 + if (parser.reachedPacketEnd()) {
56 + return;
57 + }
58 +
59 + // According to the docs this should be 0x00 terminated, but MariaDB does
60 + // not do this, so we assume this string to be packet terminated.
61 + this.pluginData = parser.parsePacketTerminatedString();
62 +
63 + // However, if there is a trailing '\0', strip it
64 + var lastChar = this.pluginData.length - 1;
65 + if (this.pluginData[lastChar] === '\0') {
66 + this.pluginData = this.pluginData.substr(0, lastChar);
67 + }
68 +};
69 +
70 +HandshakeInitializationPacket.prototype.write = function(writer) {
71 + writer.writeUnsignedNumber(1, this.protocolVersion);
72 + writer.writeNullTerminatedString(this.serverVersion);
73 + writer.writeUnsignedNumber(4, this.threadId);
74 + writer.writeBuffer(this.scrambleBuff1);
75 + writer.writeFiller(1);
76 + writer.writeUnsignedNumber(2, this.serverCapabilities1);
77 + writer.writeUnsignedNumber(1, this.serverLanguage);
78 + writer.writeUnsignedNumber(2, this.serverStatus);
79 + if (this.protocol41) {
80 + writer.writeUnsignedNumber(2, this.serverCapabilities2);
81 + writer.writeUnsignedNumber(1, this.scrambleLength);
82 + writer.writeFiller(10);
83 + }
84 + writer.writeNullTerminatedBuffer(this.scrambleBuff2);
85 +
86 + if (this.pluginData !== undefined) {
87 + writer.writeNullTerminatedString(this.pluginData);
88 + }
89 +};
90 +
91 +HandshakeInitializationPacket.prototype.scrambleBuff = function() {
92 + var buffer = null;
93 +
94 + if (typeof this.scrambleBuff2 === 'undefined') {
95 + buffer = Buffer.from(this.scrambleBuff1);
96 + } else {
97 + buffer = Buffer.allocUnsafe(this.scrambleBuff1.length + this.scrambleBuff2.length);
98 + this.scrambleBuff1.copy(buffer, 0);
99 + this.scrambleBuff2.copy(buffer, this.scrambleBuff1.length);
100 + }
101 +
102 + return buffer;
103 +};
1 +module.exports = LocalDataFilePacket;
2 +
3 +/**
4 + * Create a new LocalDataFilePacket
5 + * @constructor
6 + * @param {Buffer} data The data contents of the packet
7 + * @public
8 + */
9 +function LocalDataFilePacket(data) {
10 + this.data = data;
11 +}
12 +
13 +LocalDataFilePacket.prototype.write = function(writer) {
14 + writer.writeBuffer(this.data);
15 +};
1 +
2 +// Language-neutral expression to match ER_UPDATE_INFO
3 +var ER_UPDATE_INFO_REGEXP = /^[^:0-9]+: [0-9]+[^:0-9]+: ([0-9]+)[^:0-9]+: [0-9]+[^:0-9]*$/;
4 +
5 +module.exports = OkPacket;
6 +function OkPacket(options) {
7 + options = options || {};
8 +
9 + this.fieldCount = undefined;
10 + this.affectedRows = undefined;
11 + this.insertId = undefined;
12 + this.serverStatus = undefined;
13 + this.warningCount = undefined;
14 + this.message = undefined;
15 + this.protocol41 = options.protocol41;
16 +}
17 +
18 +OkPacket.prototype.parse = function(parser) {
19 + this.fieldCount = parser.parseUnsignedNumber(1);
20 + this.affectedRows = parser.parseLengthCodedNumber();
21 + this.insertId = parser.parseLengthCodedNumber();
22 + if (this.protocol41) {
23 + this.serverStatus = parser.parseUnsignedNumber(2);
24 + this.warningCount = parser.parseUnsignedNumber(2);
25 + }
26 + this.message = parser.parsePacketTerminatedString();
27 + this.changedRows = 0;
28 +
29 + var m = ER_UPDATE_INFO_REGEXP.exec(this.message);
30 + if (m !== null) {
31 + this.changedRows = parseInt(m[1], 10);
32 + }
33 +};
34 +
35 +OkPacket.prototype.write = function(writer) {
36 + writer.writeUnsignedNumber(1, 0x00);
37 + writer.writeLengthCodedNumber(this.affectedRows || 0);
38 + writer.writeLengthCodedNumber(this.insertId || 0);
39 + if (this.protocol41) {
40 + writer.writeUnsignedNumber(2, this.serverStatus || 0);
41 + writer.writeUnsignedNumber(2, this.warningCount || 0);
42 + }
43 + writer.writeString(this.message);
44 +};
1 +module.exports = OldPasswordPacket;
2 +function OldPasswordPacket(options) {
3 + options = options || {};
4 +
5 + this.scrambleBuff = options.scrambleBuff;
6 +}
7 +
8 +OldPasswordPacket.prototype.parse = function(parser) {
9 + this.scrambleBuff = parser.parseNullTerminatedBuffer();
10 +};
11 +
12 +OldPasswordPacket.prototype.write = function(writer) {
13 + writer.writeBuffer(this.scrambleBuff);
14 + writer.writeFiller(1);
15 +};
1 +module.exports = ResultSetHeaderPacket;
2 +function ResultSetHeaderPacket(options) {
3 + options = options || {};
4 +
5 + this.fieldCount = options.fieldCount;
6 + this.extra = options.extra;
7 +}
8 +
9 +ResultSetHeaderPacket.prototype.parse = function(parser) {
10 + this.fieldCount = parser.parseLengthCodedNumber();
11 +
12 + if (parser.reachedPacketEnd()) return;
13 +
14 + this.extra = (this.fieldCount === null)
15 + ? parser.parsePacketTerminatedString()
16 + : parser.parseLengthCodedNumber();
17 +};
18 +
19 +ResultSetHeaderPacket.prototype.write = function(writer) {
20 + writer.writeLengthCodedNumber(this.fieldCount);
21 +
22 + if (this.extra !== undefined) {
23 + writer.writeLengthCodedNumber(this.extra);
24 + }
25 +};
1 +var Types = require('../constants/types');
2 +var Charsets = require('../constants/charsets');
3 +var Field = require('./Field');
4 +var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53);
5 +
6 +module.exports = RowDataPacket;
7 +function RowDataPacket() {
8 +}
9 +
10 +Object.defineProperty(RowDataPacket.prototype, 'parse', {
11 + configurable : true,
12 + enumerable : false,
13 + value : parse
14 +});
15 +
16 +Object.defineProperty(RowDataPacket.prototype, '_typeCast', {
17 + configurable : true,
18 + enumerable : false,
19 + value : typeCast
20 +});
21 +
22 +function parse(parser, fieldPackets, typeCast, nestTables, connection) {
23 + var self = this;
24 + var next = function () {
25 + return self._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings, connection.config.dateStrings);
26 + };
27 +
28 + for (var i = 0; i < fieldPackets.length; i++) {
29 + var fieldPacket = fieldPackets[i];
30 + var value;
31 +
32 + if (typeof typeCast === 'function') {
33 + value = typeCast.apply(connection, [ new Field({ packet: fieldPacket, parser: parser }), next ]);
34 + } else {
35 + value = (typeCast)
36 + ? this._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings, connection.config.dateStrings)
37 + : ( (fieldPacket.charsetNr === Charsets.BINARY)
38 + ? parser.parseLengthCodedBuffer()
39 + : parser.parseLengthCodedString() );
40 + }
41 +
42 + if (typeof nestTables === 'string' && nestTables.length) {
43 + this[fieldPacket.table + nestTables + fieldPacket.name] = value;
44 + } else if (nestTables) {
45 + this[fieldPacket.table] = this[fieldPacket.table] || {};
46 + this[fieldPacket.table][fieldPacket.name] = value;
47 + } else {
48 + this[fieldPacket.name] = value;
49 + }
50 + }
51 +}
52 +
53 +function typeCast(field, parser, timeZone, supportBigNumbers, bigNumberStrings, dateStrings) {
54 + var numberString;
55 +
56 + switch (field.type) {
57 + case Types.TIMESTAMP:
58 + case Types.TIMESTAMP2:
59 + case Types.DATE:
60 + case Types.DATETIME:
61 + case Types.DATETIME2:
62 + case Types.NEWDATE:
63 + var dateString = parser.parseLengthCodedString();
64 +
65 + if (typeMatch(field.type, dateStrings)) {
66 + return dateString;
67 + }
68 +
69 + if (dateString === null) {
70 + return null;
71 + }
72 +
73 + var originalString = dateString;
74 + if (field.type === Types.DATE) {
75 + dateString += ' 00:00:00';
76 + }
77 +
78 + if (timeZone !== 'local') {
79 + dateString += ' ' + timeZone;
80 + }
81 +
82 + var dt = new Date(dateString);
83 + if (isNaN(dt.getTime())) {
84 + return originalString;
85 + }
86 +
87 + return dt;
88 + case Types.TINY:
89 + case Types.SHORT:
90 + case Types.LONG:
91 + case Types.INT24:
92 + case Types.YEAR:
93 + case Types.FLOAT:
94 + case Types.DOUBLE:
95 + numberString = parser.parseLengthCodedString();
96 + return (numberString === null || (field.zeroFill && numberString[0] === '0'))
97 + ? numberString : Number(numberString);
98 + case Types.NEWDECIMAL:
99 + case Types.LONGLONG:
100 + numberString = parser.parseLengthCodedString();
101 + return (numberString === null || (field.zeroFill && numberString[0] === '0'))
102 + ? numberString
103 + : ((supportBigNumbers && (bigNumberStrings || (Number(numberString) >= IEEE_754_BINARY_64_PRECISION) || Number(numberString) <= -IEEE_754_BINARY_64_PRECISION))
104 + ? numberString
105 + : Number(numberString));
106 + case Types.BIT:
107 + return parser.parseLengthCodedBuffer();
108 + case Types.STRING:
109 + case Types.VAR_STRING:
110 + case Types.TINY_BLOB:
111 + case Types.MEDIUM_BLOB:
112 + case Types.LONG_BLOB:
113 + case Types.BLOB:
114 + return (field.charsetNr === Charsets.BINARY)
115 + ? parser.parseLengthCodedBuffer()
116 + : parser.parseLengthCodedString();
117 + case Types.GEOMETRY:
118 + return parser.parseGeometryValue();
119 + default:
120 + return parser.parseLengthCodedString();
121 + }
122 +}
123 +
124 +function typeMatch(type, list) {
125 + if (Array.isArray(list)) {
126 + for (var i = 0; i < list.length; i++) {
127 + if (Types[list[i]] === type) return true;
128 + }
129 + return false;
130 + } else {
131 + return Boolean(list);
132 + }
133 +}
1 +// http://dev.mysql.com/doc/internals/en/ssl.html
2 +// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::SSLRequest
3 +
4 +var ClientConstants = require('../constants/client');
5 +
6 +module.exports = SSLRequestPacket;
7 +
8 +function SSLRequestPacket(options) {
9 + options = options || {};
10 + this.clientFlags = options.clientFlags | ClientConstants.CLIENT_SSL;
11 + this.maxPacketSize = options.maxPacketSize;
12 + this.charsetNumber = options.charsetNumber;
13 +}
14 +
15 +SSLRequestPacket.prototype.parse = function(parser) {
16 + // TODO: check SSLRequest packet v41 vs pre v41
17 + this.clientFlags = parser.parseUnsignedNumber(4);
18 + this.maxPacketSize = parser.parseUnsignedNumber(4);
19 + this.charsetNumber = parser.parseUnsignedNumber(1);
20 +};
21 +
22 +SSLRequestPacket.prototype.write = function(writer) {
23 + writer.writeUnsignedNumber(4, this.clientFlags);
24 + writer.writeUnsignedNumber(4, this.maxPacketSize);
25 + writer.writeUnsignedNumber(1, this.charsetNumber);
26 + writer.writeFiller(23);
27 +};
1 +module.exports = StatisticsPacket;
2 +function StatisticsPacket() {
3 + this.message = undefined;
4 +}
5 +
6 +StatisticsPacket.prototype.parse = function(parser) {
7 + this.message = parser.parsePacketTerminatedString();
8 +
9 + var items = this.message.split(/\s\s/);
10 + for (var i = 0; i < items.length; i++) {
11 + var m = items[i].match(/^(.+)\:\s+(.+)$/);
12 + if (m !== null) {
13 + this[m[1].toLowerCase().replace(/\s/g, '_')] = Number(m[2]);
14 + }
15 + }
16 +};
17 +
18 +StatisticsPacket.prototype.write = function(writer) {
19 + writer.writeString(this.message);
20 +};
1 +module.exports = UseOldPasswordPacket;
2 +function UseOldPasswordPacket(options) {
3 + options = options || {};
4 +
5 + this.firstByte = options.firstByte || 0xfe;
6 +}
7 +
8 +UseOldPasswordPacket.prototype.parse = function(parser) {
9 + this.firstByte = parser.parseUnsignedNumber(1);
10 +};
11 +
12 +UseOldPasswordPacket.prototype.write = function(writer) {
13 + writer.writeUnsignedNumber(1, this.firstByte);
14 +};
1 +exports.AuthSwitchRequestPacket = require('./AuthSwitchRequestPacket');
2 +exports.AuthSwitchResponsePacket = require('./AuthSwitchResponsePacket');
3 +exports.ClientAuthenticationPacket = require('./ClientAuthenticationPacket');
4 +exports.ComChangeUserPacket = require('./ComChangeUserPacket');
5 +exports.ComPingPacket = require('./ComPingPacket');
6 +exports.ComQueryPacket = require('./ComQueryPacket');
7 +exports.ComQuitPacket = require('./ComQuitPacket');
8 +exports.ComStatisticsPacket = require('./ComStatisticsPacket');
9 +exports.EmptyPacket = require('./EmptyPacket');
10 +exports.EofPacket = require('./EofPacket');
11 +exports.ErrorPacket = require('./ErrorPacket');
12 +exports.Field = require('./Field');
13 +exports.FieldPacket = require('./FieldPacket');
14 +exports.HandshakeInitializationPacket = require('./HandshakeInitializationPacket');
15 +exports.LocalDataFilePacket = require('./LocalDataFilePacket');
16 +exports.OkPacket = require('./OkPacket');
17 +exports.OldPasswordPacket = require('./OldPasswordPacket');
18 +exports.ResultSetHeaderPacket = require('./ResultSetHeaderPacket');
19 +exports.RowDataPacket = require('./RowDataPacket');
20 +exports.SSLRequestPacket = require('./SSLRequestPacket');
21 +exports.StatisticsPacket = require('./StatisticsPacket');
22 +exports.UseOldPasswordPacket = require('./UseOldPasswordPacket');
1 +var Sequence = require('./Sequence');
2 +var Util = require('util');
3 +var Packets = require('../packets');
4 +var Auth = require('../Auth');
5 +
6 +module.exports = ChangeUser;
7 +Util.inherits(ChangeUser, Sequence);
8 +function ChangeUser(options, callback) {
9 + Sequence.call(this, options, callback);
10 +
11 + this._user = options.user;
12 + this._password = options.password;
13 + this._database = options.database;
14 + this._charsetNumber = options.charsetNumber;
15 + this._currentConfig = options.currentConfig;
16 +}
17 +
18 +ChangeUser.prototype.start = function(handshakeInitializationPacket) {
19 + var scrambleBuff = handshakeInitializationPacket.scrambleBuff();
20 + scrambleBuff = Auth.token(this._password, scrambleBuff);
21 +
22 + var packet = new Packets.ComChangeUserPacket({
23 + user : this._user,
24 + scrambleBuff : scrambleBuff,
25 + database : this._database,
26 + charsetNumber : this._charsetNumber
27 + });
28 +
29 + this._currentConfig.user = this._user;
30 + this._currentConfig.password = this._password;
31 + this._currentConfig.database = this._database;
32 + this._currentConfig.charsetNumber = this._charsetNumber;
33 +
34 + this.emit('packet', packet);
35 +};
36 +
37 +ChangeUser.prototype['ErrorPacket'] = function(packet) {
38 + var err = this._packetToError(packet);
39 + err.fatal = true;
40 + this.end(err);
41 +};
1 +var Sequence = require('./Sequence');
2 +var Util = require('util');
3 +var Packets = require('../packets');
4 +var Auth = require('../Auth');
5 +var ClientConstants = require('../constants/client');
6 +
7 +module.exports = Handshake;
8 +Util.inherits(Handshake, Sequence);
9 +function Handshake(options, callback) {
10 + Sequence.call(this, options, callback);
11 +
12 + options = options || {};
13 +
14 + this._config = options.config;
15 + this._handshakeInitializationPacket = null;
16 +}
17 +
18 +Handshake.prototype.determinePacket = function determinePacket(firstByte, parser) {
19 + if (firstByte === 0xff) {
20 + return Packets.ErrorPacket;
21 + }
22 +
23 + if (!this._handshakeInitializationPacket) {
24 + return Packets.HandshakeInitializationPacket;
25 + }
26 +
27 + if (firstByte === 0xfe) {
28 + return (parser.packetLength() === 1)
29 + ? Packets.UseOldPasswordPacket
30 + : Packets.AuthSwitchRequestPacket;
31 + }
32 +
33 + return undefined;
34 +};
35 +
36 +Handshake.prototype['AuthSwitchRequestPacket'] = function (packet) {
37 + if (packet.authMethodName === 'mysql_native_password') {
38 + var challenge = packet.authMethodData.slice(0, 20);
39 +
40 + this.emit('packet', new Packets.AuthSwitchResponsePacket({
41 + data: Auth.token(this._config.password, challenge)
42 + }));
43 + } else {
44 + var err = new Error(
45 + 'MySQL is requesting the ' + packet.authMethodName + ' authentication method, which is not supported.'
46 + );
47 +
48 + err.code = 'UNSUPPORTED_AUTH_METHOD';
49 + err.fatal = true;
50 +
51 + this.end(err);
52 + }
53 +};
54 +
55 +Handshake.prototype['HandshakeInitializationPacket'] = function(packet) {
56 + this._handshakeInitializationPacket = packet;
57 +
58 + this._config.protocol41 = packet.protocol41;
59 +
60 + var serverSSLSupport = packet.serverCapabilities1 & ClientConstants.CLIENT_SSL;
61 +
62 + if (this._config.ssl) {
63 + if (!serverSSLSupport) {
64 + var err = new Error('Server does not support secure connection');
65 +
66 + err.code = 'HANDSHAKE_NO_SSL_SUPPORT';
67 + err.fatal = true;
68 +
69 + this.end(err);
70 + return;
71 + }
72 +
73 + this._config.clientFlags |= ClientConstants.CLIENT_SSL;
74 + this.emit('packet', new Packets.SSLRequestPacket({
75 + clientFlags : this._config.clientFlags,
76 + maxPacketSize : this._config.maxPacketSize,
77 + charsetNumber : this._config.charsetNumber
78 + }));
79 + this.emit('start-tls');
80 + } else {
81 + this._sendCredentials();
82 + }
83 +};
84 +
85 +Handshake.prototype._tlsUpgradeCompleteHandler = function() {
86 + this._sendCredentials();
87 +};
88 +
89 +Handshake.prototype._sendCredentials = function() {
90 + var packet = this._handshakeInitializationPacket;
91 + this.emit('packet', new Packets.ClientAuthenticationPacket({
92 + clientFlags : this._config.clientFlags,
93 + maxPacketSize : this._config.maxPacketSize,
94 + charsetNumber : this._config.charsetNumber,
95 + user : this._config.user,
96 + database : this._config.database,
97 + protocol41 : packet.protocol41,
98 + scrambleBuff : (packet.protocol41)
99 + ? Auth.token(this._config.password, packet.scrambleBuff())
100 + : Auth.scramble323(packet.scrambleBuff(), this._config.password)
101 + }));
102 +};
103 +
104 +Handshake.prototype['UseOldPasswordPacket'] = function() {
105 + if (!this._config.insecureAuth) {
106 + var err = new Error(
107 + 'MySQL server is requesting the old and insecure pre-4.1 auth mechanism. ' +
108 + 'Upgrade the user password or use the {insecureAuth: true} option.'
109 + );
110 +
111 + err.code = 'HANDSHAKE_INSECURE_AUTH';
112 + err.fatal = true;
113 +
114 + this.end(err);
115 + return;
116 + }
117 +
118 + this.emit('packet', new Packets.OldPasswordPacket({
119 + scrambleBuff: Auth.scramble323(this._handshakeInitializationPacket.scrambleBuff(), this._config.password)
120 + }));
121 +};
122 +
123 +Handshake.prototype['ErrorPacket'] = function(packet) {
124 + var err = this._packetToError(packet, true);
125 + err.fatal = true;
126 + this.end(err);
127 +};
1 +var Sequence = require('./Sequence');
2 +var Util = require('util');
3 +var Packets = require('../packets');
4 +
5 +module.exports = Ping;
6 +Util.inherits(Ping, Sequence);
7 +
8 +function Ping(options, callback) {
9 + if (!callback && typeof options === 'function') {
10 + callback = options;
11 + options = {};
12 + }
13 +
14 + Sequence.call(this, options, callback);
15 +}
16 +
17 +Ping.prototype.start = function() {
18 + this.emit('packet', new Packets.ComPingPacket());
19 +};
1 +var Sequence = require('./Sequence');
2 +var Util = require('util');
3 +var Packets = require('../packets');
4 +var ResultSet = require('../ResultSet');
5 +var ServerStatus = require('../constants/server_status');
6 +var fs = require('fs');
7 +var Readable = require('readable-stream');
8 +
9 +module.exports = Query;
10 +Util.inherits(Query, Sequence);
11 +function Query(options, callback) {
12 + Sequence.call(this, options, callback);
13 +
14 + this.sql = options.sql;
15 + this.values = options.values;
16 + this.typeCast = (options.typeCast === undefined)
17 + ? true
18 + : options.typeCast;
19 + this.nestTables = options.nestTables || false;
20 +
21 + this._resultSet = null;
22 + this._results = [];
23 + this._fields = [];
24 + this._index = 0;
25 + this._loadError = null;
26 +}
27 +
28 +Query.prototype.start = function() {
29 + this.emit('packet', new Packets.ComQueryPacket(this.sql));
30 +};
31 +
32 +Query.prototype.determinePacket = function determinePacket(byte, parser) {
33 + var resultSet = this._resultSet;
34 +
35 + if (!resultSet) {
36 + switch (byte) {
37 + case 0x00: return Packets.OkPacket;
38 + case 0xff: return Packets.ErrorPacket;
39 + default: return Packets.ResultSetHeaderPacket;
40 + }
41 + }
42 +
43 + if (resultSet.eofPackets.length === 0) {
44 + return (resultSet.fieldPackets.length < resultSet.resultSetHeaderPacket.fieldCount)
45 + ? Packets.FieldPacket
46 + : Packets.EofPacket;
47 + }
48 +
49 + if (byte === 0xff) {
50 + return Packets.ErrorPacket;
51 + }
52 +
53 + if (byte === 0xfe && parser.packetLength() < 9) {
54 + return Packets.EofPacket;
55 + }
56 +
57 + return Packets.RowDataPacket;
58 +};
59 +
60 +Query.prototype['OkPacket'] = function(packet) {
61 + // try...finally for exception safety
62 + try {
63 + if (!this._callback) {
64 + this.emit('result', packet, this._index);
65 + } else {
66 + this._results.push(packet);
67 + this._fields.push(undefined);
68 + }
69 + } finally {
70 + this._index++;
71 + this._resultSet = null;
72 + this._handleFinalResultPacket(packet);
73 + }
74 +};
75 +
76 +Query.prototype['ErrorPacket'] = function(packet) {
77 + var err = this._packetToError(packet);
78 +
79 + var results = (this._results.length > 0)
80 + ? this._results
81 + : undefined;
82 +
83 + var fields = (this._fields.length > 0)
84 + ? this._fields
85 + : undefined;
86 +
87 + err.index = this._index;
88 + err.sql = this.sql;
89 +
90 + this.end(err, results, fields);
91 +};
92 +
93 +Query.prototype['ResultSetHeaderPacket'] = function(packet) {
94 + if (packet.fieldCount === null) {
95 + this._sendLocalDataFile(packet.extra);
96 + } else {
97 + this._resultSet = new ResultSet(packet);
98 + }
99 +};
100 +
101 +Query.prototype['FieldPacket'] = function(packet) {
102 + this._resultSet.fieldPackets.push(packet);
103 +};
104 +
105 +Query.prototype['EofPacket'] = function(packet) {
106 + this._resultSet.eofPackets.push(packet);
107 +
108 + if (this._resultSet.eofPackets.length === 1 && !this._callback) {
109 + this.emit('fields', this._resultSet.fieldPackets, this._index);
110 + }
111 +
112 + if (this._resultSet.eofPackets.length !== 2) {
113 + return;
114 + }
115 +
116 + if (this._callback) {
117 + this._results.push(this._resultSet.rows);
118 + this._fields.push(this._resultSet.fieldPackets);
119 + }
120 +
121 + this._index++;
122 + this._resultSet = null;
123 + this._handleFinalResultPacket(packet);
124 +};
125 +
126 +Query.prototype._handleFinalResultPacket = function(packet) {
127 + if (packet.serverStatus & ServerStatus.SERVER_MORE_RESULTS_EXISTS) {
128 + return;
129 + }
130 +
131 + var results = (this._results.length > 1)
132 + ? this._results
133 + : this._results[0];
134 +
135 + var fields = (this._fields.length > 1)
136 + ? this._fields
137 + : this._fields[0];
138 +
139 + this.end(this._loadError, results, fields);
140 +};
141 +
142 +Query.prototype['RowDataPacket'] = function(packet, parser, connection) {
143 + packet.parse(parser, this._resultSet.fieldPackets, this.typeCast, this.nestTables, connection);
144 +
145 + if (this._callback) {
146 + this._resultSet.rows.push(packet);
147 + } else {
148 + this.emit('result', packet, this._index);
149 + }
150 +};
151 +
152 +Query.prototype._sendLocalDataFile = function(path) {
153 + var self = this;
154 + var localStream = fs.createReadStream(path, {
155 + flag : 'r',
156 + encoding : null,
157 + autoClose : true
158 + });
159 +
160 + this.on('pause', function () {
161 + localStream.pause();
162 + });
163 +
164 + this.on('resume', function () {
165 + localStream.resume();
166 + });
167 +
168 + localStream.on('data', function (data) {
169 + self.emit('packet', new Packets.LocalDataFilePacket(data));
170 + });
171 +
172 + localStream.on('error', function (err) {
173 + self._loadError = err;
174 + localStream.emit('end');
175 + });
176 +
177 + localStream.on('end', function () {
178 + self.emit('packet', new Packets.EmptyPacket());
179 + });
180 +};
181 +
182 +Query.prototype.stream = function(options) {
183 + var self = this;
184 +
185 + options = options || {};
186 + options.objectMode = true;
187 +
188 + var stream = new Readable(options);
189 +
190 + stream._read = function() {
191 + self._connection && self._connection.resume();
192 + };
193 +
194 + stream.once('end', function() {
195 + process.nextTick(function () {
196 + stream.emit('close');
197 + });
198 + });
199 +
200 + this.on('result', function(row, i) {
201 + if (!stream.push(row)) self._connection.pause();
202 + stream.emit('result', row, i); // replicate old emitter
203 + });
204 +
205 + this.on('error', function(err) {
206 + stream.emit('error', err); // Pass on any errors
207 + });
208 +
209 + this.on('end', function() {
210 + stream.push(null); // pushing null, indicating EOF
211 + });
212 +
213 + this.on('fields', function(fields, i) {
214 + stream.emit('fields', fields, i); // replicate old emitter
215 + });
216 +
217 + return stream;
218 +};
1 +var Sequence = require('./Sequence');
2 +var Util = require('util');
3 +var Packets = require('../packets');
4 +
5 +module.exports = Quit;
6 +Util.inherits(Quit, Sequence);
7 +function Quit(options, callback) {
8 + if (!callback && typeof options === 'function') {
9 + callback = options;
10 + options = {};
11 + }
12 +
13 + Sequence.call(this, options, callback);
14 +
15 + this._started = false;
16 +}
17 +
18 +Quit.prototype.end = function end(err) {
19 + if (this._ended) {
20 + return;
21 + }
22 +
23 + if (!this._started) {
24 + Sequence.prototype.end.call(this, err);
25 + return;
26 + }
27 +
28 + if (err && err.code === 'ECONNRESET' && err.syscall === 'read') {
29 + // Ignore read errors after packet sent
30 + Sequence.prototype.end.call(this);
31 + return;
32 + }
33 +
34 + Sequence.prototype.end.call(this, err);
35 +};
36 +
37 +Quit.prototype.start = function() {
38 + this._started = true;
39 + this.emit('packet', new Packets.ComQuitPacket());
40 +};
1 +var Util = require('util');
2 +var EventEmitter = require('events').EventEmitter;
3 +var Packets = require('../packets');
4 +var ErrorConstants = require('../constants/errors');
5 +var Timer = require('../Timer');
6 +
7 +// istanbul ignore next: Node.js < 0.10 not covered
8 +var listenerCount = EventEmitter.listenerCount
9 + || function(emitter, type){ return emitter.listeners(type).length; };
10 +
11 +var LONG_STACK_DELIMITER = '\n --------------------\n';
12 +
13 +module.exports = Sequence;
14 +Util.inherits(Sequence, EventEmitter);
15 +function Sequence(options, callback) {
16 + if (typeof options === 'function') {
17 + callback = options;
18 + options = {};
19 + }
20 +
21 + EventEmitter.call(this);
22 +
23 + options = options || {};
24 +
25 + this._callback = callback;
26 + this._callSite = null;
27 + this._ended = false;
28 + this._timeout = options.timeout;
29 + this._timer = new Timer(this);
30 +}
31 +
32 +Sequence.determinePacket = function(byte) {
33 + switch (byte) {
34 + case 0x00: return Packets.OkPacket;
35 + case 0xfe: return Packets.EofPacket;
36 + case 0xff: return Packets.ErrorPacket;
37 + default: return undefined;
38 + }
39 +};
40 +
41 +Sequence.prototype.hasErrorHandler = function() {
42 + return Boolean(this._callback) || listenerCount(this, 'error') > 1;
43 +};
44 +
45 +Sequence.prototype._packetToError = function(packet) {
46 + var code = ErrorConstants[packet.errno] || 'UNKNOWN_CODE_PLEASE_REPORT';
47 + var err = new Error(code + ': ' + packet.message);
48 + err.code = code;
49 + err.errno = packet.errno;
50 +
51 + err.sqlMessage = packet.message;
52 + err.sqlState = packet.sqlState;
53 +
54 + return err;
55 +};
56 +
57 +Sequence.prototype.end = function(err) {
58 + if (this._ended) {
59 + return;
60 + }
61 +
62 + this._ended = true;
63 +
64 + if (err) {
65 + this._addLongStackTrace(err);
66 + }
67 +
68 + // Without this we are leaking memory. This problem was introduced in
69 + // 8189925374e7ce3819bbe88b64c7b15abac96b16. I suspect that the error object
70 + // causes a cyclic reference that the GC does not detect properly, but I was
71 + // unable to produce a standalone version of this leak. This would be a great
72 + // challenge for somebody interested in difficult problems : )!
73 + this._callSite = null;
74 +
75 + // try...finally for exception safety
76 + try {
77 + if (err) {
78 + this.emit('error', err);
79 + }
80 + } finally {
81 + try {
82 + if (this._callback) {
83 + this._callback.apply(this, arguments);
84 + }
85 + } finally {
86 + this.emit('end');
87 + }
88 + }
89 +};
90 +
91 +Sequence.prototype['OkPacket'] = function(packet) {
92 + this.end(null, packet);
93 +};
94 +
95 +Sequence.prototype['ErrorPacket'] = function(packet) {
96 + this.end(this._packetToError(packet));
97 +};
98 +
99 +// Implemented by child classes
100 +Sequence.prototype.start = function() {};
101 +
102 +Sequence.prototype._addLongStackTrace = function _addLongStackTrace(err) {
103 + var callSiteStack = this._callSite && this._callSite.stack;
104 +
105 + if (!callSiteStack || typeof callSiteStack !== 'string') {
106 + // No recorded call site
107 + return;
108 + }
109 +
110 + if (err.stack.indexOf(LONG_STACK_DELIMITER) !== -1) {
111 + // Error stack already looks long
112 + return;
113 + }
114 +
115 + var index = callSiteStack.indexOf('\n');
116 +
117 + if (index !== -1) {
118 + // Append recorded call site
119 + err.stack += LONG_STACK_DELIMITER + callSiteStack.substr(index + 1);
120 + }
121 +};
122 +
123 +Sequence.prototype._onTimeout = function _onTimeout() {
124 + this.emit('timeout');
125 +};
1 +var Sequence = require('./Sequence');
2 +var Util = require('util');
3 +var Packets = require('../packets');
4 +
5 +module.exports = Statistics;
6 +Util.inherits(Statistics, Sequence);
7 +function Statistics(options, callback) {
8 + if (!callback && typeof options === 'function') {
9 + callback = options;
10 + options = {};
11 + }
12 +
13 + Sequence.call(this, options, callback);
14 +}
15 +
16 +Statistics.prototype.start = function() {
17 + this.emit('packet', new Packets.ComStatisticsPacket());
18 +};
19 +
20 +Statistics.prototype['StatisticsPacket'] = function (packet) {
21 + this.end(null, packet);
22 +};
23 +
24 +Statistics.prototype.determinePacket = function determinePacket(firstByte) {
25 + if (firstByte === 0x55) {
26 + return Packets.StatisticsPacket;
27 + }
28 +
29 + return undefined;
30 +};
1 +exports.ChangeUser = require('./ChangeUser');
2 +exports.Handshake = require('./Handshake');
3 +exports.Ping = require('./Ping');
4 +exports.Query = require('./Query');
5 +exports.Quit = require('./Quit');
6 +exports.Sequence = require('./Sequence');
7 +exports.Statistics = require('./Statistics');
1 +{
2 + "_from": "mysql@^2.14.1",
3 + "_id": "mysql@2.16.0",
4 + "_inBundle": false,
5 + "_integrity": "sha512-dPbN2LHonQp7D5ja5DJXNbCLe/HRdu+f3v61aguzNRQIrmZLOeRoymBYyeThrR6ug+FqzDL95Gc9maqZUJS+Gw==",
6 + "_location": "/mysql",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "mysql@^2.14.1",
12 + "name": "mysql",
13 + "escapedName": "mysql",
14 + "rawSpec": "^2.14.1",
15 + "saveSpec": null,
16 + "fetchSpec": "^2.14.1"
17 + },
18 + "_requiredBy": [
19 + "/promise-mysql"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/mysql/-/mysql-2.16.0.tgz",
22 + "_shasum": "b23b22ab5de44fc2d5d32bd4f5af6653fc45e2ba",
23 + "_spec": "mysql@^2.14.1",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/promise-mysql",
25 + "author": {
26 + "name": "Felix Geisendörfer",
27 + "email": "felix@debuggable.com",
28 + "url": "http://debuggable.com/"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/mysqljs/mysql/issues"
32 + },
33 + "bundleDependencies": false,
34 + "contributors": [
35 + {
36 + "name": "Andrey Sidorov",
37 + "email": "sidorares@yandex.ru"
38 + },
39 + {
40 + "name": "Bradley Grainger",
41 + "email": "bgrainger@gmail.com"
42 + },
43 + {
44 + "name": "Douglas Christopher Wilson",
45 + "email": "doug@somethingdoug.com"
46 + },
47 + {
48 + "name": "Diogo Resende",
49 + "email": "dresende@thinkdigital.pt"
50 + },
51 + {
52 + "name": "Nathan Woltman",
53 + "email": "nwoltman@outlook.com"
54 + }
55 + ],
56 + "dependencies": {
57 + "bignumber.js": "4.1.0",
58 + "readable-stream": "2.3.6",
59 + "safe-buffer": "5.1.2",
60 + "sqlstring": "2.3.1"
61 + },
62 + "deprecated": false,
63 + "description": "A node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.",
64 + "devDependencies": {
65 + "after": "0.8.2",
66 + "eslint": "4.19.1",
67 + "nyc": "10.3.2",
68 + "seedrandom": "2.4.3",
69 + "timezone-mock": "0.0.7",
70 + "urun": "0.0.8",
71 + "utest": "0.0.8"
72 + },
73 + "engines": {
74 + "node": ">= 0.6"
75 + },
76 + "files": [
77 + "lib/",
78 + "Changes.md",
79 + "License",
80 + "Readme.md",
81 + "index.js"
82 + ],
83 + "homepage": "https://github.com/mysqljs/mysql#readme",
84 + "license": "MIT",
85 + "name": "mysql",
86 + "repository": {
87 + "type": "git",
88 + "url": "git+https://github.com/mysqljs/mysql.git"
89 + },
90 + "scripts": {
91 + "lint": "eslint .",
92 + "test": "node test/run.js",
93 + "test-ci": "nyc --reporter=text npm test",
94 + "test-cov": "nyc --reporter=html --reporter=text npm test",
95 + "version": "node tool/version-changes.js && git add Changes.md"
96 + },
97 + "version": "2.16.0"
98 +}
1 +'use strict';
2 +
3 +if (!process.version ||
4 + process.version.indexOf('v0.') === 0 ||
5 + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
6 + module.exports = { nextTick: nextTick };
7 +} else {
8 + module.exports = process
9 +}
10 +
11 +function nextTick(fn, arg1, arg2, arg3) {
12 + if (typeof fn !== 'function') {
13 + throw new TypeError('"callback" argument must be a function');
14 + }
15 + var len = arguments.length;
16 + var args, i;
17 + switch (len) {
18 + case 0:
19 + case 1:
20 + return process.nextTick(fn);
21 + case 2:
22 + return process.nextTick(function afterTickOne() {
23 + fn.call(null, arg1);
24 + });
25 + case 3:
26 + return process.nextTick(function afterTickTwo() {
27 + fn.call(null, arg1, arg2);
28 + });
29 + case 4:
30 + return process.nextTick(function afterTickThree() {
31 + fn.call(null, arg1, arg2, arg3);
32 + });
33 + default:
34 + args = new Array(len - 1);
35 + i = 0;
36 + while (i < args.length) {
37 + args[i++] = arguments[i];
38 + }
39 + return process.nextTick(function afterTick() {
40 + fn.apply(null, args);
41 + });
42 + }
43 +}
44 +
1 +# Copyright (c) 2015 Calvin Metcalf
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to deal
5 +in the Software without restriction, including without limitation the rights
6 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 +copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in all
11 +copies or substantial portions of the Software.
12 +
13 +**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 +SOFTWARE.**
1 +{
2 + "_from": "process-nextick-args@~2.0.0",
3 + "_id": "process-nextick-args@2.0.0",
4 + "_inBundle": false,
5 + "_integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==",
6 + "_location": "/process-nextick-args",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "process-nextick-args@~2.0.0",
12 + "name": "process-nextick-args",
13 + "escapedName": "process-nextick-args",
14 + "rawSpec": "~2.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "~2.0.0"
17 + },
18 + "_requiredBy": [
19 + "/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz",
22 + "_shasum": "a37d732f4271b4ab1ad070d35508e8290788ffaa",
23 + "_spec": "process-nextick-args@~2.0.0",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/readable-stream",
25 + "author": "",
26 + "bugs": {
27 + "url": "https://github.com/calvinmetcalf/process-nextick-args/issues"
28 + },
29 + "bundleDependencies": false,
30 + "deprecated": false,
31 + "description": "process.nextTick but always with args",
32 + "devDependencies": {
33 + "tap": "~0.2.6"
34 + },
35 + "files": [
36 + "index.js"
37 + ],
38 + "homepage": "https://github.com/calvinmetcalf/process-nextick-args",
39 + "license": "MIT",
40 + "main": "index.js",
41 + "name": "process-nextick-args",
42 + "repository": {
43 + "type": "git",
44 + "url": "git+https://github.com/calvinmetcalf/process-nextick-args.git"
45 + },
46 + "scripts": {
47 + "test": "node test.js"
48 + },
49 + "version": "2.0.0"
50 +}
1 +process-nextick-args
2 +=====
3 +
4 +[![Build Status](https://travis-ci.org/calvinmetcalf/process-nextick-args.svg?branch=master)](https://travis-ci.org/calvinmetcalf/process-nextick-args)
5 +
6 +```bash
7 +npm install --save process-nextick-args
8 +```
9 +
10 +Always be able to pass arguments to process.nextTick, no matter the platform
11 +
12 +```js
13 +var pna = require('process-nextick-args');
14 +
15 +pna.nextTick(function (a, b, c) {
16 + console.log(a, b, c);
17 +}, 'step', 3, 'profit');
18 +```
1 +The MIT License (MIT)
2 +
3 +Copyright (c) 2014 Luke Bonaccorsi
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +SOFTWARE.
22 +
1 +Promise-mysql
2 +==================
3 +[![Build Status](https://travis-ci.org/lukeb-uk/node-promise-mysql.svg?style=flat&branch=master)](https://travis-ci.org/lukeb-uk/node-promise-mysql?branch=master)
4 +
5 +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.
6 +
7 +To install promise-mysql, use [npm](http://github.com/isaacs/npm):
8 +
9 +```bash
10 +$ npm install promise-mysql
11 +```
12 +
13 +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
14 +
15 +At the minute only the standard connection (using `.createConnection()`) and the pool (using `.createPool()`) is supported. `createPoolCluster` is not implemented yet.
16 +
17 +## Examples
18 +
19 +### Connection
20 +
21 +**Important note: don't forget to call connection.end() when you're finished otherwise the Node process won't finish**
22 +
23 +To connect, you simply call `.createConnection()` like you would on mysqljs/mysql:
24 +```javascript
25 +var mysql = require('promise-mysql');
26 +
27 +mysql.createConnection({
28 + host: 'localhost',
29 + user: 'sauron',
30 + password: 'theonetruering',
31 + database: 'mordor'
32 +}).then(function(conn){
33 + // do stuff with conn
34 + conn.end();
35 +});
36 +```
37 +
38 +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:
39 +```javascript
40 +var mysql = require('promise-mysql');
41 +
42 +mysql.createConnection({
43 + host: 'localhost',
44 + user: 'sauron',
45 + password: 'theonetruering',
46 + database: 'mordor'
47 +}).then(function(conn){
48 + var result = conn.query('select `name` from hobbits');
49 + conn.end();
50 + return result;
51 +}).then(function(rows){
52 + // Logs out a list of hobbits
53 + console.log(rows);
54 +});
55 +```
56 +
57 +You can even chain the promises, using a return within the .then():
58 +```javascript
59 +var mysql = require('promise-mysql');
60 +var connection;
61 +
62 +mysql.createConnection({
63 + host: 'localhost',
64 + user: 'sauron',
65 + password: 'theonetruering',
66 + database: 'mordor'
67 +}).then(function(conn){
68 + connection = conn;
69 + return connection.query('select `id` from hobbits where `name`="frodo"');
70 +}).then(function(rows){
71 + // Query the items for a ring that Frodo owns.
72 + var result = connection.query('select * from items where `owner`="' + rows[0].id + '" and `name`="ring"');
73 + connection.end();
74 + return result;
75 +}).then(function(rows){
76 + // Logs out a ring that Frodo owns
77 + console.log(rows);
78 +});
79 +```
80 +
81 +You can catch errors using the .catch() method. You can still add .then() clauses, they'll just get skipped if there's an error
82 +```javascript
83 +var mysql = require('promise-mysql');
84 +var connection;
85 +
86 +mysql.createConnection({
87 + host: 'localhost',
88 + user: 'sauron',
89 + password: 'theonetruering',
90 + database: 'mordor'
91 +}).then(function(conn){
92 + connection = conn;
93 + return connection.query('select * from tablethatdoesnotexist');
94 +}).then(function(){
95 + var result = connection.query('select * from hobbits');
96 + connection.end();
97 + return result;
98 +}).catch(function(error){
99 + if (connection && connection.end) connection.end();
100 + //logs out the error
101 + console.log(error);
102 +});
103 +
104 +```
105 +
106 +### Pool
107 +
108 +Use pool directly:
109 +
110 +```javascript
111 +pool = mysql.createPool({
112 + host: 'localhost',
113 + user: 'sauron',
114 + password: 'theonetruering',
115 + database: 'mordor',
116 + connectionLimit: 10
117 +});
118 +
119 +pool.query('select `name` from hobbits').then(function(rows){
120 + // Logs out a list of hobbits
121 + console.log(rows);
122 +});
123 +
124 +```
125 +
126 +Get a connection from the pool:
127 +
128 +```javascript
129 +pool.getConnection().then(function(connection) {
130 + connection.query('select `name` from hobbits').then(...)
131 +}).catch(function(err) {
132 + done(err);
133 +});
134 +```
135 +
136 +#### Using/Disposer Pattern with Pool
137 +Example implementing a using/disposer pattern using Bluebird's built-in `using` and `disposer` functions.
138 +
139 +databaseConnection.js:
140 +```javascript
141 +var mysql = require('promise-mysql');
142 +
143 +pool = mysql.createPool({
144 + host: 'localhost',
145 + user: 'sauron',
146 + password: 'theonetruering',
147 + database: 'mordor',
148 + connectionLimit: 10
149 +});
150 +
151 +function getSqlConnection() {
152 + return pool.getConnection().disposer(function(connection) {
153 + pool.releaseConnection(connection);
154 + });
155 +}
156 +
157 +module.exports = getSqlConnection;
158 +```
159 +
160 +sqlQuery.js:
161 +```javascript
162 +var Promise = require("bluebird");
163 +var getSqlConnection = require('./databaseConnection');
164 +Promise.using(getSqlConnection(), function(connection) {
165 + return connection.query('select `name` from hobbits').then(function(rows) {
166 + return console.log(rows);
167 + }).catch(function(error) {
168 + console.log(error);
169 + });
170 +})
171 +```
172 +
173 +
174 +## Tests
175 +
176 +At the moment only simple basics tests are implemented using Mocha.
177 +To run the tests, you need to connect to a running MySQL server. A database or write permissions are not required.
178 +
179 +If you have docker, you can run a docker container bound to the mysql port with the command:
180 +```bash
181 +docker run -p 3306:3306 --name mysql_container -e MYSQL_ROOT_PASSWORD=password -d mysql
182 +```
183 +
184 +Start the test suite with
185 +
186 +```bash
187 +DB_HOST=localhost DB_USER=user DB_PWD=pwd npm test
188 +```
189 +
190 +## License
191 +
192 +The MIT License (MIT)
193 +
194 +Copyright (c) 2014 Luke Bonaccorsi
195 +
196 +Permission is hereby granted, free of charge, to any person obtaining a copy of
197 +this software and associated documentation files (the "Software"), to deal in
198 +the Software without restriction, including without limitation the rights to
199 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
200 +the Software, and to permit persons to whom the Software is furnished to do so,
201 +subject to the following conditions:
202 +
203 +The above copyright notice and this permission notice shall be included in all
204 +copies or substantial portions of the Software.
205 +
206 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
207 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
208 +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
209 +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
210 +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
211 +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1 +import * as mysql from 'mysql';
2 +import * as Bluebird from 'bluebird';
3 +
4 +export function createConnection(connectionUri: string | mysql.ConnectionConfig): Bluebird<Connection>;
5 +
6 +export function createPool(config: mysql.PoolConfig | string): Pool;
7 +
8 +export { Types, escape, escapeId, format, ConnectionOptions, ConnectionConfig, PoolConfig } from 'mysql';
9 +
10 +export interface QueryFunction {
11 + (query: mysql.Query | string | mysql.QueryOptions): Bluebird<any>;
12 +
13 + (options: string, values: any): Bluebird<any>;
14 +}
15 +
16 +export interface Connection {
17 + query: QueryFunction;
18 +
19 + beginTransaction(options?: mysql.QueryOptions): Bluebird<void>;
20 +
21 + commit(options?: mysql.QueryOptions): Bluebird<void>;
22 +
23 + rollback(options?: mysql.QueryOptions): Bluebird<void>;
24 +
25 + changeUser(options?: mysql.ConnectionOptions): Bluebird<void>;
26 +
27 + ping(options?: mysql.QueryOptions): Bluebird<void>;
28 +
29 + queryStream(sql: string, values: any): mysql.Query;
30 +
31 + statistics(options?: mysql.QueryOptions): Bluebird<void>;
32 +
33 + end(options?: mysql.QueryOptions): Bluebird<void>;
34 +
35 + destroy(): void;
36 +
37 + pause(): void;
38 +
39 + resume(): void;
40 +
41 + escape(value: any, stringifyObjects?: boolean, timeZone?: string): string;
42 +
43 + escapeId(value: string, forbidQualified?: boolean): string;
44 +
45 + format(sql: string, values: any[], stringifyObjects?: boolean, timeZone?: string): string;
46 +}
47 +
48 +export interface PoolConnection extends Connection {
49 + release(): any;
50 +
51 + destroy(): any;
52 +}
53 +
54 +export interface Pool {
55 + getConnection(): Bluebird<PoolConnection>;
56 +
57 + releaseConnection(connection: PoolConnection): void;
58 +
59 + query: QueryFunction;
60 +
61 + end(options?: mysql.QueryOptions): Bluebird<void>;
62 +
63 + release(options?: mysql.QueryOptions): Bluebird<void>;
64 +
65 + escape(value: any, stringifyObjects?: boolean, timeZone?: string): string;
66 +
67 + escapeId(value: string, forbidQualified?: boolean): string;
68 +
69 + on(ev: 'connection' | 'acquire' | 'release', callback: (connection: mysql.PoolConnection) => void): mysql.Pool;
70 +
71 + on(ev: 'error', callback: (err: mysql.MysqlError) => void): mysql.Pool;
72 +
73 + on(ev: 'enqueue', callback: (err?: mysql.MysqlError) => void): mysql.Pool;
74 +
75 + on(ev: string, callback: (...args: any[]) => void): mysql.Pool;
76 +}
1 +var Connection = require('./lib/connection.js');
2 +var Pool = require('./lib/pool.js');
3 +var mysql = require('mysql');
4 +
5 +exports.createConnection = function(config){
6 + return new Connection(config);
7 +}
8 +
9 +exports.createPool = function(config){
10 + return new Pool(config);
11 +}
12 +
13 +exports.Types = mysql.Types;
14 +exports.escape = mysql.escape;
15 +exports.escapeId = mysql.escapeId;
16 +exports.format = mysql.format;
1 +var Promise = require('bluebird'),
2 + mysql = require('mysql'),
3 + promiseCallback = require('./helper').promiseCallback;
4 +
5 +/**
6 +* Constructor
7 +* @param {object} config - The configuration object
8 +* @param {object} _connection - Mysql-Connection, only used internaly by the pool object
9 +*/
10 +var connection = function(config, _connection){
11 + var self = this,
12 + connect = function(resolve, reject) {
13 + if (_connection) {
14 + self.connection = _connection;
15 + resolve();
16 + } else {
17 + self.connection = mysql.createConnection(self.config);
18 + self.connection.connect(
19 + function(err){
20 + if (err) {
21 + self.connection.err = err;
22 + if (typeof reject === 'function') {
23 + return reject(err);
24 + } else {
25 + setTimeout(function(){
26 + connect();
27 + }, 2000);
28 + return;
29 + }
30 + } else {
31 + delete self.connection.err;
32 + if (typeof resolve === 'function') {
33 + return resolve();
34 + }
35 + }
36 + }
37 + );
38 +
39 + self.connection.on('error', function(err) {
40 + console.log('db error', err);
41 + self.connection.err = err;
42 + if(err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'ECONNRESET' || err.code === 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR') {
43 + connect();
44 + }
45 + });
46 + }
47 + };
48 +
49 + this.config = config;
50 +
51 + return new Promise(function(resolve, reject) {
52 + connect(
53 + function(){
54 + return resolve(self);
55 + },
56 + function(err){
57 + return reject(err);
58 + }
59 + );
60 + });
61 +}
62 +
63 +connection.prototype.query = function(sql, values) {
64 + return promiseCallback.apply(this.connection, ['query', arguments]);
65 +};
66 +
67 +connection.prototype.queryStream = function(sql, values) {
68 + return this.connection.query(sql, values);
69 +};
70 +
71 +connection.prototype.beginTransaction = function() {
72 + return promiseCallback.apply(this.connection, ['beginTransaction', arguments]);
73 +};
74 +
75 +connection.prototype.commit = function() {
76 + return promiseCallback.apply(this.connection, ['commit', arguments]);
77 +};
78 +
79 +connection.prototype.rollback = function() {
80 + return promiseCallback.apply(this.connection, ['rollback', arguments]);
81 +};
82 +
83 +connection.prototype.changeUser = function(data) {
84 + return promiseCallback.apply(this.connection, ['changeUser', arguments]);
85 +};
86 +
87 +connection.prototype.ping = function(data) {
88 + return promiseCallback.apply(this.connection, ['ping', arguments]);
89 +};
90 +
91 +connection.prototype.statistics = function(data) {
92 + return promiseCallback.apply(this.connection, ['statistics', arguments]);
93 +};
94 +
95 +connection.prototype.end = function(data) {
96 + return promiseCallback.apply(this.connection, ['end', arguments]);
97 +};
98 +
99 +connection.prototype.destroy = function() {
100 + this.connection.destroy();
101 +};
102 +
103 +connection.prototype.pause = function() {
104 + this.connection.pause();
105 +};
106 +
107 +connection.prototype.resume = function() {
108 + this.connection.resume();
109 +};
110 +
111 +connection.prototype.escape = function(value) {
112 + return this.connection.escape(value);
113 +};
114 +
115 +connection.prototype.escapeId = function(value) {
116 + return this.connection.escapeId(value);
117 +};
118 +
119 +connection.prototype.format = function(sql, values) {
120 + return this.connection.format(sql, values);
121 +};
122 +
123 +module.exports = connection;
1 +var Promise = require('bluebird');
2 +
3 +var promiseCallback = function(functionName, params) {
4 + var self = this;
5 + params = Array.prototype.slice.call(params, 0);
6 + return new Promise(function(resolve, reject) {
7 + params.push(function(err) {
8 + var args = Array.prototype.slice.call(arguments, 1);
9 + if (err) {
10 + return reject(err);
11 + }
12 +
13 + return resolve.apply(this, args);
14 + });
15 +
16 + self[functionName].apply(self, params);
17 + });
18 +};
19 +
20 +module.exports = {
21 + promiseCallback: promiseCallback,
22 +};
1 +var mysql = require('mysql'),
2 + PoolConnection = require('./poolConnection.js'),
3 + promiseCallback = require('./helper').promiseCallback;
4 +
5 +var pool = function(config) {
6 + this.pool = mysql.createPool(config);
7 +};
8 +
9 +pool.prototype.getConnection = function getConnection() {
10 + return promiseCallback.apply(this.pool, ['getConnection', arguments])
11 + .then(function(con) {
12 + return new PoolConnection(con);
13 + });
14 +};
15 +
16 +pool.prototype.releaseConnection = function releaseConnection(connection) {
17 + //Use the underlying connection from the mysql-module here:
18 + return this.pool.releaseConnection(connection.connection);
19 +};
20 +
21 +pool.prototype.query = function(sql, values) {
22 + return promiseCallback.apply(this.pool, ['query', arguments]);
23 +};
24 +
25 +pool.prototype.end = function(data) {
26 + return promiseCallback.apply(this.pool, ['end', arguments]);
27 +};
28 +
29 +pool.prototype.release = function(data) {
30 + return promiseCallback.apply(this.pool, ['release', arguments]);
31 +};
32 +
33 +pool.prototype.escape = function(value) {
34 + return this.pool.escape(value);
35 +};
36 +
37 +pool.prototype.escapeId = function(value) {
38 + return this.pool.escapeId(value);
39 +};
40 +
41 +pool.prototype.on = function(event, fn) {
42 + this.pool.on(event, fn);
43 +};
44 +
45 +module.exports = pool;
1 +var Connection = require('./connection.js'),
2 + inherits = require('util').inherits,
3 + promiseCallback = require('./helper').promiseCallback;
4 +
5 +var poolConnection = function(_connection) {
6 + this.connection = _connection;
7 +
8 + Connection.call(this, null, _connection)
9 +}
10 +
11 +inherits(poolConnection, Connection);
12 +
13 +poolConnection.prototype.release = function() {
14 + this.connection.release();
15 +};
16 +
17 +poolConnection.prototype.destroy = function() {
18 + this.connection.destroy();
19 +};
20 +
21 +module.exports = poolConnection;
1 +{
2 + "_from": "promise-mysql",
3 + "_id": "promise-mysql@3.3.1",
4 + "_inBundle": false,
5 + "_integrity": "sha512-PE+J6TtAqMJpdREvSphKvd+pn0IgGiLgxaDBb12oZNBR1VSxYSzknveuiSBmkptZC1ZDRwU+zBxBJeBgGFkCRA==",
6 + "_location": "/promise-mysql",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "tag",
10 + "registry": true,
11 + "raw": "promise-mysql",
12 + "name": "promise-mysql",
13 + "escapedName": "promise-mysql",
14 + "rawSpec": "",
15 + "saveSpec": null,
16 + "fetchSpec": "latest"
17 + },
18 + "_requiredBy": [
19 + "#USER",
20 + "/"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/promise-mysql/-/promise-mysql-3.3.1.tgz",
23 + "_shasum": "31ad1bbff065a9f2abb2627294502c98045d3d16",
24 + "_spec": "promise-mysql",
25 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project",
26 + "author": {
27 + "name": "Luke Bonaccorsi"
28 + },
29 + "bugs": {
30 + "url": "https://github.com/lukeb-uk/node-promise-mysql/issues"
31 + },
32 + "bundleDependencies": false,
33 + "dependencies": {
34 + "@types/bluebird": "^3.5.19",
35 + "@types/mysql": "^2.15.2",
36 + "bluebird": "^3.5.0",
37 + "mysql": "^2.14.1"
38 + },
39 + "deprecated": false,
40 + "description": "A bluebird wrapper for node-mysql",
41 + "devDependencies": {
42 + "chai": "^4.0.1",
43 + "mocha": "^5.0.0"
44 + },
45 + "homepage": "https://github.com/lukeb-uk/node-promise-mysql#readme",
46 + "keywords": [
47 + "promise",
48 + "performance",
49 + "promises",
50 + "promises-a",
51 + "promises-aplus",
52 + "async",
53 + "await",
54 + "deferred",
55 + "deferreds",
56 + "future",
57 + "flow control",
58 + "dsl",
59 + "fluent interface",
60 + "database",
61 + "mysql",
62 + "mysql-promise",
63 + "bluebird",
64 + "q"
65 + ],
66 + "license": "MIT",
67 + "main": "index.js",
68 + "name": "promise-mysql",
69 + "repository": {
70 + "type": "git",
71 + "url": "git+https://github.com/lukeb-uk/node-promise-mysql.git"
72 + },
73 + "scripts": {
74 + "test": "mocha --exit"
75 + },
76 + "version": "3.3.1"
77 +}
1 +sudo: false
2 +language: node_js
3 +before_install:
4 + - npm install -g npm@2
5 + - test $NPM_LEGACY && npm install -g npm@latest-3 || npm install npm -g
6 +notifications:
7 + email: false
8 +matrix:
9 + fast_finish: true
10 + include:
11 + - node_js: '0.8'
12 + env:
13 + - TASK=test
14 + - NPM_LEGACY=true
15 + - node_js: '0.10'
16 + env:
17 + - TASK=test
18 + - NPM_LEGACY=true
19 + - node_js: '0.11'
20 + env:
21 + - TASK=test
22 + - NPM_LEGACY=true
23 + - node_js: '0.12'
24 + env:
25 + - TASK=test
26 + - NPM_LEGACY=true
27 + - node_js: 1
28 + env:
29 + - TASK=test
30 + - NPM_LEGACY=true
31 + - node_js: 2
32 + env:
33 + - TASK=test
34 + - NPM_LEGACY=true
35 + - node_js: 3
36 + env:
37 + - TASK=test
38 + - NPM_LEGACY=true
39 + - node_js: 4
40 + env: TASK=test
41 + - node_js: 5
42 + env: TASK=test
43 + - node_js: 6
44 + env: TASK=test
45 + - node_js: 7
46 + env: TASK=test
47 + - node_js: 8
48 + env: TASK=test
49 + - node_js: 9
50 + env: TASK=test
51 +script: "npm run $TASK"
52 +env:
53 + global:
54 + - secure: rE2Vvo7vnjabYNULNyLFxOyt98BoJexDqsiOnfiD6kLYYsiQGfr/sbZkPMOFm9qfQG7pjqx+zZWZjGSswhTt+626C0t/njXqug7Yps4c3dFblzGfreQHp7wNX5TFsvrxd6dAowVasMp61sJcRnB2w8cUzoe3RAYUDHyiHktwqMc=
55 + - secure: g9YINaKAdMatsJ28G9jCGbSaguXCyxSTy+pBO6Ch0Cf57ZLOTka3HqDj8p3nV28LUIHZ3ut5WO43CeYKwt4AUtLpBS3a0dndHdY6D83uY6b2qh5hXlrcbeQTq2cvw2y95F7hm4D1kwrgZ7ViqaKggRcEupAL69YbJnxeUDKWEdI=
1 +# Developer's Certificate of Origin 1.1
2 +
3 +By making a contribution to this project, I certify that:
4 +
5 +* (a) The contribution was created in whole or in part by me and I
6 + have the right to submit it under the open source license
7 + indicated in the file; or
8 +
9 +* (b) The contribution is based upon previous work that, to the best
10 + of my knowledge, is covered under an appropriate open source
11 + license and I have the right under that license to submit that
12 + work with modifications, whether created in whole or in part
13 + by me, under the same open source license (unless I am
14 + permitted to submit under a different license), as indicated
15 + in the file; or
16 +
17 +* (c) The contribution was provided directly to me by some other
18 + person who certified (a), (b) or (c) and I have not modified
19 + it.
20 +
21 +* (d) I understand and agree that this project and the contribution
22 + are public and that a record of the contribution (including all
23 + personal information I submit with it, including my sign-off) is
24 + maintained indefinitely and may be redistributed consistent with
25 + this project or the open source license(s) involved.
26 +
27 +## Moderation Policy
28 +
29 +The [Node.js Moderation Policy] applies to this WG.
30 +
31 +## Code of Conduct
32 +
33 +The [Node.js Code of Conduct][] applies to this WG.
34 +
35 +[Node.js Code of Conduct]:
36 +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md
37 +[Node.js Moderation Policy]:
38 +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md
1 +### Streams Working Group
2 +
3 +The Node.js Streams is jointly governed by a Working Group
4 +(WG)
5 +that is responsible for high-level guidance of the project.
6 +
7 +The WG has final authority over this project including:
8 +
9 +* Technical direction
10 +* Project governance and process (including this policy)
11 +* Contribution policy
12 +* GitHub repository hosting
13 +* Conduct guidelines
14 +* Maintaining the list of additional Collaborators
15 +
16 +For the current list of WG members, see the project
17 +[README.md](./README.md#current-project-team-members).
18 +
19 +### Collaborators
20 +
21 +The readable-stream GitHub repository is
22 +maintained by the WG and additional Collaborators who are added by the
23 +WG on an ongoing basis.
24 +
25 +Individuals making significant and valuable contributions are made
26 +Collaborators and given commit-access to the project. These
27 +individuals are identified by the WG and their addition as
28 +Collaborators is discussed during the WG meeting.
29 +
30 +_Note:_ If you make a significant contribution and are not considered
31 +for commit-access log an issue or contact a WG member directly and it
32 +will be brought up in the next WG meeting.
33 +
34 +Modifications of the contents of the readable-stream repository are
35 +made on
36 +a collaborative basis. Anybody with a GitHub account may propose a
37 +modification via pull request and it will be considered by the project
38 +Collaborators. All pull requests must be reviewed and accepted by a
39 +Collaborator with sufficient expertise who is able to take full
40 +responsibility for the change. In the case of pull requests proposed
41 +by an existing Collaborator, an additional Collaborator is required
42 +for sign-off. Consensus should be sought if additional Collaborators
43 +participate and there is disagreement around a particular
44 +modification. See _Consensus Seeking Process_ below for further detail
45 +on the consensus model used for governance.
46 +
47 +Collaborators may opt to elevate significant or controversial
48 +modifications, or modifications that have not found consensus to the
49 +WG for discussion by assigning the ***WG-agenda*** tag to a pull
50 +request or issue. The WG should serve as the final arbiter where
51 +required.
52 +
53 +For the current list of Collaborators, see the project
54 +[README.md](./README.md#members).
55 +
56 +### WG Membership
57 +
58 +WG seats are not time-limited. There is no fixed size of the WG.
59 +However, the expected target is between 6 and 12, to ensure adequate
60 +coverage of important areas of expertise, balanced with the ability to
61 +make decisions efficiently.
62 +
63 +There is no specific set of requirements or qualifications for WG
64 +membership beyond these rules.
65 +
66 +The WG may add additional members to the WG by unanimous consensus.
67 +
68 +A WG member may be removed from the WG by voluntary resignation, or by
69 +unanimous consensus of all other WG members.
70 +
71 +Changes to WG membership should be posted in the agenda, and may be
72 +suggested as any other agenda item (see "WG Meetings" below).
73 +
74 +If an addition or removal is proposed during a meeting, and the full
75 +WG is not in attendance to participate, then the addition or removal
76 +is added to the agenda for the subsequent meeting. This is to ensure
77 +that all members are given the opportunity to participate in all
78 +membership decisions. If a WG member is unable to attend a meeting
79 +where a planned membership decision is being made, then their consent
80 +is assumed.
81 +
82 +No more than 1/3 of the WG members may be affiliated with the same
83 +employer. If removal or resignation of a WG member, or a change of
84 +employment by a WG member, creates a situation where more than 1/3 of
85 +the WG membership shares an employer, then the situation must be
86 +immediately remedied by the resignation or removal of one or more WG
87 +members affiliated with the over-represented employer(s).
88 +
89 +### WG Meetings
90 +
91 +The WG meets occasionally on a Google Hangout On Air. A designated moderator
92 +approved by the WG runs the meeting. Each meeting should be
93 +published to YouTube.
94 +
95 +Items are added to the WG agenda that are considered contentious or
96 +are modifications of governance, contribution policy, WG membership,
97 +or release process.
98 +
99 +The intention of the agenda is not to approve or review all patches;
100 +that should happen continuously on GitHub and be handled by the larger
101 +group of Collaborators.
102 +
103 +Any community member or contributor can ask that something be added to
104 +the next meeting's agenda by logging a GitHub Issue. Any Collaborator,
105 +WG member or the moderator can add the item to the agenda by adding
106 +the ***WG-agenda*** tag to the issue.
107 +
108 +Prior to each WG meeting the moderator will share the Agenda with
109 +members of the WG. WG members can add any items they like to the
110 +agenda at the beginning of each meeting. The moderator and the WG
111 +cannot veto or remove items.
112 +
113 +The WG may invite persons or representatives from certain projects to
114 +participate in a non-voting capacity.
115 +
116 +The moderator is responsible for summarizing the discussion of each
117 +agenda item and sends it as a pull request after the meeting.
118 +
119 +### Consensus Seeking Process
120 +
121 +The WG follows a
122 +[Consensus
123 +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making)
124 +decision-making model.
125 +
126 +When an agenda item has appeared to reach a consensus the moderator
127 +will ask "Does anyone object?" as a final call for dissent from the
128 +consensus.
129 +
130 +If an agenda item cannot reach a consensus a WG member can call for
131 +either a closing vote or a vote to table the issue to the next
132 +meeting. The call for a vote must be seconded by a majority of the WG
133 +or else the discussion will continue. Simple majority wins.
134 +
135 +Note that changes to WG membership require a majority consensus. See
136 +"WG Membership" above.
1 +Node.js is licensed for use as follows:
2 +
3 +"""
4 +Copyright Node.js contributors. All rights reserved.
5 +
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to
8 +deal in the Software without restriction, including without limitation the
9 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 +sell copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +
13 +The above copyright notice and this permission notice shall be included in
14 +all copies or substantial portions of the Software.
15 +
16 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 +IN THE SOFTWARE.
23 +"""
24 +
25 +This license applies to parts of Node.js originating from the
26 +https://github.com/joyent/node repository:
27 +
28 +"""
29 +Copyright Joyent, Inc. and other Node contributors. All rights reserved.
30 +Permission is hereby granted, free of charge, to any person obtaining a copy
31 +of this software and associated documentation files (the "Software"), to
32 +deal in the Software without restriction, including without limitation the
33 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
34 +sell copies of the Software, and to permit persons to whom the Software is
35 +furnished to do so, subject to the following conditions:
36 +
37 +The above copyright notice and this permission notice shall be included in
38 +all copies or substantial portions of the Software.
39 +
40 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
45 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
46 +IN THE SOFTWARE.
47 +"""
1 +# readable-stream
2 +
3 +***Node-core v8.11.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream)
4 +
5 +
6 +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)
7 +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/)
8 +
9 +
10 +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream)
11 +
12 +```bash
13 +npm install --save readable-stream
14 +```
15 +
16 +***Node-core streams for userland***
17 +
18 +This package is a mirror of the Streams2 and Streams3 implementations in
19 +Node-core.
20 +
21 +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.11.1/docs/api/stream.html).
22 +
23 +If you want to guarantee a stable streams base, regardless of what version of
24 +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).
25 +
26 +As of version 2.0.0 **readable-stream** uses semantic versioning.
27 +
28 +# Streams Working Group
29 +
30 +`readable-stream` is maintained by the Streams Working Group, which
31 +oversees the development and maintenance of the Streams API within
32 +Node.js. The responsibilities of the Streams Working Group include:
33 +
34 +* Addressing stream issues on the Node.js issue tracker.
35 +* Authoring and editing stream documentation within the Node.js project.
36 +* Reviewing changes to stream subclasses within the Node.js project.
37 +* Redirecting changes to streams from the Node.js project to this
38 + project.
39 +* Assisting in the implementation of stream providers within Node.js.
40 +* Recommending versions of `readable-stream` to be included in Node.js.
41 +* Messaging about the future of streams to give the community advance
42 + notice of changes.
43 +
44 +<a name="members"></a>
45 +## Team Members
46 +
47 +* **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) &lt;christopher.s.dickinson@gmail.com&gt;
48 + - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B
49 +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt;
50 + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
51 +* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;rod@vagg.org&gt;
52 + - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D
53 +* **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;newmansam@outlook.com&gt;
54 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt;
55 +* **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;d@domenic.me&gt;
56 +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt;
57 + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E
58 +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt;
1 +# streams WG Meeting 2015-01-30
2 +
3 +## Links
4 +
5 +* **Google Hangouts Video**: http://www.youtube.com/watch?v=I9nDOSGfwZg
6 +* **GitHub Issue**: https://github.com/iojs/readable-stream/issues/106
7 +* **Original Minutes Google Doc**: https://docs.google.com/document/d/17aTgLnjMXIrfjgNaTUnHQO7m3xgzHR2VXBTmi03Qii4/
8 +
9 +## Agenda
10 +
11 +Extracted from https://github.com/iojs/readable-stream/labels/wg-agenda prior to meeting.
12 +
13 +* adopt a charter [#105](https://github.com/iojs/readable-stream/issues/105)
14 +* release and versioning strategy [#101](https://github.com/iojs/readable-stream/issues/101)
15 +* simpler stream creation [#102](https://github.com/iojs/readable-stream/issues/102)
16 +* proposal: deprecate implicit flowing of streams [#99](https://github.com/iojs/readable-stream/issues/99)
17 +
18 +## Minutes
19 +
20 +### adopt a charter
21 +
22 +* group: +1's all around
23 +
24 +### What versioning scheme should be adopted?
25 +* group: +1’s 3.0.0
26 +* domenic+group: pulling in patches from other sources where appropriate
27 +* mikeal: version independently, suggesting versions for io.js
28 +* mikeal+domenic: work with TC to notify in advance of changes
29 +simpler stream creation
30 +
31 +### streamline creation of streams
32 +* sam: streamline creation of streams
33 +* domenic: nice simple solution posted
34 + but, we lose the opportunity to change the model
35 + may not be backwards incompatible (double check keys)
36 +
37 + **action item:** domenic will check
38 +
39 +### remove implicit flowing of streams on(‘data’)
40 +* add isFlowing / isPaused
41 +* mikeal: worrying that we’re documenting polyfill methods – confuses users
42 +* domenic: more reflective API is probably good, with warning labels for users
43 +* new section for mad scientists (reflective stream access)
44 +* calvin: name the “third state”
45 +* mikeal: maybe borrow the name from whatwg?
46 +* domenic: we’re missing the “third state”
47 +* consensus: kind of difficult to name the third state
48 +* mikeal: figure out differences in states / compat
49 +* mathias: always flow on data – eliminates third state
50 + * explore what it breaks
51 +
52 +**action items:**
53 +* ask isaac for ability to list packages by what public io.js APIs they use (esp. Stream)
54 +* ask rod/build for infrastructure
55 +* **chris**: explore the “flow on data” approach
56 +* add isPaused/isFlowing
57 +* add new docs section
58 +* move isPaused to that section
59 +
60 +
1 +module.exports = require('./lib/_stream_duplex.js');
1 +module.exports = require('./readable').Duplex
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// a duplex stream is just a stream that is both readable and writable.
23 +// Since JS doesn't have multiple prototypal inheritance, this class
24 +// prototypally inherits from Readable, and then parasitically from
25 +// Writable.
26 +
27 +'use strict';
28 +
29 +/*<replacement>*/
30 +
31 +var pna = require('process-nextick-args');
32 +/*</replacement>*/
33 +
34 +/*<replacement>*/
35 +var objectKeys = Object.keys || function (obj) {
36 + var keys = [];
37 + for (var key in obj) {
38 + keys.push(key);
39 + }return keys;
40 +};
41 +/*</replacement>*/
42 +
43 +module.exports = Duplex;
44 +
45 +/*<replacement>*/
46 +var util = require('core-util-is');
47 +util.inherits = require('inherits');
48 +/*</replacement>*/
49 +
50 +var Readable = require('./_stream_readable');
51 +var Writable = require('./_stream_writable');
52 +
53 +util.inherits(Duplex, Readable);
54 +
55 +{
56 + // avoid scope creep, the keys array can then be collected
57 + var keys = objectKeys(Writable.prototype);
58 + for (var v = 0; v < keys.length; v++) {
59 + var method = keys[v];
60 + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
61 + }
62 +}
63 +
64 +function Duplex(options) {
65 + if (!(this instanceof Duplex)) return new Duplex(options);
66 +
67 + Readable.call(this, options);
68 + Writable.call(this, options);
69 +
70 + if (options && options.readable === false) this.readable = false;
71 +
72 + if (options && options.writable === false) this.writable = false;
73 +
74 + this.allowHalfOpen = true;
75 + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
76 +
77 + this.once('end', onend);
78 +}
79 +
80 +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
81 + // making it explicit this property is not enumerable
82 + // because otherwise some prototype manipulation in
83 + // userland will fail
84 + enumerable: false,
85 + get: function () {
86 + return this._writableState.highWaterMark;
87 + }
88 +});
89 +
90 +// the no-half-open enforcer
91 +function onend() {
92 + // if we allow half-open state, or if the writable side ended,
93 + // then we're ok.
94 + if (this.allowHalfOpen || this._writableState.ended) return;
95 +
96 + // no more data can be written.
97 + // But allow more writes to happen in this tick.
98 + pna.nextTick(onEndNT, this);
99 +}
100 +
101 +function onEndNT(self) {
102 + self.end();
103 +}
104 +
105 +Object.defineProperty(Duplex.prototype, 'destroyed', {
106 + get: function () {
107 + if (this._readableState === undefined || this._writableState === undefined) {
108 + return false;
109 + }
110 + return this._readableState.destroyed && this._writableState.destroyed;
111 + },
112 + set: function (value) {
113 + // we ignore the value if the stream
114 + // has not been initialized yet
115 + if (this._readableState === undefined || this._writableState === undefined) {
116 + return;
117 + }
118 +
119 + // backward compatibility, the user is explicitly
120 + // managing destroyed
121 + this._readableState.destroyed = value;
122 + this._writableState.destroyed = value;
123 + }
124 +});
125 +
126 +Duplex.prototype._destroy = function (err, cb) {
127 + this.push(null);
128 + this.end();
129 +
130 + pna.nextTick(cb, err);
131 +};
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// a passthrough stream.
23 +// basically just the most minimal sort of Transform stream.
24 +// Every written chunk gets output as-is.
25 +
26 +'use strict';
27 +
28 +module.exports = PassThrough;
29 +
30 +var Transform = require('./_stream_transform');
31 +
32 +/*<replacement>*/
33 +var util = require('core-util-is');
34 +util.inherits = require('inherits');
35 +/*</replacement>*/
36 +
37 +util.inherits(PassThrough, Transform);
38 +
39 +function PassThrough(options) {
40 + if (!(this instanceof PassThrough)) return new PassThrough(options);
41 +
42 + Transform.call(this, options);
43 +}
44 +
45 +PassThrough.prototype._transform = function (chunk, encoding, cb) {
46 + cb(null, chunk);
47 +};
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +'use strict';
23 +
24 +/*<replacement>*/
25 +
26 +var pna = require('process-nextick-args');
27 +/*</replacement>*/
28 +
29 +module.exports = Readable;
30 +
31 +/*<replacement>*/
32 +var isArray = require('isarray');
33 +/*</replacement>*/
34 +
35 +/*<replacement>*/
36 +var Duplex;
37 +/*</replacement>*/
38 +
39 +Readable.ReadableState = ReadableState;
40 +
41 +/*<replacement>*/
42 +var EE = require('events').EventEmitter;
43 +
44 +var EElistenerCount = function (emitter, type) {
45 + return emitter.listeners(type).length;
46 +};
47 +/*</replacement>*/
48 +
49 +/*<replacement>*/
50 +var Stream = require('./internal/streams/stream');
51 +/*</replacement>*/
52 +
53 +/*<replacement>*/
54 +
55 +var Buffer = require('safe-buffer').Buffer;
56 +var OurUint8Array = global.Uint8Array || function () {};
57 +function _uint8ArrayToBuffer(chunk) {
58 + return Buffer.from(chunk);
59 +}
60 +function _isUint8Array(obj) {
61 + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
62 +}
63 +
64 +/*</replacement>*/
65 +
66 +/*<replacement>*/
67 +var util = require('core-util-is');
68 +util.inherits = require('inherits');
69 +/*</replacement>*/
70 +
71 +/*<replacement>*/
72 +var debugUtil = require('util');
73 +var debug = void 0;
74 +if (debugUtil && debugUtil.debuglog) {
75 + debug = debugUtil.debuglog('stream');
76 +} else {
77 + debug = function () {};
78 +}
79 +/*</replacement>*/
80 +
81 +var BufferList = require('./internal/streams/BufferList');
82 +var destroyImpl = require('./internal/streams/destroy');
83 +var StringDecoder;
84 +
85 +util.inherits(Readable, Stream);
86 +
87 +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
88 +
89 +function prependListener(emitter, event, fn) {
90 + // Sadly this is not cacheable as some libraries bundle their own
91 + // event emitter implementation with them.
92 + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
93 +
94 + // This is a hack to make sure that our error handler is attached before any
95 + // userland ones. NEVER DO THIS. This is here only because this code needs
96 + // to continue to work with older versions of Node.js that do not include
97 + // the prependListener() method. The goal is to eventually remove this hack.
98 + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
99 +}
100 +
101 +function ReadableState(options, stream) {
102 + Duplex = Duplex || require('./_stream_duplex');
103 +
104 + options = options || {};
105 +
106 + // Duplex streams are both readable and writable, but share
107 + // the same options object.
108 + // However, some cases require setting options to different
109 + // values for the readable and the writable sides of the duplex stream.
110 + // These options can be provided separately as readableXXX and writableXXX.
111 + var isDuplex = stream instanceof Duplex;
112 +
113 + // object stream flag. Used to make read(n) ignore n and to
114 + // make all the buffer merging and length checks go away
115 + this.objectMode = !!options.objectMode;
116 +
117 + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
118 +
119 + // the point at which it stops calling _read() to fill the buffer
120 + // Note: 0 is a valid value, means "don't call _read preemptively ever"
121 + var hwm = options.highWaterMark;
122 + var readableHwm = options.readableHighWaterMark;
123 + var defaultHwm = this.objectMode ? 16 : 16 * 1024;
124 +
125 + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
126 +
127 + // cast to ints.
128 + this.highWaterMark = Math.floor(this.highWaterMark);
129 +
130 + // A linked list is used to store data chunks instead of an array because the
131 + // linked list can remove elements from the beginning faster than
132 + // array.shift()
133 + this.buffer = new BufferList();
134 + this.length = 0;
135 + this.pipes = null;
136 + this.pipesCount = 0;
137 + this.flowing = null;
138 + this.ended = false;
139 + this.endEmitted = false;
140 + this.reading = false;
141 +
142 + // a flag to be able to tell if the event 'readable'/'data' is emitted
143 + // immediately, or on a later tick. We set this to true at first, because
144 + // any actions that shouldn't happen until "later" should generally also
145 + // not happen before the first read call.
146 + this.sync = true;
147 +
148 + // whenever we return null, then we set a flag to say
149 + // that we're awaiting a 'readable' event emission.
150 + this.needReadable = false;
151 + this.emittedReadable = false;
152 + this.readableListening = false;
153 + this.resumeScheduled = false;
154 +
155 + // has it been destroyed
156 + this.destroyed = false;
157 +
158 + // Crypto is kind of old and crusty. Historically, its default string
159 + // encoding is 'binary' so we have to make this configurable.
160 + // Everything else in the universe uses 'utf8', though.
161 + this.defaultEncoding = options.defaultEncoding || 'utf8';
162 +
163 + // the number of writers that are awaiting a drain event in .pipe()s
164 + this.awaitDrain = 0;
165 +
166 + // if true, a maybeReadMore has been scheduled
167 + this.readingMore = false;
168 +
169 + this.decoder = null;
170 + this.encoding = null;
171 + if (options.encoding) {
172 + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
173 + this.decoder = new StringDecoder(options.encoding);
174 + this.encoding = options.encoding;
175 + }
176 +}
177 +
178 +function Readable(options) {
179 + Duplex = Duplex || require('./_stream_duplex');
180 +
181 + if (!(this instanceof Readable)) return new Readable(options);
182 +
183 + this._readableState = new ReadableState(options, this);
184 +
185 + // legacy
186 + this.readable = true;
187 +
188 + if (options) {
189 + if (typeof options.read === 'function') this._read = options.read;
190 +
191 + if (typeof options.destroy === 'function') this._destroy = options.destroy;
192 + }
193 +
194 + Stream.call(this);
195 +}
196 +
197 +Object.defineProperty(Readable.prototype, 'destroyed', {
198 + get: function () {
199 + if (this._readableState === undefined) {
200 + return false;
201 + }
202 + return this._readableState.destroyed;
203 + },
204 + set: function (value) {
205 + // we ignore the value if the stream
206 + // has not been initialized yet
207 + if (!this._readableState) {
208 + return;
209 + }
210 +
211 + // backward compatibility, the user is explicitly
212 + // managing destroyed
213 + this._readableState.destroyed = value;
214 + }
215 +});
216 +
217 +Readable.prototype.destroy = destroyImpl.destroy;
218 +Readable.prototype._undestroy = destroyImpl.undestroy;
219 +Readable.prototype._destroy = function (err, cb) {
220 + this.push(null);
221 + cb(err);
222 +};
223 +
224 +// Manually shove something into the read() buffer.
225 +// This returns true if the highWaterMark has not been hit yet,
226 +// similar to how Writable.write() returns true if you should
227 +// write() some more.
228 +Readable.prototype.push = function (chunk, encoding) {
229 + var state = this._readableState;
230 + var skipChunkCheck;
231 +
232 + if (!state.objectMode) {
233 + if (typeof chunk === 'string') {
234 + encoding = encoding || state.defaultEncoding;
235 + if (encoding !== state.encoding) {
236 + chunk = Buffer.from(chunk, encoding);
237 + encoding = '';
238 + }
239 + skipChunkCheck = true;
240 + }
241 + } else {
242 + skipChunkCheck = true;
243 + }
244 +
245 + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
246 +};
247 +
248 +// Unshift should *always* be something directly out of read()
249 +Readable.prototype.unshift = function (chunk) {
250 + return readableAddChunk(this, chunk, null, true, false);
251 +};
252 +
253 +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
254 + var state = stream._readableState;
255 + if (chunk === null) {
256 + state.reading = false;
257 + onEofChunk(stream, state);
258 + } else {
259 + var er;
260 + if (!skipChunkCheck) er = chunkInvalid(state, chunk);
261 + if (er) {
262 + stream.emit('error', er);
263 + } else if (state.objectMode || chunk && chunk.length > 0) {
264 + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
265 + chunk = _uint8ArrayToBuffer(chunk);
266 + }
267 +
268 + if (addToFront) {
269 + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
270 + } else if (state.ended) {
271 + stream.emit('error', new Error('stream.push() after EOF'));
272 + } else {
273 + state.reading = false;
274 + if (state.decoder && !encoding) {
275 + chunk = state.decoder.write(chunk);
276 + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
277 + } else {
278 + addChunk(stream, state, chunk, false);
279 + }
280 + }
281 + } else if (!addToFront) {
282 + state.reading = false;
283 + }
284 + }
285 +
286 + return needMoreData(state);
287 +}
288 +
289 +function addChunk(stream, state, chunk, addToFront) {
290 + if (state.flowing && state.length === 0 && !state.sync) {
291 + stream.emit('data', chunk);
292 + stream.read(0);
293 + } else {
294 + // update the buffer info.
295 + state.length += state.objectMode ? 1 : chunk.length;
296 + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
297 +
298 + if (state.needReadable) emitReadable(stream);
299 + }
300 + maybeReadMore(stream, state);
301 +}
302 +
303 +function chunkInvalid(state, chunk) {
304 + var er;
305 + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
306 + er = new TypeError('Invalid non-string/buffer chunk');
307 + }
308 + return er;
309 +}
310 +
311 +// if it's past the high water mark, we can push in some more.
312 +// Also, if we have no data yet, we can stand some
313 +// more bytes. This is to work around cases where hwm=0,
314 +// such as the repl. Also, if the push() triggered a
315 +// readable event, and the user called read(largeNumber) such that
316 +// needReadable was set, then we ought to push more, so that another
317 +// 'readable' event will be triggered.
318 +function needMoreData(state) {
319 + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
320 +}
321 +
322 +Readable.prototype.isPaused = function () {
323 + return this._readableState.flowing === false;
324 +};
325 +
326 +// backwards compatibility.
327 +Readable.prototype.setEncoding = function (enc) {
328 + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
329 + this._readableState.decoder = new StringDecoder(enc);
330 + this._readableState.encoding = enc;
331 + return this;
332 +};
333 +
334 +// Don't raise the hwm > 8MB
335 +var MAX_HWM = 0x800000;
336 +function computeNewHighWaterMark(n) {
337 + if (n >= MAX_HWM) {
338 + n = MAX_HWM;
339 + } else {
340 + // Get the next highest power of 2 to prevent increasing hwm excessively in
341 + // tiny amounts
342 + n--;
343 + n |= n >>> 1;
344 + n |= n >>> 2;
345 + n |= n >>> 4;
346 + n |= n >>> 8;
347 + n |= n >>> 16;
348 + n++;
349 + }
350 + return n;
351 +}
352 +
353 +// This function is designed to be inlinable, so please take care when making
354 +// changes to the function body.
355 +function howMuchToRead(n, state) {
356 + if (n <= 0 || state.length === 0 && state.ended) return 0;
357 + if (state.objectMode) return 1;
358 + if (n !== n) {
359 + // Only flow one buffer at a time
360 + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
361 + }
362 + // If we're asking for more than the current hwm, then raise the hwm.
363 + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
364 + if (n <= state.length) return n;
365 + // Don't have enough
366 + if (!state.ended) {
367 + state.needReadable = true;
368 + return 0;
369 + }
370 + return state.length;
371 +}
372 +
373 +// you can override either this method, or the async _read(n) below.
374 +Readable.prototype.read = function (n) {
375 + debug('read', n);
376 + n = parseInt(n, 10);
377 + var state = this._readableState;
378 + var nOrig = n;
379 +
380 + if (n !== 0) state.emittedReadable = false;
381 +
382 + // if we're doing read(0) to trigger a readable event, but we
383 + // already have a bunch of data in the buffer, then just trigger
384 + // the 'readable' event and move on.
385 + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
386 + debug('read: emitReadable', state.length, state.ended);
387 + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
388 + return null;
389 + }
390 +
391 + n = howMuchToRead(n, state);
392 +
393 + // if we've ended, and we're now clear, then finish it up.
394 + if (n === 0 && state.ended) {
395 + if (state.length === 0) endReadable(this);
396 + return null;
397 + }
398 +
399 + // All the actual chunk generation logic needs to be
400 + // *below* the call to _read. The reason is that in certain
401 + // synthetic stream cases, such as passthrough streams, _read
402 + // may be a completely synchronous operation which may change
403 + // the state of the read buffer, providing enough data when
404 + // before there was *not* enough.
405 + //
406 + // So, the steps are:
407 + // 1. Figure out what the state of things will be after we do
408 + // a read from the buffer.
409 + //
410 + // 2. If that resulting state will trigger a _read, then call _read.
411 + // Note that this may be asynchronous, or synchronous. Yes, it is
412 + // deeply ugly to write APIs this way, but that still doesn't mean
413 + // that the Readable class should behave improperly, as streams are
414 + // designed to be sync/async agnostic.
415 + // Take note if the _read call is sync or async (ie, if the read call
416 + // has returned yet), so that we know whether or not it's safe to emit
417 + // 'readable' etc.
418 + //
419 + // 3. Actually pull the requested chunks out of the buffer and return.
420 +
421 + // if we need a readable event, then we need to do some reading.
422 + var doRead = state.needReadable;
423 + debug('need readable', doRead);
424 +
425 + // if we currently have less than the highWaterMark, then also read some
426 + if (state.length === 0 || state.length - n < state.highWaterMark) {
427 + doRead = true;
428 + debug('length less than watermark', doRead);
429 + }
430 +
431 + // however, if we've ended, then there's no point, and if we're already
432 + // reading, then it's unnecessary.
433 + if (state.ended || state.reading) {
434 + doRead = false;
435 + debug('reading or ended', doRead);
436 + } else if (doRead) {
437 + debug('do read');
438 + state.reading = true;
439 + state.sync = true;
440 + // if the length is currently zero, then we *need* a readable event.
441 + if (state.length === 0) state.needReadable = true;
442 + // call internal read method
443 + this._read(state.highWaterMark);
444 + state.sync = false;
445 + // If _read pushed data synchronously, then `reading` will be false,
446 + // and we need to re-evaluate how much data we can return to the user.
447 + if (!state.reading) n = howMuchToRead(nOrig, state);
448 + }
449 +
450 + var ret;
451 + if (n > 0) ret = fromList(n, state);else ret = null;
452 +
453 + if (ret === null) {
454 + state.needReadable = true;
455 + n = 0;
456 + } else {
457 + state.length -= n;
458 + }
459 +
460 + if (state.length === 0) {
461 + // If we have nothing in the buffer, then we want to know
462 + // as soon as we *do* get something into the buffer.
463 + if (!state.ended) state.needReadable = true;
464 +
465 + // If we tried to read() past the EOF, then emit end on the next tick.
466 + if (nOrig !== n && state.ended) endReadable(this);
467 + }
468 +
469 + if (ret !== null) this.emit('data', ret);
470 +
471 + return ret;
472 +};
473 +
474 +function onEofChunk(stream, state) {
475 + if (state.ended) return;
476 + if (state.decoder) {
477 + var chunk = state.decoder.end();
478 + if (chunk && chunk.length) {
479 + state.buffer.push(chunk);
480 + state.length += state.objectMode ? 1 : chunk.length;
481 + }
482 + }
483 + state.ended = true;
484 +
485 + // emit 'readable' now to make sure it gets picked up.
486 + emitReadable(stream);
487 +}
488 +
489 +// Don't emit readable right away in sync mode, because this can trigger
490 +// another read() call => stack overflow. This way, it might trigger
491 +// a nextTick recursion warning, but that's not so bad.
492 +function emitReadable(stream) {
493 + var state = stream._readableState;
494 + state.needReadable = false;
495 + if (!state.emittedReadable) {
496 + debug('emitReadable', state.flowing);
497 + state.emittedReadable = true;
498 + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
499 + }
500 +}
501 +
502 +function emitReadable_(stream) {
503 + debug('emit readable');
504 + stream.emit('readable');
505 + flow(stream);
506 +}
507 +
508 +// at this point, the user has presumably seen the 'readable' event,
509 +// and called read() to consume some data. that may have triggered
510 +// in turn another _read(n) call, in which case reading = true if
511 +// it's in progress.
512 +// However, if we're not ended, or reading, and the length < hwm,
513 +// then go ahead and try to read some more preemptively.
514 +function maybeReadMore(stream, state) {
515 + if (!state.readingMore) {
516 + state.readingMore = true;
517 + pna.nextTick(maybeReadMore_, stream, state);
518 + }
519 +}
520 +
521 +function maybeReadMore_(stream, state) {
522 + var len = state.length;
523 + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
524 + debug('maybeReadMore read 0');
525 + stream.read(0);
526 + if (len === state.length)
527 + // didn't get any data, stop spinning.
528 + break;else len = state.length;
529 + }
530 + state.readingMore = false;
531 +}
532 +
533 +// abstract method. to be overridden in specific implementation classes.
534 +// call cb(er, data) where data is <= n in length.
535 +// for virtual (non-string, non-buffer) streams, "length" is somewhat
536 +// arbitrary, and perhaps not very meaningful.
537 +Readable.prototype._read = function (n) {
538 + this.emit('error', new Error('_read() is not implemented'));
539 +};
540 +
541 +Readable.prototype.pipe = function (dest, pipeOpts) {
542 + var src = this;
543 + var state = this._readableState;
544 +
545 + switch (state.pipesCount) {
546 + case 0:
547 + state.pipes = dest;
548 + break;
549 + case 1:
550 + state.pipes = [state.pipes, dest];
551 + break;
552 + default:
553 + state.pipes.push(dest);
554 + break;
555 + }
556 + state.pipesCount += 1;
557 + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
558 +
559 + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
560 +
561 + var endFn = doEnd ? onend : unpipe;
562 + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
563 +
564 + dest.on('unpipe', onunpipe);
565 + function onunpipe(readable, unpipeInfo) {
566 + debug('onunpipe');
567 + if (readable === src) {
568 + if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
569 + unpipeInfo.hasUnpiped = true;
570 + cleanup();
571 + }
572 + }
573 + }
574 +
575 + function onend() {
576 + debug('onend');
577 + dest.end();
578 + }
579 +
580 + // when the dest drains, it reduces the awaitDrain counter
581 + // on the source. This would be more elegant with a .once()
582 + // handler in flow(), but adding and removing repeatedly is
583 + // too slow.
584 + var ondrain = pipeOnDrain(src);
585 + dest.on('drain', ondrain);
586 +
587 + var cleanedUp = false;
588 + function cleanup() {
589 + debug('cleanup');
590 + // cleanup event handlers once the pipe is broken
591 + dest.removeListener('close', onclose);
592 + dest.removeListener('finish', onfinish);
593 + dest.removeListener('drain', ondrain);
594 + dest.removeListener('error', onerror);
595 + dest.removeListener('unpipe', onunpipe);
596 + src.removeListener('end', onend);
597 + src.removeListener('end', unpipe);
598 + src.removeListener('data', ondata);
599 +
600 + cleanedUp = true;
601 +
602 + // if the reader is waiting for a drain event from this
603 + // specific writer, then it would cause it to never start
604 + // flowing again.
605 + // So, if this is awaiting a drain, then we just call it now.
606 + // If we don't know, then assume that we are waiting for one.
607 + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
608 + }
609 +
610 + // If the user pushes more data while we're writing to dest then we'll end up
611 + // in ondata again. However, we only want to increase awaitDrain once because
612 + // dest will only emit one 'drain' event for the multiple writes.
613 + // => Introduce a guard on increasing awaitDrain.
614 + var increasedAwaitDrain = false;
615 + src.on('data', ondata);
616 + function ondata(chunk) {
617 + debug('ondata');
618 + increasedAwaitDrain = false;
619 + var ret = dest.write(chunk);
620 + if (false === ret && !increasedAwaitDrain) {
621 + // If the user unpiped during `dest.write()`, it is possible
622 + // to get stuck in a permanently paused state if that write
623 + // also returned false.
624 + // => Check whether `dest` is still a piping destination.
625 + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
626 + debug('false write response, pause', src._readableState.awaitDrain);
627 + src._readableState.awaitDrain++;
628 + increasedAwaitDrain = true;
629 + }
630 + src.pause();
631 + }
632 + }
633 +
634 + // if the dest has an error, then stop piping into it.
635 + // however, don't suppress the throwing behavior for this.
636 + function onerror(er) {
637 + debug('onerror', er);
638 + unpipe();
639 + dest.removeListener('error', onerror);
640 + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
641 + }
642 +
643 + // Make sure our error handler is attached before userland ones.
644 + prependListener(dest, 'error', onerror);
645 +
646 + // Both close and finish should trigger unpipe, but only once.
647 + function onclose() {
648 + dest.removeListener('finish', onfinish);
649 + unpipe();
650 + }
651 + dest.once('close', onclose);
652 + function onfinish() {
653 + debug('onfinish');
654 + dest.removeListener('close', onclose);
655 + unpipe();
656 + }
657 + dest.once('finish', onfinish);
658 +
659 + function unpipe() {
660 + debug('unpipe');
661 + src.unpipe(dest);
662 + }
663 +
664 + // tell the dest that it's being piped to
665 + dest.emit('pipe', src);
666 +
667 + // start the flow if it hasn't been started already.
668 + if (!state.flowing) {
669 + debug('pipe resume');
670 + src.resume();
671 + }
672 +
673 + return dest;
674 +};
675 +
676 +function pipeOnDrain(src) {
677 + return function () {
678 + var state = src._readableState;
679 + debug('pipeOnDrain', state.awaitDrain);
680 + if (state.awaitDrain) state.awaitDrain--;
681 + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
682 + state.flowing = true;
683 + flow(src);
684 + }
685 + };
686 +}
687 +
688 +Readable.prototype.unpipe = function (dest) {
689 + var state = this._readableState;
690 + var unpipeInfo = { hasUnpiped: false };
691 +
692 + // if we're not piping anywhere, then do nothing.
693 + if (state.pipesCount === 0) return this;
694 +
695 + // just one destination. most common case.
696 + if (state.pipesCount === 1) {
697 + // passed in one, but it's not the right one.
698 + if (dest && dest !== state.pipes) return this;
699 +
700 + if (!dest) dest = state.pipes;
701 +
702 + // got a match.
703 + state.pipes = null;
704 + state.pipesCount = 0;
705 + state.flowing = false;
706 + if (dest) dest.emit('unpipe', this, unpipeInfo);
707 + return this;
708 + }
709 +
710 + // slow case. multiple pipe destinations.
711 +
712 + if (!dest) {
713 + // remove all.
714 + var dests = state.pipes;
715 + var len = state.pipesCount;
716 + state.pipes = null;
717 + state.pipesCount = 0;
718 + state.flowing = false;
719 +
720 + for (var i = 0; i < len; i++) {
721 + dests[i].emit('unpipe', this, unpipeInfo);
722 + }return this;
723 + }
724 +
725 + // try to find the right one.
726 + var index = indexOf(state.pipes, dest);
727 + if (index === -1) return this;
728 +
729 + state.pipes.splice(index, 1);
730 + state.pipesCount -= 1;
731 + if (state.pipesCount === 1) state.pipes = state.pipes[0];
732 +
733 + dest.emit('unpipe', this, unpipeInfo);
734 +
735 + return this;
736 +};
737 +
738 +// set up data events if they are asked for
739 +// Ensure readable listeners eventually get something
740 +Readable.prototype.on = function (ev, fn) {
741 + var res = Stream.prototype.on.call(this, ev, fn);
742 +
743 + if (ev === 'data') {
744 + // Start flowing on next tick if stream isn't explicitly paused
745 + if (this._readableState.flowing !== false) this.resume();
746 + } else if (ev === 'readable') {
747 + var state = this._readableState;
748 + if (!state.endEmitted && !state.readableListening) {
749 + state.readableListening = state.needReadable = true;
750 + state.emittedReadable = false;
751 + if (!state.reading) {
752 + pna.nextTick(nReadingNextTick, this);
753 + } else if (state.length) {
754 + emitReadable(this);
755 + }
756 + }
757 + }
758 +
759 + return res;
760 +};
761 +Readable.prototype.addListener = Readable.prototype.on;
762 +
763 +function nReadingNextTick(self) {
764 + debug('readable nexttick read 0');
765 + self.read(0);
766 +}
767 +
768 +// pause() and resume() are remnants of the legacy readable stream API
769 +// If the user uses them, then switch into old mode.
770 +Readable.prototype.resume = function () {
771 + var state = this._readableState;
772 + if (!state.flowing) {
773 + debug('resume');
774 + state.flowing = true;
775 + resume(this, state);
776 + }
777 + return this;
778 +};
779 +
780 +function resume(stream, state) {
781 + if (!state.resumeScheduled) {
782 + state.resumeScheduled = true;
783 + pna.nextTick(resume_, stream, state);
784 + }
785 +}
786 +
787 +function resume_(stream, state) {
788 + if (!state.reading) {
789 + debug('resume read 0');
790 + stream.read(0);
791 + }
792 +
793 + state.resumeScheduled = false;
794 + state.awaitDrain = 0;
795 + stream.emit('resume');
796 + flow(stream);
797 + if (state.flowing && !state.reading) stream.read(0);
798 +}
799 +
800 +Readable.prototype.pause = function () {
801 + debug('call pause flowing=%j', this._readableState.flowing);
802 + if (false !== this._readableState.flowing) {
803 + debug('pause');
804 + this._readableState.flowing = false;
805 + this.emit('pause');
806 + }
807 + return this;
808 +};
809 +
810 +function flow(stream) {
811 + var state = stream._readableState;
812 + debug('flow', state.flowing);
813 + while (state.flowing && stream.read() !== null) {}
814 +}
815 +
816 +// wrap an old-style stream as the async data source.
817 +// This is *not* part of the readable stream interface.
818 +// It is an ugly unfortunate mess of history.
819 +Readable.prototype.wrap = function (stream) {
820 + var _this = this;
821 +
822 + var state = this._readableState;
823 + var paused = false;
824 +
825 + stream.on('end', function () {
826 + debug('wrapped end');
827 + if (state.decoder && !state.ended) {
828 + var chunk = state.decoder.end();
829 + if (chunk && chunk.length) _this.push(chunk);
830 + }
831 +
832 + _this.push(null);
833 + });
834 +
835 + stream.on('data', function (chunk) {
836 + debug('wrapped data');
837 + if (state.decoder) chunk = state.decoder.write(chunk);
838 +
839 + // don't skip over falsy values in objectMode
840 + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
841 +
842 + var ret = _this.push(chunk);
843 + if (!ret) {
844 + paused = true;
845 + stream.pause();
846 + }
847 + });
848 +
849 + // proxy all the other methods.
850 + // important when wrapping filters and duplexes.
851 + for (var i in stream) {
852 + if (this[i] === undefined && typeof stream[i] === 'function') {
853 + this[i] = function (method) {
854 + return function () {
855 + return stream[method].apply(stream, arguments);
856 + };
857 + }(i);
858 + }
859 + }
860 +
861 + // proxy certain important events.
862 + for (var n = 0; n < kProxyEvents.length; n++) {
863 + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
864 + }
865 +
866 + // when we try to consume some more bytes, simply unpause the
867 + // underlying stream.
868 + this._read = function (n) {
869 + debug('wrapped _read', n);
870 + if (paused) {
871 + paused = false;
872 + stream.resume();
873 + }
874 + };
875 +
876 + return this;
877 +};
878 +
879 +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
880 + // making it explicit this property is not enumerable
881 + // because otherwise some prototype manipulation in
882 + // userland will fail
883 + enumerable: false,
884 + get: function () {
885 + return this._readableState.highWaterMark;
886 + }
887 +});
888 +
889 +// exposed for testing purposes only.
890 +Readable._fromList = fromList;
891 +
892 +// Pluck off n bytes from an array of buffers.
893 +// Length is the combined lengths of all the buffers in the list.
894 +// This function is designed to be inlinable, so please take care when making
895 +// changes to the function body.
896 +function fromList(n, state) {
897 + // nothing buffered
898 + if (state.length === 0) return null;
899 +
900 + var ret;
901 + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
902 + // read it all, truncate the list
903 + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
904 + state.buffer.clear();
905 + } else {
906 + // read part of list
907 + ret = fromListPartial(n, state.buffer, state.decoder);
908 + }
909 +
910 + return ret;
911 +}
912 +
913 +// Extracts only enough buffered data to satisfy the amount requested.
914 +// This function is designed to be inlinable, so please take care when making
915 +// changes to the function body.
916 +function fromListPartial(n, list, hasStrings) {
917 + var ret;
918 + if (n < list.head.data.length) {
919 + // slice is the same for buffers and strings
920 + ret = list.head.data.slice(0, n);
921 + list.head.data = list.head.data.slice(n);
922 + } else if (n === list.head.data.length) {
923 + // first chunk is a perfect match
924 + ret = list.shift();
925 + } else {
926 + // result spans more than one buffer
927 + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
928 + }
929 + return ret;
930 +}
931 +
932 +// Copies a specified amount of characters from the list of buffered data
933 +// chunks.
934 +// This function is designed to be inlinable, so please take care when making
935 +// changes to the function body.
936 +function copyFromBufferString(n, list) {
937 + var p = list.head;
938 + var c = 1;
939 + var ret = p.data;
940 + n -= ret.length;
941 + while (p = p.next) {
942 + var str = p.data;
943 + var nb = n > str.length ? str.length : n;
944 + if (nb === str.length) ret += str;else ret += str.slice(0, n);
945 + n -= nb;
946 + if (n === 0) {
947 + if (nb === str.length) {
948 + ++c;
949 + if (p.next) list.head = p.next;else list.head = list.tail = null;
950 + } else {
951 + list.head = p;
952 + p.data = str.slice(nb);
953 + }
954 + break;
955 + }
956 + ++c;
957 + }
958 + list.length -= c;
959 + return ret;
960 +}
961 +
962 +// Copies a specified amount of bytes from the list of buffered data chunks.
963 +// This function is designed to be inlinable, so please take care when making
964 +// changes to the function body.
965 +function copyFromBuffer(n, list) {
966 + var ret = Buffer.allocUnsafe(n);
967 + var p = list.head;
968 + var c = 1;
969 + p.data.copy(ret);
970 + n -= p.data.length;
971 + while (p = p.next) {
972 + var buf = p.data;
973 + var nb = n > buf.length ? buf.length : n;
974 + buf.copy(ret, ret.length - n, 0, nb);
975 + n -= nb;
976 + if (n === 0) {
977 + if (nb === buf.length) {
978 + ++c;
979 + if (p.next) list.head = p.next;else list.head = list.tail = null;
980 + } else {
981 + list.head = p;
982 + p.data = buf.slice(nb);
983 + }
984 + break;
985 + }
986 + ++c;
987 + }
988 + list.length -= c;
989 + return ret;
990 +}
991 +
992 +function endReadable(stream) {
993 + var state = stream._readableState;
994 +
995 + // If we get here before consuming all the bytes, then that is a
996 + // bug in node. Should never happen.
997 + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
998 +
999 + if (!state.endEmitted) {
1000 + state.ended = true;
1001 + pna.nextTick(endReadableNT, state, stream);
1002 + }
1003 +}
1004 +
1005 +function endReadableNT(state, stream) {
1006 + // Check that we didn't get one last unshift.
1007 + if (!state.endEmitted && state.length === 0) {
1008 + state.endEmitted = true;
1009 + stream.readable = false;
1010 + stream.emit('end');
1011 + }
1012 +}
1013 +
1014 +function indexOf(xs, x) {
1015 + for (var i = 0, l = xs.length; i < l; i++) {
1016 + if (xs[i] === x) return i;
1017 + }
1018 + return -1;
1019 +}
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// a transform stream is a readable/writable stream where you do
23 +// something with the data. Sometimes it's called a "filter",
24 +// but that's not a great name for it, since that implies a thing where
25 +// some bits pass through, and others are simply ignored. (That would
26 +// be a valid example of a transform, of course.)
27 +//
28 +// While the output is causally related to the input, it's not a
29 +// necessarily symmetric or synchronous transformation. For example,
30 +// a zlib stream might take multiple plain-text writes(), and then
31 +// emit a single compressed chunk some time in the future.
32 +//
33 +// Here's how this works:
34 +//
35 +// The Transform stream has all the aspects of the readable and writable
36 +// stream classes. When you write(chunk), that calls _write(chunk,cb)
37 +// internally, and returns false if there's a lot of pending writes
38 +// buffered up. When you call read(), that calls _read(n) until
39 +// there's enough pending readable data buffered up.
40 +//
41 +// In a transform stream, the written data is placed in a buffer. When
42 +// _read(n) is called, it transforms the queued up data, calling the
43 +// buffered _write cb's as it consumes chunks. If consuming a single
44 +// written chunk would result in multiple output chunks, then the first
45 +// outputted bit calls the readcb, and subsequent chunks just go into
46 +// the read buffer, and will cause it to emit 'readable' if necessary.
47 +//
48 +// This way, back-pressure is actually determined by the reading side,
49 +// since _read has to be called to start processing a new chunk. However,
50 +// a pathological inflate type of transform can cause excessive buffering
51 +// here. For example, imagine a stream where every byte of input is
52 +// interpreted as an integer from 0-255, and then results in that many
53 +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
54 +// 1kb of data being output. In this case, you could write a very small
55 +// amount of input, and end up with a very large amount of output. In
56 +// such a pathological inflating mechanism, there'd be no way to tell
57 +// the system to stop doing the transform. A single 4MB write could
58 +// cause the system to run out of memory.
59 +//
60 +// However, even in such a pathological case, only a single written chunk
61 +// would be consumed, and then the rest would wait (un-transformed) until
62 +// the results of the previous transformed chunk were consumed.
63 +
64 +'use strict';
65 +
66 +module.exports = Transform;
67 +
68 +var Duplex = require('./_stream_duplex');
69 +
70 +/*<replacement>*/
71 +var util = require('core-util-is');
72 +util.inherits = require('inherits');
73 +/*</replacement>*/
74 +
75 +util.inherits(Transform, Duplex);
76 +
77 +function afterTransform(er, data) {
78 + var ts = this._transformState;
79 + ts.transforming = false;
80 +
81 + var cb = ts.writecb;
82 +
83 + if (!cb) {
84 + return this.emit('error', new Error('write callback called multiple times'));
85 + }
86 +
87 + ts.writechunk = null;
88 + ts.writecb = null;
89 +
90 + if (data != null) // single equals check for both `null` and `undefined`
91 + this.push(data);
92 +
93 + cb(er);
94 +
95 + var rs = this._readableState;
96 + rs.reading = false;
97 + if (rs.needReadable || rs.length < rs.highWaterMark) {
98 + this._read(rs.highWaterMark);
99 + }
100 +}
101 +
102 +function Transform(options) {
103 + if (!(this instanceof Transform)) return new Transform(options);
104 +
105 + Duplex.call(this, options);
106 +
107 + this._transformState = {
108 + afterTransform: afterTransform.bind(this),
109 + needTransform: false,
110 + transforming: false,
111 + writecb: null,
112 + writechunk: null,
113 + writeencoding: null
114 + };
115 +
116 + // start out asking for a readable event once data is transformed.
117 + this._readableState.needReadable = true;
118 +
119 + // we have implemented the _read method, and done the other things
120 + // that Readable wants before the first _read call, so unset the
121 + // sync guard flag.
122 + this._readableState.sync = false;
123 +
124 + if (options) {
125 + if (typeof options.transform === 'function') this._transform = options.transform;
126 +
127 + if (typeof options.flush === 'function') this._flush = options.flush;
128 + }
129 +
130 + // When the writable side finishes, then flush out anything remaining.
131 + this.on('prefinish', prefinish);
132 +}
133 +
134 +function prefinish() {
135 + var _this = this;
136 +
137 + if (typeof this._flush === 'function') {
138 + this._flush(function (er, data) {
139 + done(_this, er, data);
140 + });
141 + } else {
142 + done(this, null, null);
143 + }
144 +}
145 +
146 +Transform.prototype.push = function (chunk, encoding) {
147 + this._transformState.needTransform = false;
148 + return Duplex.prototype.push.call(this, chunk, encoding);
149 +};
150 +
151 +// This is the part where you do stuff!
152 +// override this function in implementation classes.
153 +// 'chunk' is an input chunk.
154 +//
155 +// Call `push(newChunk)` to pass along transformed output
156 +// to the readable side. You may call 'push' zero or more times.
157 +//
158 +// Call `cb(err)` when you are done with this chunk. If you pass
159 +// an error, then that'll put the hurt on the whole operation. If you
160 +// never call cb(), then you'll never get another chunk.
161 +Transform.prototype._transform = function (chunk, encoding, cb) {
162 + throw new Error('_transform() is not implemented');
163 +};
164 +
165 +Transform.prototype._write = function (chunk, encoding, cb) {
166 + var ts = this._transformState;
167 + ts.writecb = cb;
168 + ts.writechunk = chunk;
169 + ts.writeencoding = encoding;
170 + if (!ts.transforming) {
171 + var rs = this._readableState;
172 + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
173 + }
174 +};
175 +
176 +// Doesn't matter what the args are here.
177 +// _transform does all the work.
178 +// That we got here means that the readable side wants more data.
179 +Transform.prototype._read = function (n) {
180 + var ts = this._transformState;
181 +
182 + if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
183 + ts.transforming = true;
184 + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
185 + } else {
186 + // mark that we need a transform, so that any data that comes in
187 + // will get processed, now that we've asked for it.
188 + ts.needTransform = true;
189 + }
190 +};
191 +
192 +Transform.prototype._destroy = function (err, cb) {
193 + var _this2 = this;
194 +
195 + Duplex.prototype._destroy.call(this, err, function (err2) {
196 + cb(err2);
197 + _this2.emit('close');
198 + });
199 +};
200 +
201 +function done(stream, er, data) {
202 + if (er) return stream.emit('error', er);
203 +
204 + if (data != null) // single equals check for both `null` and `undefined`
205 + stream.push(data);
206 +
207 + // if there's nothing in the write buffer, then that means
208 + // that nothing more will ever be provided
209 + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
210 +
211 + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
212 +
213 + return stream.push(null);
214 +}
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// A bit simpler than readable streams.
23 +// Implement an async ._write(chunk, encoding, cb), and it'll handle all
24 +// the drain event emission and buffering.
25 +
26 +'use strict';
27 +
28 +/*<replacement>*/
29 +
30 +var pna = require('process-nextick-args');
31 +/*</replacement>*/
32 +
33 +module.exports = Writable;
34 +
35 +/* <replacement> */
36 +function WriteReq(chunk, encoding, cb) {
37 + this.chunk = chunk;
38 + this.encoding = encoding;
39 + this.callback = cb;
40 + this.next = null;
41 +}
42 +
43 +// It seems a linked list but it is not
44 +// there will be only 2 of these for each stream
45 +function CorkedRequest(state) {
46 + var _this = this;
47 +
48 + this.next = null;
49 + this.entry = null;
50 + this.finish = function () {
51 + onCorkedFinish(_this, state);
52 + };
53 +}
54 +/* </replacement> */
55 +
56 +/*<replacement>*/
57 +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
58 +/*</replacement>*/
59 +
60 +/*<replacement>*/
61 +var Duplex;
62 +/*</replacement>*/
63 +
64 +Writable.WritableState = WritableState;
65 +
66 +/*<replacement>*/
67 +var util = require('core-util-is');
68 +util.inherits = require('inherits');
69 +/*</replacement>*/
70 +
71 +/*<replacement>*/
72 +var internalUtil = {
73 + deprecate: require('util-deprecate')
74 +};
75 +/*</replacement>*/
76 +
77 +/*<replacement>*/
78 +var Stream = require('./internal/streams/stream');
79 +/*</replacement>*/
80 +
81 +/*<replacement>*/
82 +
83 +var Buffer = require('safe-buffer').Buffer;
84 +var OurUint8Array = global.Uint8Array || function () {};
85 +function _uint8ArrayToBuffer(chunk) {
86 + return Buffer.from(chunk);
87 +}
88 +function _isUint8Array(obj) {
89 + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
90 +}
91 +
92 +/*</replacement>*/
93 +
94 +var destroyImpl = require('./internal/streams/destroy');
95 +
96 +util.inherits(Writable, Stream);
97 +
98 +function nop() {}
99 +
100 +function WritableState(options, stream) {
101 + Duplex = Duplex || require('./_stream_duplex');
102 +
103 + options = options || {};
104 +
105 + // Duplex streams are both readable and writable, but share
106 + // the same options object.
107 + // However, some cases require setting options to different
108 + // values for the readable and the writable sides of the duplex stream.
109 + // These options can be provided separately as readableXXX and writableXXX.
110 + var isDuplex = stream instanceof Duplex;
111 +
112 + // object stream flag to indicate whether or not this stream
113 + // contains buffers or objects.
114 + this.objectMode = !!options.objectMode;
115 +
116 + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
117 +
118 + // the point at which write() starts returning false
119 + // Note: 0 is a valid value, means that we always return false if
120 + // the entire buffer is not flushed immediately on write()
121 + var hwm = options.highWaterMark;
122 + var writableHwm = options.writableHighWaterMark;
123 + var defaultHwm = this.objectMode ? 16 : 16 * 1024;
124 +
125 + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
126 +
127 + // cast to ints.
128 + this.highWaterMark = Math.floor(this.highWaterMark);
129 +
130 + // if _final has been called
131 + this.finalCalled = false;
132 +
133 + // drain event flag.
134 + this.needDrain = false;
135 + // at the start of calling end()
136 + this.ending = false;
137 + // when end() has been called, and returned
138 + this.ended = false;
139 + // when 'finish' is emitted
140 + this.finished = false;
141 +
142 + // has it been destroyed
143 + this.destroyed = false;
144 +
145 + // should we decode strings into buffers before passing to _write?
146 + // this is here so that some node-core streams can optimize string
147 + // handling at a lower level.
148 + var noDecode = options.decodeStrings === false;
149 + this.decodeStrings = !noDecode;
150 +
151 + // Crypto is kind of old and crusty. Historically, its default string
152 + // encoding is 'binary' so we have to make this configurable.
153 + // Everything else in the universe uses 'utf8', though.
154 + this.defaultEncoding = options.defaultEncoding || 'utf8';
155 +
156 + // not an actual buffer we keep track of, but a measurement
157 + // of how much we're waiting to get pushed to some underlying
158 + // socket or file.
159 + this.length = 0;
160 +
161 + // a flag to see when we're in the middle of a write.
162 + this.writing = false;
163 +
164 + // when true all writes will be buffered until .uncork() call
165 + this.corked = 0;
166 +
167 + // a flag to be able to tell if the onwrite cb is called immediately,
168 + // or on a later tick. We set this to true at first, because any
169 + // actions that shouldn't happen until "later" should generally also
170 + // not happen before the first write call.
171 + this.sync = true;
172 +
173 + // a flag to know if we're processing previously buffered items, which
174 + // may call the _write() callback in the same tick, so that we don't
175 + // end up in an overlapped onwrite situation.
176 + this.bufferProcessing = false;
177 +
178 + // the callback that's passed to _write(chunk,cb)
179 + this.onwrite = function (er) {
180 + onwrite(stream, er);
181 + };
182 +
183 + // the callback that the user supplies to write(chunk,encoding,cb)
184 + this.writecb = null;
185 +
186 + // the amount that is being written when _write is called.
187 + this.writelen = 0;
188 +
189 + this.bufferedRequest = null;
190 + this.lastBufferedRequest = null;
191 +
192 + // number of pending user-supplied write callbacks
193 + // this must be 0 before 'finish' can be emitted
194 + this.pendingcb = 0;
195 +
196 + // emit prefinish if the only thing we're waiting for is _write cbs
197 + // This is relevant for synchronous Transform streams
198 + this.prefinished = false;
199 +
200 + // True if the error was already emitted and should not be thrown again
201 + this.errorEmitted = false;
202 +
203 + // count buffered requests
204 + this.bufferedRequestCount = 0;
205 +
206 + // allocate the first CorkedRequest, there is always
207 + // one allocated and free to use, and we maintain at most two
208 + this.corkedRequestsFree = new CorkedRequest(this);
209 +}
210 +
211 +WritableState.prototype.getBuffer = function getBuffer() {
212 + var current = this.bufferedRequest;
213 + var out = [];
214 + while (current) {
215 + out.push(current);
216 + current = current.next;
217 + }
218 + return out;
219 +};
220 +
221 +(function () {
222 + try {
223 + Object.defineProperty(WritableState.prototype, 'buffer', {
224 + get: internalUtil.deprecate(function () {
225 + return this.getBuffer();
226 + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
227 + });
228 + } catch (_) {}
229 +})();
230 +
231 +// Test _writableState for inheritance to account for Duplex streams,
232 +// whose prototype chain only points to Readable.
233 +var realHasInstance;
234 +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
235 + realHasInstance = Function.prototype[Symbol.hasInstance];
236 + Object.defineProperty(Writable, Symbol.hasInstance, {
237 + value: function (object) {
238 + if (realHasInstance.call(this, object)) return true;
239 + if (this !== Writable) return false;
240 +
241 + return object && object._writableState instanceof WritableState;
242 + }
243 + });
244 +} else {
245 + realHasInstance = function (object) {
246 + return object instanceof this;
247 + };
248 +}
249 +
250 +function Writable(options) {
251 + Duplex = Duplex || require('./_stream_duplex');
252 +
253 + // Writable ctor is applied to Duplexes, too.
254 + // `realHasInstance` is necessary because using plain `instanceof`
255 + // would return false, as no `_writableState` property is attached.
256 +
257 + // Trying to use the custom `instanceof` for Writable here will also break the
258 + // Node.js LazyTransform implementation, which has a non-trivial getter for
259 + // `_writableState` that would lead to infinite recursion.
260 + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
261 + return new Writable(options);
262 + }
263 +
264 + this._writableState = new WritableState(options, this);
265 +
266 + // legacy.
267 + this.writable = true;
268 +
269 + if (options) {
270 + if (typeof options.write === 'function') this._write = options.write;
271 +
272 + if (typeof options.writev === 'function') this._writev = options.writev;
273 +
274 + if (typeof options.destroy === 'function') this._destroy = options.destroy;
275 +
276 + if (typeof options.final === 'function') this._final = options.final;
277 + }
278 +
279 + Stream.call(this);
280 +}
281 +
282 +// Otherwise people can pipe Writable streams, which is just wrong.
283 +Writable.prototype.pipe = function () {
284 + this.emit('error', new Error('Cannot pipe, not readable'));
285 +};
286 +
287 +function writeAfterEnd(stream, cb) {
288 + var er = new Error('write after end');
289 + // TODO: defer error events consistently everywhere, not just the cb
290 + stream.emit('error', er);
291 + pna.nextTick(cb, er);
292 +}
293 +
294 +// Checks that a user-supplied chunk is valid, especially for the particular
295 +// mode the stream is in. Currently this means that `null` is never accepted
296 +// and undefined/non-string values are only allowed in object mode.
297 +function validChunk(stream, state, chunk, cb) {
298 + var valid = true;
299 + var er = false;
300 +
301 + if (chunk === null) {
302 + er = new TypeError('May not write null values to stream');
303 + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
304 + er = new TypeError('Invalid non-string/buffer chunk');
305 + }
306 + if (er) {
307 + stream.emit('error', er);
308 + pna.nextTick(cb, er);
309 + valid = false;
310 + }
311 + return valid;
312 +}
313 +
314 +Writable.prototype.write = function (chunk, encoding, cb) {
315 + var state = this._writableState;
316 + var ret = false;
317 + var isBuf = !state.objectMode && _isUint8Array(chunk);
318 +
319 + if (isBuf && !Buffer.isBuffer(chunk)) {
320 + chunk = _uint8ArrayToBuffer(chunk);
321 + }
322 +
323 + if (typeof encoding === 'function') {
324 + cb = encoding;
325 + encoding = null;
326 + }
327 +
328 + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
329 +
330 + if (typeof cb !== 'function') cb = nop;
331 +
332 + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
333 + state.pendingcb++;
334 + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
335 + }
336 +
337 + return ret;
338 +};
339 +
340 +Writable.prototype.cork = function () {
341 + var state = this._writableState;
342 +
343 + state.corked++;
344 +};
345 +
346 +Writable.prototype.uncork = function () {
347 + var state = this._writableState;
348 +
349 + if (state.corked) {
350 + state.corked--;
351 +
352 + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
353 + }
354 +};
355 +
356 +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
357 + // node::ParseEncoding() requires lower case.
358 + if (typeof encoding === 'string') encoding = encoding.toLowerCase();
359 + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
360 + this._writableState.defaultEncoding = encoding;
361 + return this;
362 +};
363 +
364 +function decodeChunk(state, chunk, encoding) {
365 + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
366 + chunk = Buffer.from(chunk, encoding);
367 + }
368 + return chunk;
369 +}
370 +
371 +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
372 + // making it explicit this property is not enumerable
373 + // because otherwise some prototype manipulation in
374 + // userland will fail
375 + enumerable: false,
376 + get: function () {
377 + return this._writableState.highWaterMark;
378 + }
379 +});
380 +
381 +// if we're already writing something, then just put this
382 +// in the queue, and wait our turn. Otherwise, call _write
383 +// If we return false, then we need a drain event, so set that flag.
384 +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
385 + if (!isBuf) {
386 + var newChunk = decodeChunk(state, chunk, encoding);
387 + if (chunk !== newChunk) {
388 + isBuf = true;
389 + encoding = 'buffer';
390 + chunk = newChunk;
391 + }
392 + }
393 + var len = state.objectMode ? 1 : chunk.length;
394 +
395 + state.length += len;
396 +
397 + var ret = state.length < state.highWaterMark;
398 + // we must ensure that previous needDrain will not be reset to false.
399 + if (!ret) state.needDrain = true;
400 +
401 + if (state.writing || state.corked) {
402 + var last = state.lastBufferedRequest;
403 + state.lastBufferedRequest = {
404 + chunk: chunk,
405 + encoding: encoding,
406 + isBuf: isBuf,
407 + callback: cb,
408 + next: null
409 + };
410 + if (last) {
411 + last.next = state.lastBufferedRequest;
412 + } else {
413 + state.bufferedRequest = state.lastBufferedRequest;
414 + }
415 + state.bufferedRequestCount += 1;
416 + } else {
417 + doWrite(stream, state, false, len, chunk, encoding, cb);
418 + }
419 +
420 + return ret;
421 +}
422 +
423 +function doWrite(stream, state, writev, len, chunk, encoding, cb) {
424 + state.writelen = len;
425 + state.writecb = cb;
426 + state.writing = true;
427 + state.sync = true;
428 + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
429 + state.sync = false;
430 +}
431 +
432 +function onwriteError(stream, state, sync, er, cb) {
433 + --state.pendingcb;
434 +
435 + if (sync) {
436 + // defer the callback if we are being called synchronously
437 + // to avoid piling up things on the stack
438 + pna.nextTick(cb, er);
439 + // this can emit finish, and it will always happen
440 + // after error
441 + pna.nextTick(finishMaybe, stream, state);
442 + stream._writableState.errorEmitted = true;
443 + stream.emit('error', er);
444 + } else {
445 + // the caller expect this to happen before if
446 + // it is async
447 + cb(er);
448 + stream._writableState.errorEmitted = true;
449 + stream.emit('error', er);
450 + // this can emit finish, but finish must
451 + // always follow error
452 + finishMaybe(stream, state);
453 + }
454 +}
455 +
456 +function onwriteStateUpdate(state) {
457 + state.writing = false;
458 + state.writecb = null;
459 + state.length -= state.writelen;
460 + state.writelen = 0;
461 +}
462 +
463 +function onwrite(stream, er) {
464 + var state = stream._writableState;
465 + var sync = state.sync;
466 + var cb = state.writecb;
467 +
468 + onwriteStateUpdate(state);
469 +
470 + if (er) onwriteError(stream, state, sync, er, cb);else {
471 + // Check if we're actually ready to finish, but don't emit yet
472 + var finished = needFinish(state);
473 +
474 + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
475 + clearBuffer(stream, state);
476 + }
477 +
478 + if (sync) {
479 + /*<replacement>*/
480 + asyncWrite(afterWrite, stream, state, finished, cb);
481 + /*</replacement>*/
482 + } else {
483 + afterWrite(stream, state, finished, cb);
484 + }
485 + }
486 +}
487 +
488 +function afterWrite(stream, state, finished, cb) {
489 + if (!finished) onwriteDrain(stream, state);
490 + state.pendingcb--;
491 + cb();
492 + finishMaybe(stream, state);
493 +}
494 +
495 +// Must force callback to be called on nextTick, so that we don't
496 +// emit 'drain' before the write() consumer gets the 'false' return
497 +// value, and has a chance to attach a 'drain' listener.
498 +function onwriteDrain(stream, state) {
499 + if (state.length === 0 && state.needDrain) {
500 + state.needDrain = false;
501 + stream.emit('drain');
502 + }
503 +}
504 +
505 +// if there's something in the buffer waiting, then process it
506 +function clearBuffer(stream, state) {
507 + state.bufferProcessing = true;
508 + var entry = state.bufferedRequest;
509 +
510 + if (stream._writev && entry && entry.next) {
511 + // Fast case, write everything using _writev()
512 + var l = state.bufferedRequestCount;
513 + var buffer = new Array(l);
514 + var holder = state.corkedRequestsFree;
515 + holder.entry = entry;
516 +
517 + var count = 0;
518 + var allBuffers = true;
519 + while (entry) {
520 + buffer[count] = entry;
521 + if (!entry.isBuf) allBuffers = false;
522 + entry = entry.next;
523 + count += 1;
524 + }
525 + buffer.allBuffers = allBuffers;
526 +
527 + doWrite(stream, state, true, state.length, buffer, '', holder.finish);
528 +
529 + // doWrite is almost always async, defer these to save a bit of time
530 + // as the hot path ends with doWrite
531 + state.pendingcb++;
532 + state.lastBufferedRequest = null;
533 + if (holder.next) {
534 + state.corkedRequestsFree = holder.next;
535 + holder.next = null;
536 + } else {
537 + state.corkedRequestsFree = new CorkedRequest(state);
538 + }
539 + state.bufferedRequestCount = 0;
540 + } else {
541 + // Slow case, write chunks one-by-one
542 + while (entry) {
543 + var chunk = entry.chunk;
544 + var encoding = entry.encoding;
545 + var cb = entry.callback;
546 + var len = state.objectMode ? 1 : chunk.length;
547 +
548 + doWrite(stream, state, false, len, chunk, encoding, cb);
549 + entry = entry.next;
550 + state.bufferedRequestCount--;
551 + // if we didn't call the onwrite immediately, then
552 + // it means that we need to wait until it does.
553 + // also, that means that the chunk and cb are currently
554 + // being processed, so move the buffer counter past them.
555 + if (state.writing) {
556 + break;
557 + }
558 + }
559 +
560 + if (entry === null) state.lastBufferedRequest = null;
561 + }
562 +
563 + state.bufferedRequest = entry;
564 + state.bufferProcessing = false;
565 +}
566 +
567 +Writable.prototype._write = function (chunk, encoding, cb) {
568 + cb(new Error('_write() is not implemented'));
569 +};
570 +
571 +Writable.prototype._writev = null;
572 +
573 +Writable.prototype.end = function (chunk, encoding, cb) {
574 + var state = this._writableState;
575 +
576 + if (typeof chunk === 'function') {
577 + cb = chunk;
578 + chunk = null;
579 + encoding = null;
580 + } else if (typeof encoding === 'function') {
581 + cb = encoding;
582 + encoding = null;
583 + }
584 +
585 + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
586 +
587 + // .end() fully uncorks
588 + if (state.corked) {
589 + state.corked = 1;
590 + this.uncork();
591 + }
592 +
593 + // ignore unnecessary end() calls.
594 + if (!state.ending && !state.finished) endWritable(this, state, cb);
595 +};
596 +
597 +function needFinish(state) {
598 + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
599 +}
600 +function callFinal(stream, state) {
601 + stream._final(function (err) {
602 + state.pendingcb--;
603 + if (err) {
604 + stream.emit('error', err);
605 + }
606 + state.prefinished = true;
607 + stream.emit('prefinish');
608 + finishMaybe(stream, state);
609 + });
610 +}
611 +function prefinish(stream, state) {
612 + if (!state.prefinished && !state.finalCalled) {
613 + if (typeof stream._final === 'function') {
614 + state.pendingcb++;
615 + state.finalCalled = true;
616 + pna.nextTick(callFinal, stream, state);
617 + } else {
618 + state.prefinished = true;
619 + stream.emit('prefinish');
620 + }
621 + }
622 +}
623 +
624 +function finishMaybe(stream, state) {
625 + var need = needFinish(state);
626 + if (need) {
627 + prefinish(stream, state);
628 + if (state.pendingcb === 0) {
629 + state.finished = true;
630 + stream.emit('finish');
631 + }
632 + }
633 + return need;
634 +}
635 +
636 +function endWritable(stream, state, cb) {
637 + state.ending = true;
638 + finishMaybe(stream, state);
639 + if (cb) {
640 + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
641 + }
642 + state.ended = true;
643 + stream.writable = false;
644 +}
645 +
646 +function onCorkedFinish(corkReq, state, err) {
647 + var entry = corkReq.entry;
648 + corkReq.entry = null;
649 + while (entry) {
650 + var cb = entry.callback;
651 + state.pendingcb--;
652 + cb(err);
653 + entry = entry.next;
654 + }
655 + if (state.corkedRequestsFree) {
656 + state.corkedRequestsFree.next = corkReq;
657 + } else {
658 + state.corkedRequestsFree = corkReq;
659 + }
660 +}
661 +
662 +Object.defineProperty(Writable.prototype, 'destroyed', {
663 + get: function () {
664 + if (this._writableState === undefined) {
665 + return false;
666 + }
667 + return this._writableState.destroyed;
668 + },
669 + set: function (value) {
670 + // we ignore the value if the stream
671 + // has not been initialized yet
672 + if (!this._writableState) {
673 + return;
674 + }
675 +
676 + // backward compatibility, the user is explicitly
677 + // managing destroyed
678 + this._writableState.destroyed = value;
679 + }
680 +});
681 +
682 +Writable.prototype.destroy = destroyImpl.destroy;
683 +Writable.prototype._undestroy = destroyImpl.undestroy;
684 +Writable.prototype._destroy = function (err, cb) {
685 + this.end();
686 + cb(err);
687 +};
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4 +
5 +var Buffer = require('safe-buffer').Buffer;
6 +var util = require('util');
7 +
8 +function copyBuffer(src, target, offset) {
9 + src.copy(target, offset);
10 +}
11 +
12 +module.exports = function () {
13 + function BufferList() {
14 + _classCallCheck(this, BufferList);
15 +
16 + this.head = null;
17 + this.tail = null;
18 + this.length = 0;
19 + }
20 +
21 + BufferList.prototype.push = function push(v) {
22 + var entry = { data: v, next: null };
23 + if (this.length > 0) this.tail.next = entry;else this.head = entry;
24 + this.tail = entry;
25 + ++this.length;
26 + };
27 +
28 + BufferList.prototype.unshift = function unshift(v) {
29 + var entry = { data: v, next: this.head };
30 + if (this.length === 0) this.tail = entry;
31 + this.head = entry;
32 + ++this.length;
33 + };
34 +
35 + BufferList.prototype.shift = function shift() {
36 + if (this.length === 0) return;
37 + var ret = this.head.data;
38 + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
39 + --this.length;
40 + return ret;
41 + };
42 +
43 + BufferList.prototype.clear = function clear() {
44 + this.head = this.tail = null;
45 + this.length = 0;
46 + };
47 +
48 + BufferList.prototype.join = function join(s) {
49 + if (this.length === 0) return '';
50 + var p = this.head;
51 + var ret = '' + p.data;
52 + while (p = p.next) {
53 + ret += s + p.data;
54 + }return ret;
55 + };
56 +
57 + BufferList.prototype.concat = function concat(n) {
58 + if (this.length === 0) return Buffer.alloc(0);
59 + if (this.length === 1) return this.head.data;
60 + var ret = Buffer.allocUnsafe(n >>> 0);
61 + var p = this.head;
62 + var i = 0;
63 + while (p) {
64 + copyBuffer(p.data, ret, i);
65 + i += p.data.length;
66 + p = p.next;
67 + }
68 + return ret;
69 + };
70 +
71 + return BufferList;
72 +}();
73 +
74 +if (util && util.inspect && util.inspect.custom) {
75 + module.exports.prototype[util.inspect.custom] = function () {
76 + var obj = util.inspect({ length: this.length });
77 + return this.constructor.name + ' ' + obj;
78 + };
79 +}
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +/*<replacement>*/
4 +
5 +var pna = require('process-nextick-args');
6 +/*</replacement>*/
7 +
8 +// undocumented cb() API, needed for core, not for public API
9 +function destroy(err, cb) {
10 + var _this = this;
11 +
12 + var readableDestroyed = this._readableState && this._readableState.destroyed;
13 + var writableDestroyed = this._writableState && this._writableState.destroyed;
14 +
15 + if (readableDestroyed || writableDestroyed) {
16 + if (cb) {
17 + cb(err);
18 + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
19 + pna.nextTick(emitErrorNT, this, err);
20 + }
21 + return this;
22 + }
23 +
24 + // we set destroyed to true before firing error callbacks in order
25 + // to make it re-entrance safe in case destroy() is called within callbacks
26 +
27 + if (this._readableState) {
28 + this._readableState.destroyed = true;
29 + }
30 +
31 + // if this is a duplex stream mark the writable part as destroyed as well
32 + if (this._writableState) {
33 + this._writableState.destroyed = true;
34 + }
35 +
36 + this._destroy(err || null, function (err) {
37 + if (!cb && err) {
38 + pna.nextTick(emitErrorNT, _this, err);
39 + if (_this._writableState) {
40 + _this._writableState.errorEmitted = true;
41 + }
42 + } else if (cb) {
43 + cb(err);
44 + }
45 + });
46 +
47 + return this;
48 +}
49 +
50 +function undestroy() {
51 + if (this._readableState) {
52 + this._readableState.destroyed = false;
53 + this._readableState.reading = false;
54 + this._readableState.ended = false;
55 + this._readableState.endEmitted = false;
56 + }
57 +
58 + if (this._writableState) {
59 + this._writableState.destroyed = false;
60 + this._writableState.ended = false;
61 + this._writableState.ending = false;
62 + this._writableState.finished = false;
63 + this._writableState.errorEmitted = false;
64 + }
65 +}
66 +
67 +function emitErrorNT(self, err) {
68 + self.emit('error', err);
69 +}
70 +
71 +module.exports = {
72 + destroy: destroy,
73 + undestroy: undestroy
74 +};
...\ No newline at end of file ...\ No newline at end of file
1 +module.exports = require('events').EventEmitter;
1 +{
2 + "_from": "readable-stream@2.3.6",
3 + "_id": "readable-stream@2.3.6",
4 + "_inBundle": false,
5 + "_integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==",
6 + "_location": "/readable-stream",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "version",
10 + "registry": true,
11 + "raw": "readable-stream@2.3.6",
12 + "name": "readable-stream",
13 + "escapedName": "readable-stream",
14 + "rawSpec": "2.3.6",
15 + "saveSpec": null,
16 + "fetchSpec": "2.3.6"
17 + },
18 + "_requiredBy": [
19 + "/mysql"
20 + ],
21 + "_resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz",
22 + "_shasum": "b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf",
23 + "_spec": "readable-stream@2.3.6",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/mysql",
25 + "browser": {
26 + "util": false,
27 + "./readable.js": "./readable-browser.js",
28 + "./writable.js": "./writable-browser.js",
29 + "./duplex.js": "./duplex-browser.js",
30 + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js"
31 + },
32 + "bugs": {
33 + "url": "https://github.com/nodejs/readable-stream/issues"
34 + },
35 + "bundleDependencies": false,
36 + "dependencies": {
37 + "core-util-is": "~1.0.0",
38 + "inherits": "~2.0.3",
39 + "isarray": "~1.0.0",
40 + "process-nextick-args": "~2.0.0",
41 + "safe-buffer": "~5.1.1",
42 + "string_decoder": "~1.1.1",
43 + "util-deprecate": "~1.0.1"
44 + },
45 + "deprecated": false,
46 + "description": "Streams3, a user-land copy of the stream library from Node.js",
47 + "devDependencies": {
48 + "assert": "^1.4.0",
49 + "babel-polyfill": "^6.9.1",
50 + "buffer": "^4.9.0",
51 + "lolex": "^2.3.2",
52 + "nyc": "^6.4.0",
53 + "tap": "^0.7.0",
54 + "tape": "^4.8.0"
55 + },
56 + "homepage": "https://github.com/nodejs/readable-stream#readme",
57 + "keywords": [
58 + "readable",
59 + "stream",
60 + "pipe"
61 + ],
62 + "license": "MIT",
63 + "main": "readable.js",
64 + "name": "readable-stream",
65 + "nyc": {
66 + "include": [
67 + "lib/**.js"
68 + ]
69 + },
70 + "repository": {
71 + "type": "git",
72 + "url": "git://github.com/nodejs/readable-stream.git"
73 + },
74 + "scripts": {
75 + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js",
76 + "cover": "nyc npm test",
77 + "report": "nyc report --reporter=lcov",
78 + "test": "tap test/parallel/*.js test/ours/*.js && node test/verify-dependencies.js"
79 + },
80 + "version": "2.3.6"
81 +}
1 +module.exports = require('./readable').PassThrough
1 +exports = module.exports = require('./lib/_stream_readable.js');
2 +exports.Stream = exports;
3 +exports.Readable = exports;
4 +exports.Writable = require('./lib/_stream_writable.js');
5 +exports.Duplex = require('./lib/_stream_duplex.js');
6 +exports.Transform = require('./lib/_stream_transform.js');
7 +exports.PassThrough = require('./lib/_stream_passthrough.js');
1 +var Stream = require('stream');
2 +if (process.env.READABLE_STREAM === 'disable' && Stream) {
3 + module.exports = Stream;
4 + exports = module.exports = Stream.Readable;
5 + exports.Readable = Stream.Readable;
6 + exports.Writable = Stream.Writable;
7 + exports.Duplex = Stream.Duplex;
8 + exports.Transform = Stream.Transform;
9 + exports.PassThrough = Stream.PassThrough;
10 + exports.Stream = Stream;
11 +} else {
12 + exports = module.exports = require('./lib/_stream_readable.js');
13 + exports.Stream = Stream || exports;
14 + exports.Readable = exports;
15 + exports.Writable = require('./lib/_stream_writable.js');
16 + exports.Duplex = require('./lib/_stream_duplex.js');
17 + exports.Transform = require('./lib/_stream_transform.js');
18 + exports.PassThrough = require('./lib/_stream_passthrough.js');
19 +}
1 +module.exports = require('./readable').Transform
1 +module.exports = require('./lib/_stream_writable.js');
1 +var Stream = require("stream")
2 +var Writable = require("./lib/_stream_writable.js")
3 +
4 +if (process.env.READABLE_STREAM === 'disable') {
5 + module.exports = Stream && Stream.Writable || Writable
6 +} else {
7 + module.exports = Writable
8 +}
1 +2.3.1 / 2018-02-24
2 +==================
3 +
4 + * Fix incorrectly replacing non-placeholders in SQL
5 +
6 +2.3.0 / 2017-10-01
7 +==================
8 +
9 + * Add `.toSqlString()` escape overriding
10 + * Add `raw` method to wrap raw strings for escape overriding
11 + * Small performance improvement on `escapeId`
12 +
13 +2.2.0 / 2016-11-01
14 +==================
15 +
16 + * Escape invalid `Date` objects as `NULL`
17 +
18 +2.1.0 / 2016-09-26
19 +==================
20 +
21 + * Accept numbers and other value types in `escapeId`
22 + * Run `buffer.toString()` through escaping
23 +
24 +2.0.1 / 2016-06-06
25 +==================
26 +
27 + * Fix npm package to include missing `lib/` directory
28 +
29 +2.0.0 / 2016-06-06
30 +==================
31 +
32 + * Bring repository up-to-date with `mysql` module changes
33 + * Support Node.js 0.6.x
34 +
35 +1.0.0 / 2014-11-09
36 +==================
37 +
38 + * Support Node.js 0.8.x
39 +
40 +0.0.1 / 2014-02-25
41 +==================
42 +
43 + * Initial release
1 +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors
2 +
3 + Permission is hereby granted, free of charge, to any person obtaining a copy
4 + of this software and associated documentation files (the "Software"), to deal
5 + in the Software without restriction, including without limitation the rights
6 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 + copies of the Software, and to permit persons to whom the Software is
8 + furnished to do so, subject to the following conditions:
9 +
10 + The above copyright notice and this permission notice shall be included in
11 + all copies or substantial portions of the Software.
12 +
13 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 + THE SOFTWARE.
1 +# sqlstring
2 +
3 +[![NPM Version][npm-version-image]][npm-url]
4 +[![NPM Downloads][npm-downloads-image]][npm-url]
5 +[![Node.js Version][node-image]][node-url]
6 +[![Build Status][travis-image]][travis-url]
7 +[![Coverage Status][coveralls-image]][coveralls-url]
8 +
9 +Simple SQL escape and format for MySQL
10 +
11 +## Install
12 +
13 +```sh
14 +$ npm install sqlstring
15 +```
16 +
17 +## Usage
18 +
19 +<!-- eslint-disable no-unused-vars -->
20 +
21 +```js
22 +var SqlString = require('sqlstring');
23 +```
24 +
25 +### Escaping query values
26 +
27 +**Caution** These methods of escaping values only works when the
28 +[NO_BACKSLASH_ESCAPES](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_backslash_escapes)
29 +SQL mode is disabled (which is the default state for MySQL servers).
30 +
31 +In order to avoid SQL Injection attacks, you should always escape any user
32 +provided data before using it inside a SQL query. You can do so using the
33 +`SqlString.escape()` method:
34 +
35 +```js
36 +var userId = 'some user provided value';
37 +var sql = 'SELECT * FROM users WHERE id = ' + SqlString.escape(userId);
38 +console.log(sql); // SELECT * FROM users WHERE id = 'some user provided value'
39 +```
40 +
41 +Alternatively, you can use `?` characters as placeholders for values you would
42 +like to have escaped like this:
43 +
44 +```js
45 +var userId = 1;
46 +var sql = SqlString.format('SELECT * FROM users WHERE id = ?', [userId]);
47 +console.log(sql); // SELECT * FROM users WHERE id = 1
48 +```
49 +
50 +Multiple placeholders are mapped to values in the same order as passed. For example,
51 +in the following query `foo` equals `a`, `bar` equals `b`, `baz` equals `c`, and
52 +`id` will be `userId`:
53 +
54 +```js
55 +var userId = 1;
56 +var sql = SqlString.format('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?',
57 + ['a', 'b', 'c', userId]);
58 +console.log(sql); // UPDATE users SET foo = 'a', bar = 'b', baz = 'c' WHERE id = 1
59 +```
60 +
61 +This looks similar to prepared statements in MySQL, however it really just uses
62 +the same `SqlString.escape()` method internally.
63 +
64 +**Caution** This also differs from prepared statements in that all `?` are
65 +replaced, even those contained in comments and strings.
66 +
67 +Different value types are escaped differently, here is how:
68 +
69 +* Numbers are left untouched
70 +* Booleans are converted to `true` / `false`
71 +* Date objects are converted to `'YYYY-mm-dd HH:ii:ss'` strings
72 +* Buffers are converted to hex strings, e.g. `X'0fa5'`
73 +* Strings are safely escaped
74 +* Arrays are turned into list, e.g. `['a', 'b']` turns into `'a', 'b'`
75 +* Nested arrays are turned into grouped lists (for bulk inserts), e.g. `[['a',
76 + 'b'], ['c', 'd']]` turns into `('a', 'b'), ('c', 'd')`
77 +* Objects that have a `toSqlString` method will have `.toSqlString()` called
78 + and the returned value is used as the raw SQL.
79 +* Objects are turned into `key = 'val'` pairs for each enumerable property on
80 + the object. If the property's value is a function, it is skipped; if the
81 + property's value is an object, toString() is called on it and the returned
82 + value is used.
83 +* `undefined` / `null` are converted to `NULL`
84 +* `NaN` / `Infinity` are left as-is. MySQL does not support these, and trying
85 + to insert them as values will trigger MySQL errors until they implement
86 + support.
87 +
88 +You may have noticed that this escaping allows you to do neat things like this:
89 +
90 +```js
91 +var post = {id: 1, title: 'Hello MySQL'};
92 +var sql = SqlString.format('INSERT INTO posts SET ?', post);
93 +console.log(sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
94 +```
95 +
96 +And the `toSqlString` method allows you to form complex queries with functions:
97 +
98 +```js
99 +var CURRENT_TIMESTAMP = { toSqlString: function() { return 'CURRENT_TIMESTAMP()'; } };
100 +var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]);
101 +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42
102 +```
103 +
104 +To generate objects with a `toSqlString` method, the `SqlString.raw()` method can
105 +be used. This creates an object that will be left un-touched when using in a `?`
106 +placeholder, useful for using functions as dynamic values:
107 +
108 +**Caution** The string provided to `SqlString.raw()` will skip all escaping
109 +functions when used, so be careful when passing in unvalidated input.
110 +
111 +```js
112 +var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()');
113 +var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]);
114 +console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42
115 +```
116 +
117 +If you feel the need to escape queries by yourself, you can also use the escaping
118 +function directly:
119 +
120 +```js
121 +var sql = 'SELECT * FROM posts WHERE title=' + SqlString.escape('Hello MySQL');
122 +console.log(sql); // SELECT * FROM posts WHERE title='Hello MySQL'
123 +```
124 +
125 +### Escaping query identifiers
126 +
127 +If you can't trust an SQL identifier (database / table / column name) because it is
128 +provided by a user, you should escape it with `SqlString.escapeId(identifier)` like this:
129 +
130 +```js
131 +var sorter = 'date';
132 +var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter);
133 +console.log(sql); // SELECT * FROM posts ORDER BY `date`
134 +```
135 +
136 +It also supports adding qualified identifiers. It will escape both parts.
137 +
138 +```js
139 +var sorter = 'date';
140 +var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId('posts.' + sorter);
141 +console.log(sql); // SELECT * FROM posts ORDER BY `posts`.`date`
142 +```
143 +
144 +If you do not want to treat `.` as qualified identifiers, you can set the second
145 +argument to `true` in order to keep the string as a literal identifier:
146 +
147 +```js
148 +var sorter = 'date.2';
149 +var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter, true);
150 +console.log(sql); // SELECT * FROM posts ORDER BY `date.2`
151 +```
152 +
153 +Alternatively, you can use `??` characters as placeholders for identifiers you would
154 +like to have escaped like this:
155 +
156 +```js
157 +var userId = 1;
158 +var columns = ['username', 'email'];
159 +var sql = SqlString.format('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId]);
160 +console.log(sql); // SELECT `username`, `email` FROM `users` WHERE id = 1
161 +```
162 +**Please note that this last character sequence is experimental and syntax might change**
163 +
164 +When you pass an Object to `.escape()` or `.format()`, `.escapeId()` is used to avoid SQL injection in object keys.
165 +
166 +### Formatting queries
167 +
168 +You can use `SqlString.format` to prepare a query with multiple insertion points,
169 +utilizing the proper escaping for ids and values. A simple example of this follows:
170 +
171 +```js
172 +var userId = 1;
173 +var inserts = ['users', 'id', userId];
174 +var sql = SqlString.format('SELECT * FROM ?? WHERE ?? = ?', inserts);
175 +console.log(sql); // SELECT * FROM `users` WHERE `id` = 1
176 +```
177 +
178 +Following this you then have a valid, escaped query that you can then send to the database safely.
179 +This is useful if you are looking to prepare the query before actually sending it to the database.
180 +You also have the option (but are not required) to pass in `stringifyObject` and `timeZone`,
181 +allowing you provide a custom means of turning objects into strings, as well as a
182 +location-specific/timezone-aware `Date`.
183 +
184 +This can be further combined with the `SqlString.raw()` helper to generate SQL
185 +that includes MySQL functions as dynamic vales:
186 +
187 +```js
188 +var userId = 1;
189 +var data = { email: 'foobar@example.com', modified: SqlString.raw('NOW()') };
190 +var sql = SqlString.format('UPDATE ?? SET ? WHERE `id` = ?', ['users', data, userId]);
191 +console.log(sql); // UPDATE `users` SET `email` = 'foobar@example.com', `modified` = NOW() WHERE `id` = 1
192 +```
193 +
194 +## License
195 +
196 +[MIT](LICENSE)
197 +
198 +[npm-version-image]: https://img.shields.io/npm/v/sqlstring.svg
199 +[npm-downloads-image]: https://img.shields.io/npm/dm/sqlstring.svg
200 +[npm-url]: https://npmjs.org/package/sqlstring
201 +[travis-image]: https://img.shields.io/travis/mysqljs/sqlstring/master.svg
202 +[travis-url]: https://travis-ci.org/mysqljs/sqlstring
203 +[coveralls-image]: https://img.shields.io/coveralls/mysqljs/sqlstring/master.svg
204 +[coveralls-url]: https://coveralls.io/r/mysqljs/sqlstring?branch=master
205 +[node-image]: https://img.shields.io/node/v/sqlstring.svg
206 +[node-url]: https://nodejs.org/en/download
1 +module.exports = require('./lib/SqlString');
1 +var SqlString = exports;
2 +
3 +var ID_GLOBAL_REGEXP = /`/g;
4 +var QUAL_GLOBAL_REGEXP = /\./g;
5 +var CHARS_GLOBAL_REGEXP = /[\0\b\t\n\r\x1a\"\'\\]/g; // eslint-disable-line no-control-regex
6 +var CHARS_ESCAPE_MAP = {
7 + '\0' : '\\0',
8 + '\b' : '\\b',
9 + '\t' : '\\t',
10 + '\n' : '\\n',
11 + '\r' : '\\r',
12 + '\x1a' : '\\Z',
13 + '"' : '\\"',
14 + '\'' : '\\\'',
15 + '\\' : '\\\\'
16 +};
17 +
18 +SqlString.escapeId = function escapeId(val, forbidQualified) {
19 + if (Array.isArray(val)) {
20 + var sql = '';
21 +
22 + for (var i = 0; i < val.length; i++) {
23 + sql += (i === 0 ? '' : ', ') + SqlString.escapeId(val[i], forbidQualified);
24 + }
25 +
26 + return sql;
27 + } else if (forbidQualified) {
28 + return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``') + '`';
29 + } else {
30 + return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``').replace(QUAL_GLOBAL_REGEXP, '`.`') + '`';
31 + }
32 +};
33 +
34 +SqlString.escape = function escape(val, stringifyObjects, timeZone) {
35 + if (val === undefined || val === null) {
36 + return 'NULL';
37 + }
38 +
39 + switch (typeof val) {
40 + case 'boolean': return (val) ? 'true' : 'false';
41 + case 'number': return val + '';
42 + case 'object':
43 + if (val instanceof Date) {
44 + return SqlString.dateToString(val, timeZone || 'local');
45 + } else if (Array.isArray(val)) {
46 + return SqlString.arrayToList(val, timeZone);
47 + } else if (Buffer.isBuffer(val)) {
48 + return SqlString.bufferToString(val);
49 + } else if (typeof val.toSqlString === 'function') {
50 + return String(val.toSqlString());
51 + } else if (stringifyObjects) {
52 + return escapeString(val.toString());
53 + } else {
54 + return SqlString.objectToValues(val, timeZone);
55 + }
56 + default: return escapeString(val);
57 + }
58 +};
59 +
60 +SqlString.arrayToList = function arrayToList(array, timeZone) {
61 + var sql = '';
62 +
63 + for (var i = 0; i < array.length; i++) {
64 + var val = array[i];
65 +
66 + if (Array.isArray(val)) {
67 + sql += (i === 0 ? '' : ', ') + '(' + SqlString.arrayToList(val, timeZone) + ')';
68 + } else {
69 + sql += (i === 0 ? '' : ', ') + SqlString.escape(val, true, timeZone);
70 + }
71 + }
72 +
73 + return sql;
74 +};
75 +
76 +SqlString.format = function format(sql, values, stringifyObjects, timeZone) {
77 + if (values == null) {
78 + return sql;
79 + }
80 +
81 + if (!(values instanceof Array || Array.isArray(values))) {
82 + values = [values];
83 + }
84 +
85 + var chunkIndex = 0;
86 + var placeholdersRegex = /\?+/g;
87 + var result = '';
88 + var valuesIndex = 0;
89 + var match;
90 +
91 + while (valuesIndex < values.length && (match = placeholdersRegex.exec(sql))) {
92 + var len = match[0].length;
93 +
94 + if (len > 2) {
95 + continue;
96 + }
97 +
98 + var value = len === 2
99 + ? SqlString.escapeId(values[valuesIndex])
100 + : SqlString.escape(values[valuesIndex], stringifyObjects, timeZone);
101 +
102 + result += sql.slice(chunkIndex, match.index) + value;
103 + chunkIndex = placeholdersRegex.lastIndex;
104 + valuesIndex++;
105 + }
106 +
107 + if (chunkIndex === 0) {
108 + // Nothing was replaced
109 + return sql;
110 + }
111 +
112 + if (chunkIndex < sql.length) {
113 + return result + sql.slice(chunkIndex);
114 + }
115 +
116 + return result;
117 +};
118 +
119 +SqlString.dateToString = function dateToString(date, timeZone) {
120 + var dt = new Date(date);
121 +
122 + if (isNaN(dt.getTime())) {
123 + return 'NULL';
124 + }
125 +
126 + var year;
127 + var month;
128 + var day;
129 + var hour;
130 + var minute;
131 + var second;
132 + var millisecond;
133 +
134 + if (timeZone === 'local') {
135 + year = dt.getFullYear();
136 + month = dt.getMonth() + 1;
137 + day = dt.getDate();
138 + hour = dt.getHours();
139 + minute = dt.getMinutes();
140 + second = dt.getSeconds();
141 + millisecond = dt.getMilliseconds();
142 + } else {
143 + var tz = convertTimezone(timeZone);
144 +
145 + if (tz !== false && tz !== 0) {
146 + dt.setTime(dt.getTime() + (tz * 60000));
147 + }
148 +
149 + year = dt.getUTCFullYear();
150 + month = dt.getUTCMonth() + 1;
151 + day = dt.getUTCDate();
152 + hour = dt.getUTCHours();
153 + minute = dt.getUTCMinutes();
154 + second = dt.getUTCSeconds();
155 + millisecond = dt.getUTCMilliseconds();
156 + }
157 +
158 + // YYYY-MM-DD HH:mm:ss.mmm
159 + var str = zeroPad(year, 4) + '-' + zeroPad(month, 2) + '-' + zeroPad(day, 2) + ' ' +
160 + zeroPad(hour, 2) + ':' + zeroPad(minute, 2) + ':' + zeroPad(second, 2) + '.' +
161 + zeroPad(millisecond, 3);
162 +
163 + return escapeString(str);
164 +};
165 +
166 +SqlString.bufferToString = function bufferToString(buffer) {
167 + return 'X' + escapeString(buffer.toString('hex'));
168 +};
169 +
170 +SqlString.objectToValues = function objectToValues(object, timeZone) {
171 + var sql = '';
172 +
173 + for (var key in object) {
174 + var val = object[key];
175 +
176 + if (typeof val === 'function') {
177 + continue;
178 + }
179 +
180 + sql += (sql.length === 0 ? '' : ', ') + SqlString.escapeId(key) + ' = ' + SqlString.escape(val, true, timeZone);
181 + }
182 +
183 + return sql;
184 +};
185 +
186 +SqlString.raw = function raw(sql) {
187 + if (typeof sql !== 'string') {
188 + throw new TypeError('argument sql must be a string');
189 + }
190 +
191 + return {
192 + toSqlString: function toSqlString() { return sql; }
193 + };
194 +};
195 +
196 +function escapeString(val) {
197 + var chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex = 0;
198 + var escapedVal = '';
199 + var match;
200 +
201 + while ((match = CHARS_GLOBAL_REGEXP.exec(val))) {
202 + escapedVal += val.slice(chunkIndex, match.index) + CHARS_ESCAPE_MAP[match[0]];
203 + chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex;
204 + }
205 +
206 + if (chunkIndex === 0) {
207 + // Nothing was escaped
208 + return "'" + val + "'";
209 + }
210 +
211 + if (chunkIndex < val.length) {
212 + return "'" + escapedVal + val.slice(chunkIndex) + "'";
213 + }
214 +
215 + return "'" + escapedVal + "'";
216 +}
217 +
218 +function zeroPad(number, length) {
219 + number = number.toString();
220 + while (number.length < length) {
221 + number = '0' + number;
222 + }
223 +
224 + return number;
225 +}
226 +
227 +function convertTimezone(tz) {
228 + if (tz === 'Z') {
229 + return 0;
230 + }
231 +
232 + var m = tz.match(/([\+\-\s])(\d\d):?(\d\d)?/);
233 + if (m) {
234 + return (m[1] === '-' ? -1 : 1) * (parseInt(m[2], 10) + ((m[3] ? parseInt(m[3], 10) : 0) / 60)) * 60;
235 + }
236 + return false;
237 +}
1 +{
2 + "_from": "sqlstring@2.3.1",
3 + "_id": "sqlstring@2.3.1",
4 + "_inBundle": false,
5 + "_integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A=",
6 + "_location": "/sqlstring",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "version",
10 + "registry": true,
11 + "raw": "sqlstring@2.3.1",
12 + "name": "sqlstring",
13 + "escapedName": "sqlstring",
14 + "rawSpec": "2.3.1",
15 + "saveSpec": null,
16 + "fetchSpec": "2.3.1"
17 + },
18 + "_requiredBy": [
19 + "/mysql"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz",
22 + "_shasum": "475393ff9e91479aea62dcaf0ca3d14983a7fb40",
23 + "_spec": "sqlstring@2.3.1",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/mysql",
25 + "bugs": {
26 + "url": "https://github.com/mysqljs/sqlstring/issues"
27 + },
28 + "bundleDependencies": false,
29 + "contributors": [
30 + {
31 + "name": "Adri Van Houdt",
32 + "email": "adri.van.houdt@gmail.com"
33 + },
34 + {
35 + "name": "Douglas Christopher Wilson",
36 + "email": "doug@somethingdoug.com"
37 + },
38 + {
39 + "name": "fengmk2",
40 + "email": "fengmk2@gmail.com",
41 + "url": "http://fengmk2.github.com"
42 + },
43 + {
44 + "name": "Kevin Jose Martin",
45 + "email": "kevin@tiliq.com"
46 + },
47 + {
48 + "name": "Nathan Woltman",
49 + "email": "nwoltman@outlook.com"
50 + },
51 + {
52 + "name": "Sergej Sintschilin",
53 + "email": "seregpie@gmail.com"
54 + }
55 + ],
56 + "deprecated": false,
57 + "description": "Simple SQL escape and format for MySQL",
58 + "devDependencies": {
59 + "beautify-benchmark": "0.2.4",
60 + "benchmark": "2.1.4",
61 + "eslint": "4.18.1",
62 + "eslint-plugin-markdown": "1.0.0-beta.6",
63 + "nyc": "10.3.2",
64 + "urun": "0.0.8",
65 + "utest": "0.0.8"
66 + },
67 + "engines": {
68 + "node": ">= 0.6"
69 + },
70 + "files": [
71 + "lib/",
72 + "HISTORY.md",
73 + "LICENSE",
74 + "README.md",
75 + "index.js"
76 + ],
77 + "homepage": "https://github.com/mysqljs/sqlstring#readme",
78 + "keywords": [
79 + "sqlstring",
80 + "sql",
81 + "escape",
82 + "sql escape"
83 + ],
84 + "license": "MIT",
85 + "name": "sqlstring",
86 + "repository": {
87 + "type": "git",
88 + "url": "git+https://github.com/mysqljs/sqlstring.git"
89 + },
90 + "scripts": {
91 + "bench": "node benchmark/index.js",
92 + "lint": "eslint --plugin markdown --ext js,md .",
93 + "test": "node test/run.js",
94 + "test-ci": "nyc --reporter=text npm test",
95 + "test-cov": "nyc --reporter=html --reporter=text npm test"
96 + },
97 + "version": "2.3.1"
98 +}
1 +sudo: false
2 +language: node_js
3 +before_install:
4 + - npm install -g npm@2
5 + - test $NPM_LEGACY && npm install -g npm@latest-3 || npm install npm -g
6 +notifications:
7 + email: false
8 +matrix:
9 + fast_finish: true
10 + include:
11 + - node_js: '0.8'
12 + env:
13 + - TASK=test
14 + - NPM_LEGACY=true
15 + - node_js: '0.10'
16 + env:
17 + - TASK=test
18 + - NPM_LEGACY=true
19 + - node_js: '0.11'
20 + env:
21 + - TASK=test
22 + - NPM_LEGACY=true
23 + - node_js: '0.12'
24 + env:
25 + - TASK=test
26 + - NPM_LEGACY=true
27 + - node_js: 1
28 + env:
29 + - TASK=test
30 + - NPM_LEGACY=true
31 + - node_js: 2
32 + env:
33 + - TASK=test
34 + - NPM_LEGACY=true
35 + - node_js: 3
36 + env:
37 + - TASK=test
38 + - NPM_LEGACY=true
39 + - node_js: 4
40 + env: TASK=test
41 + - node_js: 5
42 + env: TASK=test
43 + - node_js: 6
44 + env: TASK=test
45 + - node_js: 7
46 + env: TASK=test
47 + - node_js: 8
48 + env: TASK=test
49 + - node_js: 9
50 + env: TASK=test
1 +Node.js is licensed for use as follows:
2 +
3 +"""
4 +Copyright Node.js contributors. All rights reserved.
5 +
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to
8 +deal in the Software without restriction, including without limitation the
9 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 +sell copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +
13 +The above copyright notice and this permission notice shall be included in
14 +all copies or substantial portions of the Software.
15 +
16 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 +IN THE SOFTWARE.
23 +"""
24 +
25 +This license applies to parts of Node.js originating from the
26 +https://github.com/joyent/node repository:
27 +
28 +"""
29 +Copyright Joyent, Inc. and other Node contributors. All rights reserved.
30 +Permission is hereby granted, free of charge, to any person obtaining a copy
31 +of this software and associated documentation files (the "Software"), to
32 +deal in the Software without restriction, including without limitation the
33 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
34 +sell copies of the Software, and to permit persons to whom the Software is
35 +furnished to do so, subject to the following conditions:
36 +
37 +The above copyright notice and this permission notice shall be included in
38 +all copies or substantial portions of the Software.
39 +
40 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
45 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
46 +IN THE SOFTWARE.
47 +"""
48 +
1 +# string_decoder
2 +
3 +***Node-core v8.9.4 string_decoder for userland***
4 +
5 +
6 +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/)
7 +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/)
8 +
9 +
10 +```bash
11 +npm install --save string_decoder
12 +```
13 +
14 +***Node-core string_decoder for userland***
15 +
16 +This package is a mirror of the string_decoder implementation in Node-core.
17 +
18 +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/).
19 +
20 +As of version 1.0.0 **string_decoder** uses semantic versioning.
21 +
22 +## Previous versions
23 +
24 +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10.
25 +
26 +## Update
27 +
28 +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version.
29 +
30 +## Streams Working Group
31 +
32 +`string_decoder` is maintained by the Streams Working Group, which
33 +oversees the development and maintenance of the Streams API within
34 +Node.js. The responsibilities of the Streams Working Group include:
35 +
36 +* Addressing stream issues on the Node.js issue tracker.
37 +* Authoring and editing stream documentation within the Node.js project.
38 +* Reviewing changes to stream subclasses within the Node.js project.
39 +* Redirecting changes to streams from the Node.js project to this
40 + project.
41 +* Assisting in the implementation of stream providers within Node.js.
42 +* Recommending versions of `readable-stream` to be included in Node.js.
43 +* Messaging about the future of streams to give the community advance
44 + notice of changes.
45 +
46 +See [readable-stream](https://github.com/nodejs/readable-stream) for
47 +more details.
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +'use strict';
23 +
24 +/*<replacement>*/
25 +
26 +var Buffer = require('safe-buffer').Buffer;
27 +/*</replacement>*/
28 +
29 +var isEncoding = Buffer.isEncoding || function (encoding) {
30 + encoding = '' + encoding;
31 + switch (encoding && encoding.toLowerCase()) {
32 + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
33 + return true;
34 + default:
35 + return false;
36 + }
37 +};
38 +
39 +function _normalizeEncoding(enc) {
40 + if (!enc) return 'utf8';
41 + var retried;
42 + while (true) {
43 + switch (enc) {
44 + case 'utf8':
45 + case 'utf-8':
46 + return 'utf8';
47 + case 'ucs2':
48 + case 'ucs-2':
49 + case 'utf16le':
50 + case 'utf-16le':
51 + return 'utf16le';
52 + case 'latin1':
53 + case 'binary':
54 + return 'latin1';
55 + case 'base64':
56 + case 'ascii':
57 + case 'hex':
58 + return enc;
59 + default:
60 + if (retried) return; // undefined
61 + enc = ('' + enc).toLowerCase();
62 + retried = true;
63 + }
64 + }
65 +};
66 +
67 +// Do not cache `Buffer.isEncoding` when checking encoding names as some
68 +// modules monkey-patch it to support additional encodings
69 +function normalizeEncoding(enc) {
70 + var nenc = _normalizeEncoding(enc);
71 + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
72 + return nenc || enc;
73 +}
74 +
75 +// StringDecoder provides an interface for efficiently splitting a series of
76 +// buffers into a series of JS strings without breaking apart multi-byte
77 +// characters.
78 +exports.StringDecoder = StringDecoder;
79 +function StringDecoder(encoding) {
80 + this.encoding = normalizeEncoding(encoding);
81 + var nb;
82 + switch (this.encoding) {
83 + case 'utf16le':
84 + this.text = utf16Text;
85 + this.end = utf16End;
86 + nb = 4;
87 + break;
88 + case 'utf8':
89 + this.fillLast = utf8FillLast;
90 + nb = 4;
91 + break;
92 + case 'base64':
93 + this.text = base64Text;
94 + this.end = base64End;
95 + nb = 3;
96 + break;
97 + default:
98 + this.write = simpleWrite;
99 + this.end = simpleEnd;
100 + return;
101 + }
102 + this.lastNeed = 0;
103 + this.lastTotal = 0;
104 + this.lastChar = Buffer.allocUnsafe(nb);
105 +}
106 +
107 +StringDecoder.prototype.write = function (buf) {
108 + if (buf.length === 0) return '';
109 + var r;
110 + var i;
111 + if (this.lastNeed) {
112 + r = this.fillLast(buf);
113 + if (r === undefined) return '';
114 + i = this.lastNeed;
115 + this.lastNeed = 0;
116 + } else {
117 + i = 0;
118 + }
119 + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
120 + return r || '';
121 +};
122 +
123 +StringDecoder.prototype.end = utf8End;
124 +
125 +// Returns only complete characters in a Buffer
126 +StringDecoder.prototype.text = utf8Text;
127 +
128 +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
129 +StringDecoder.prototype.fillLast = function (buf) {
130 + if (this.lastNeed <= buf.length) {
131 + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
132 + return this.lastChar.toString(this.encoding, 0, this.lastTotal);
133 + }
134 + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
135 + this.lastNeed -= buf.length;
136 +};
137 +
138 +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
139 +// continuation byte. If an invalid byte is detected, -2 is returned.
140 +function utf8CheckByte(byte) {
141 + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
142 + return byte >> 6 === 0x02 ? -1 : -2;
143 +}
144 +
145 +// Checks at most 3 bytes at the end of a Buffer in order to detect an
146 +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
147 +// needed to complete the UTF-8 character (if applicable) are returned.
148 +function utf8CheckIncomplete(self, buf, i) {
149 + var j = buf.length - 1;
150 + if (j < i) return 0;
151 + var nb = utf8CheckByte(buf[j]);
152 + if (nb >= 0) {
153 + if (nb > 0) self.lastNeed = nb - 1;
154 + return nb;
155 + }
156 + if (--j < i || nb === -2) return 0;
157 + nb = utf8CheckByte(buf[j]);
158 + if (nb >= 0) {
159 + if (nb > 0) self.lastNeed = nb - 2;
160 + return nb;
161 + }
162 + if (--j < i || nb === -2) return 0;
163 + nb = utf8CheckByte(buf[j]);
164 + if (nb >= 0) {
165 + if (nb > 0) {
166 + if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
167 + }
168 + return nb;
169 + }
170 + return 0;
171 +}
172 +
173 +// Validates as many continuation bytes for a multi-byte UTF-8 character as
174 +// needed or are available. If we see a non-continuation byte where we expect
175 +// one, we "replace" the validated continuation bytes we've seen so far with
176 +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
177 +// behavior. The continuation byte check is included three times in the case
178 +// where all of the continuation bytes for a character exist in the same buffer.
179 +// It is also done this way as a slight performance increase instead of using a
180 +// loop.
181 +function utf8CheckExtraBytes(self, buf, p) {
182 + if ((buf[0] & 0xC0) !== 0x80) {
183 + self.lastNeed = 0;
184 + return '\ufffd';
185 + }
186 + if (self.lastNeed > 1 && buf.length > 1) {
187 + if ((buf[1] & 0xC0) !== 0x80) {
188 + self.lastNeed = 1;
189 + return '\ufffd';
190 + }
191 + if (self.lastNeed > 2 && buf.length > 2) {
192 + if ((buf[2] & 0xC0) !== 0x80) {
193 + self.lastNeed = 2;
194 + return '\ufffd';
195 + }
196 + }
197 + }
198 +}
199 +
200 +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
201 +function utf8FillLast(buf) {
202 + var p = this.lastTotal - this.lastNeed;
203 + var r = utf8CheckExtraBytes(this, buf, p);
204 + if (r !== undefined) return r;
205 + if (this.lastNeed <= buf.length) {
206 + buf.copy(this.lastChar, p, 0, this.lastNeed);
207 + return this.lastChar.toString(this.encoding, 0, this.lastTotal);
208 + }
209 + buf.copy(this.lastChar, p, 0, buf.length);
210 + this.lastNeed -= buf.length;
211 +}
212 +
213 +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
214 +// partial character, the character's bytes are buffered until the required
215 +// number of bytes are available.
216 +function utf8Text(buf, i) {
217 + var total = utf8CheckIncomplete(this, buf, i);
218 + if (!this.lastNeed) return buf.toString('utf8', i);
219 + this.lastTotal = total;
220 + var end = buf.length - (total - this.lastNeed);
221 + buf.copy(this.lastChar, 0, end);
222 + return buf.toString('utf8', i, end);
223 +}
224 +
225 +// For UTF-8, a replacement character is added when ending on a partial
226 +// character.
227 +function utf8End(buf) {
228 + var r = buf && buf.length ? this.write(buf) : '';
229 + if (this.lastNeed) return r + '\ufffd';
230 + return r;
231 +}
232 +
233 +// UTF-16LE typically needs two bytes per character, but even if we have an even
234 +// number of bytes available, we need to check if we end on a leading/high
235 +// surrogate. In that case, we need to wait for the next two bytes in order to
236 +// decode the last character properly.
237 +function utf16Text(buf, i) {
238 + if ((buf.length - i) % 2 === 0) {
239 + var r = buf.toString('utf16le', i);
240 + if (r) {
241 + var c = r.charCodeAt(r.length - 1);
242 + if (c >= 0xD800 && c <= 0xDBFF) {
243 + this.lastNeed = 2;
244 + this.lastTotal = 4;
245 + this.lastChar[0] = buf[buf.length - 2];
246 + this.lastChar[1] = buf[buf.length - 1];
247 + return r.slice(0, -1);
248 + }
249 + }
250 + return r;
251 + }
252 + this.lastNeed = 1;
253 + this.lastTotal = 2;
254 + this.lastChar[0] = buf[buf.length - 1];
255 + return buf.toString('utf16le', i, buf.length - 1);
256 +}
257 +
258 +// For UTF-16LE we do not explicitly append special replacement characters if we
259 +// end on a partial character, we simply let v8 handle that.
260 +function utf16End(buf) {
261 + var r = buf && buf.length ? this.write(buf) : '';
262 + if (this.lastNeed) {
263 + var end = this.lastTotal - this.lastNeed;
264 + return r + this.lastChar.toString('utf16le', 0, end);
265 + }
266 + return r;
267 +}
268 +
269 +function base64Text(buf, i) {
270 + var n = (buf.length - i) % 3;
271 + if (n === 0) return buf.toString('base64', i);
272 + this.lastNeed = 3 - n;
273 + this.lastTotal = 3;
274 + if (n === 1) {
275 + this.lastChar[0] = buf[buf.length - 1];
276 + } else {
277 + this.lastChar[0] = buf[buf.length - 2];
278 + this.lastChar[1] = buf[buf.length - 1];
279 + }
280 + return buf.toString('base64', i, buf.length - n);
281 +}
282 +
283 +function base64End(buf) {
284 + var r = buf && buf.length ? this.write(buf) : '';
285 + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
286 + return r;
287 +}
288 +
289 +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
290 +function simpleWrite(buf) {
291 + return buf.toString(this.encoding);
292 +}
293 +
294 +function simpleEnd(buf) {
295 + return buf && buf.length ? this.write(buf) : '';
296 +}
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "_from": "string_decoder@~1.1.1",
3 + "_id": "string_decoder@1.1.1",
4 + "_inBundle": false,
5 + "_integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
6 + "_location": "/string_decoder",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "string_decoder@~1.1.1",
12 + "name": "string_decoder",
13 + "escapedName": "string_decoder",
14 + "rawSpec": "~1.1.1",
15 + "saveSpec": null,
16 + "fetchSpec": "~1.1.1"
17 + },
18 + "_requiredBy": [
19 + "/readable-stream"
20 + ],
21 + "_resolved": "http://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
22 + "_shasum": "9cf1611ba62685d7030ae9e4ba34149c3af03fc8",
23 + "_spec": "string_decoder@~1.1.1",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/readable-stream",
25 + "bugs": {
26 + "url": "https://github.com/nodejs/string_decoder/issues"
27 + },
28 + "bundleDependencies": false,
29 + "dependencies": {
30 + "safe-buffer": "~5.1.0"
31 + },
32 + "deprecated": false,
33 + "description": "The string_decoder module from Node core",
34 + "devDependencies": {
35 + "babel-polyfill": "^6.23.0",
36 + "core-util-is": "^1.0.2",
37 + "inherits": "^2.0.3",
38 + "tap": "~0.4.8"
39 + },
40 + "homepage": "https://github.com/nodejs/string_decoder",
41 + "keywords": [
42 + "string",
43 + "decoder",
44 + "browser",
45 + "browserify"
46 + ],
47 + "license": "MIT",
48 + "main": "lib/string_decoder.js",
49 + "name": "string_decoder",
50 + "repository": {
51 + "type": "git",
52 + "url": "git://github.com/nodejs/string_decoder.git"
53 + },
54 + "scripts": {
55 + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js",
56 + "test": "tap test/parallel/*.js && node test/verify-dependencies"
57 + },
58 + "version": "1.1.1"
59 +}
1 +
2 +1.0.2 / 2015-10-07
3 +==================
4 +
5 + * use try/catch when checking `localStorage` (#3, @kumavis)
6 +
7 +1.0.1 / 2014-11-25
8 +==================
9 +
10 + * browser: use `console.warn()` for deprecation calls
11 + * browser: more jsdocs
12 +
13 +1.0.0 / 2014-04-30
14 +==================
15 +
16 + * initial commit
1 +(The MIT License)
2 +
3 +Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net>
4 +
5 +Permission is hereby granted, free of charge, to any person
6 +obtaining a copy of this software and associated documentation
7 +files (the "Software"), to deal in the Software without
8 +restriction, including without limitation the rights to use,
9 +copy, modify, merge, publish, distribute, sublicense, and/or sell
10 +copies of the Software, and to permit persons to whom the
11 +Software is furnished to do so, subject to the following
12 +conditions:
13 +
14 +The above copyright notice and this permission notice shall be
15 +included in all copies or substantial portions of the Software.
16 +
17 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19 +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21 +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22 +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 +OTHER DEALINGS IN THE SOFTWARE.
1 +util-deprecate
2 +==============
3 +### The Node.js `util.deprecate()` function with browser support
4 +
5 +In Node.js, this module simply re-exports the `util.deprecate()` function.
6 +
7 +In the web browser (i.e. via browserify), a browser-specific implementation
8 +of the `util.deprecate()` function is used.
9 +
10 +
11 +## API
12 +
13 +A `deprecate()` function is the only thing exposed by this module.
14 +
15 +``` javascript
16 +// setup:
17 +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead');
18 +
19 +
20 +// users see:
21 +foo();
22 +// foo() is deprecated, use bar() instead
23 +foo();
24 +foo();
25 +```
26 +
27 +
28 +## License
29 +
30 +(The MIT License)
31 +
32 +Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net>
33 +
34 +Permission is hereby granted, free of charge, to any person
35 +obtaining a copy of this software and associated documentation
36 +files (the "Software"), to deal in the Software without
37 +restriction, including without limitation the rights to use,
38 +copy, modify, merge, publish, distribute, sublicense, and/or sell
39 +copies of the Software, and to permit persons to whom the
40 +Software is furnished to do so, subject to the following
41 +conditions:
42 +
43 +The above copyright notice and this permission notice shall be
44 +included in all copies or substantial portions of the Software.
45 +
46 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
47 +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
48 +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
49 +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
50 +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
51 +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
52 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
53 +OTHER DEALINGS IN THE SOFTWARE.
1 +
2 +/**
3 + * Module exports.
4 + */
5 +
6 +module.exports = deprecate;
7 +
8 +/**
9 + * Mark that a method should not be used.
10 + * Returns a modified function which warns once by default.
11 + *
12 + * If `localStorage.noDeprecation = true` is set, then it is a no-op.
13 + *
14 + * If `localStorage.throwDeprecation = true` is set, then deprecated functions
15 + * will throw an Error when invoked.
16 + *
17 + * If `localStorage.traceDeprecation = true` is set, then deprecated functions
18 + * will invoke `console.trace()` instead of `console.error()`.
19 + *
20 + * @param {Function} fn - the function to deprecate
21 + * @param {String} msg - the string to print to the console when `fn` is invoked
22 + * @returns {Function} a new "deprecated" version of `fn`
23 + * @api public
24 + */
25 +
26 +function deprecate (fn, msg) {
27 + if (config('noDeprecation')) {
28 + return fn;
29 + }
30 +
31 + var warned = false;
32 + function deprecated() {
33 + if (!warned) {
34 + if (config('throwDeprecation')) {
35 + throw new Error(msg);
36 + } else if (config('traceDeprecation')) {
37 + console.trace(msg);
38 + } else {
39 + console.warn(msg);
40 + }
41 + warned = true;
42 + }
43 + return fn.apply(this, arguments);
44 + }
45 +
46 + return deprecated;
47 +}
48 +
49 +/**
50 + * Checks `localStorage` for boolean values for the given `name`.
51 + *
52 + * @param {String} name
53 + * @returns {Boolean}
54 + * @api private
55 + */
56 +
57 +function config (name) {
58 + // accessing global.localStorage can trigger a DOMException in sandboxed iframes
59 + try {
60 + if (!global.localStorage) return false;
61 + } catch (_) {
62 + return false;
63 + }
64 + var val = global.localStorage[name];
65 + if (null == val) return false;
66 + return String(val).toLowerCase() === 'true';
67 +}
1 +
2 +/**
3 + * For Node.js, simply re-export the core `util.deprecate` function.
4 + */
5 +
6 +module.exports = require('util').deprecate;
1 +{
2 + "_from": "util-deprecate@~1.0.1",
3 + "_id": "util-deprecate@1.0.2",
4 + "_inBundle": false,
5 + "_integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=",
6 + "_location": "/util-deprecate",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "util-deprecate@~1.0.1",
12 + "name": "util-deprecate",
13 + "escapedName": "util-deprecate",
14 + "rawSpec": "~1.0.1",
15 + "saveSpec": null,
16 + "fetchSpec": "~1.0.1"
17 + },
18 + "_requiredBy": [
19 + "/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
22 + "_shasum": "450d4dc9fa70de732762fbd2d4a28981419a0ccf",
23 + "_spec": "util-deprecate@~1.0.1",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/readable-stream",
25 + "author": {
26 + "name": "Nathan Rajlich",
27 + "email": "nathan@tootallnate.net",
28 + "url": "http://n8.io/"
29 + },
30 + "browser": "browser.js",
31 + "bugs": {
32 + "url": "https://github.com/TooTallNate/util-deprecate/issues"
33 + },
34 + "bundleDependencies": false,
35 + "deprecated": false,
36 + "description": "The Node.js `util.deprecate()` function with browser support",
37 + "homepage": "https://github.com/TooTallNate/util-deprecate",
38 + "keywords": [
39 + "util",
40 + "deprecate",
41 + "browserify",
42 + "browser",
43 + "node"
44 + ],
45 + "license": "MIT",
46 + "main": "node.js",
47 + "name": "util-deprecate",
48 + "repository": {
49 + "type": "git",
50 + "url": "git://github.com/TooTallNate/util-deprecate.git"
51 + },
52 + "scripts": {
53 + "test": "echo \"Error: no test specified\" && exit 1"
54 + },
55 + "version": "1.0.2"
56 +}
...@@ -4,6 +4,24 @@ ...@@ -4,6 +4,24 @@
4 "lockfileVersion": 1, 4 "lockfileVersion": 1,
5 "requires": true, 5 "requires": true,
6 "dependencies": { 6 "dependencies": {
7 + "@types/bluebird": {
8 + "version": "3.5.24",
9 + "resolved": "https://registry.npmjs.org/@types/bluebird/-/bluebird-3.5.24.tgz",
10 + "integrity": "sha512-YeQoDpq4Lm8ppSBqAnAeF/xy1cYp/dMTif2JFcvmAbETMRlvKHT2iLcWu+WyYiJO3b3Ivokwo7EQca/xfLVJmg=="
11 + },
12 + "@types/mysql": {
13 + "version": "2.15.5",
14 + "resolved": "https://registry.npmjs.org/@types/mysql/-/mysql-2.15.5.tgz",
15 + "integrity": "sha512-4QAISTUGZbcFh7bqdndo08xRdES5OTU+JODy8VCZbe1yiXyGjqw1H83G43XjQ3IbC10wn9xlGd44A5RXJwNh0Q==",
16 + "requires": {
17 + "@types/node": "*"
18 + }
19 + },
20 + "@types/node": {
21 + "version": "10.12.15",
22 + "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.15.tgz",
23 + "integrity": "sha512-9kROxduaN98QghwwHmxXO2Xz3MaWf+I1sLVAA6KJDF5xix+IyXVhds0MAfdNwtcpSrzhaTsNB0/jnL86fgUhqA=="
24 + },
7 "accepts": { 25 "accepts": {
8 "version": "1.3.5", 26 "version": "1.3.5",
9 "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz", 27 "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz",
...@@ -26,6 +44,16 @@ ...@@ -26,6 +44,16 @@
26 "safe-buffer": "5.1.2" 44 "safe-buffer": "5.1.2"
27 } 45 }
28 }, 46 },
47 + "bignumber.js": {
48 + "version": "4.1.0",
49 + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz",
50 + "integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA=="
51 + },
52 + "bluebird": {
53 + "version": "3.5.3",
54 + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.3.tgz",
55 + "integrity": "sha512-/qKPUQlaW1OyR51WeCPBvRnAlnZFUJkCSG5HzGnuIqhgyJtF+T94lFnn33eiazjRm2LAHVy2guNnaq48X9SJuw=="
56 + },
29 "body-parser": { 57 "body-parser": {
30 "version": "1.18.3", 58 "version": "1.18.3",
31 "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.3.tgz", 59 "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.3.tgz",
...@@ -77,6 +105,11 @@ ...@@ -77,6 +105,11 @@
77 "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", 105 "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
78 "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" 106 "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
79 }, 107 },
108 + "core-util-is": {
109 + "version": "1.0.2",
110 + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
111 + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="
112 + },
80 "debug": { 113 "debug": {
81 "version": "2.6.9", 114 "version": "2.6.9",
82 "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", 115 "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
...@@ -205,6 +238,11 @@ ...@@ -205,6 +238,11 @@
205 "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.8.0.tgz", 238 "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.8.0.tgz",
206 "integrity": "sha1-6qM9bd16zo9/b+DJygRA5wZzix4=" 239 "integrity": "sha1-6qM9bd16zo9/b+DJygRA5wZzix4="
207 }, 240 },
241 + "isarray": {
242 + "version": "1.0.0",
243 + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
244 + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
245 + },
208 "media-typer": { 246 "media-typer": {
209 "version": "0.3.0", 247 "version": "0.3.0",
210 "resolved": "http://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", 248 "resolved": "http://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
...@@ -255,6 +293,17 @@ ...@@ -255,6 +293,17 @@
255 "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", 293 "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
256 "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" 294 "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
257 }, 295 },
296 + "mysql": {
297 + "version": "2.16.0",
298 + "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.16.0.tgz",
299 + "integrity": "sha512-dPbN2LHonQp7D5ja5DJXNbCLe/HRdu+f3v61aguzNRQIrmZLOeRoymBYyeThrR6ug+FqzDL95Gc9maqZUJS+Gw==",
300 + "requires": {
301 + "bignumber.js": "4.1.0",
302 + "readable-stream": "2.3.6",
303 + "safe-buffer": "5.1.2",
304 + "sqlstring": "2.3.1"
305 + }
306 + },
258 "negotiator": { 307 "negotiator": {
259 "version": "0.6.1", 308 "version": "0.6.1",
260 "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz", 309 "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz",
...@@ -283,6 +332,22 @@ ...@@ -283,6 +332,22 @@
283 "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", 332 "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
284 "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" 333 "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w="
285 }, 334 },
335 + "process-nextick-args": {
336 + "version": "2.0.0",
337 + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz",
338 + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw=="
339 + },
340 + "promise-mysql": {
341 + "version": "3.3.1",
342 + "resolved": "https://registry.npmjs.org/promise-mysql/-/promise-mysql-3.3.1.tgz",
343 + "integrity": "sha512-PE+J6TtAqMJpdREvSphKvd+pn0IgGiLgxaDBb12oZNBR1VSxYSzknveuiSBmkptZC1ZDRwU+zBxBJeBgGFkCRA==",
344 + "requires": {
345 + "@types/bluebird": "^3.5.19",
346 + "@types/mysql": "^2.15.2",
347 + "bluebird": "^3.5.0",
348 + "mysql": "^2.14.1"
349 + }
350 + },
286 "proxy-addr": { 351 "proxy-addr": {
287 "version": "2.0.4", 352 "version": "2.0.4",
288 "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.4.tgz", 353 "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.4.tgz",
...@@ -313,6 +378,20 @@ ...@@ -313,6 +378,20 @@
313 "unpipe": "1.0.0" 378 "unpipe": "1.0.0"
314 } 379 }
315 }, 380 },
381 + "readable-stream": {
382 + "version": "2.3.6",
383 + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz",
384 + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==",
385 + "requires": {
386 + "core-util-is": "~1.0.0",
387 + "inherits": "~2.0.3",
388 + "isarray": "~1.0.0",
389 + "process-nextick-args": "~2.0.0",
390 + "safe-buffer": "~5.1.1",
391 + "string_decoder": "~1.1.1",
392 + "util-deprecate": "~1.0.1"
393 + }
394 + },
316 "safe-buffer": { 395 "safe-buffer": {
317 "version": "5.1.2", 396 "version": "5.1.2",
318 "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", 397 "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
...@@ -359,11 +438,24 @@ ...@@ -359,11 +438,24 @@
359 "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", 438 "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz",
360 "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==" 439 "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ=="
361 }, 440 },
441 + "sqlstring": {
442 + "version": "2.3.1",
443 + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz",
444 + "integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A="
445 + },
362 "statuses": { 446 "statuses": {
363 "version": "1.4.0", 447 "version": "1.4.0",
364 "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz", 448 "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz",
365 "integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==" 449 "integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew=="
366 }, 450 },
451 + "string_decoder": {
452 + "version": "1.1.1",
453 + "resolved": "http://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
454 + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
455 + "requires": {
456 + "safe-buffer": "~5.1.0"
457 + }
458 + },
367 "type-is": { 459 "type-is": {
368 "version": "1.6.16", 460 "version": "1.6.16",
369 "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz", 461 "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz",
...@@ -378,6 +470,11 @@ ...@@ -378,6 +470,11 @@
378 "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", 470 "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
379 "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" 471 "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw="
380 }, 472 },
473 + "util-deprecate": {
474 + "version": "1.0.2",
475 + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
476 + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8="
477 + },
381 "utils-merge": { 478 "utils-merge": {
382 "version": "1.0.1", 479 "version": "1.0.1",
383 "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", 480 "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
9 "cookie-parser": "~1.4.3", 9 "cookie-parser": "~1.4.3",
10 "debug": "~2.6.9", 10 "debug": "~2.6.9",
11 "express": "~4.16.0", 11 "express": "~4.16.0",
12 - "morgan": "~1.9.0" 12 + "morgan": "~1.9.0",
13 + "promise-mysql": "^3.3.1"
13 } 14 }
14 } 15 }
......
...@@ -70,13 +70,6 @@ ...@@ -70,13 +70,6 @@
70 </a> 70 </a>
71 </li> 71 </li>
72 72
73 - <li class="nav-item">
74 - <a class="nav-link" href="Favorite.html">
75 - <i class="fas fa-heart"></i>
76 - <span>Favorite</span>
77 - </a>
78 - </li>
79 -
80 73
81 </ul> 74 </ul>
82 <div id="content-wrapper"> 75 <div id="content-wrapper">
......
1 -<!DOCTYPE html>
2 -<html lang="en">
3 -
4 - <head>
5 -
6 - <meta charset="utf-8">
7 - <meta http-equiv="X-UA-Compatible" content="IE=edge">
8 - <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
9 - <meta name="description" content="">
10 - <meta name="author" content="">
11 -
12 - <title>저기어때</title>
13 -
14 - <!-- Bootstrap core CSS-->
15 - <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
16 -
17 - <!-- Custom fonts for this template-->
18 - <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
19 -
20 - <!-- Page level plugin CSS-->
21 - <link href="vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet">
22 -
23 - <!-- Custom styles for this template-->
24 - <link href="css/sb-admin.css" rel="stylesheet">
25 -
26 - </head>
27 -
28 - <body id="page-top">
29 -
30 - <nav class="navbar navbar-expand navbar-dark bg-dark static-top">
31 -
32 - <a class="navbar-brand mr-1" href="index.html">저기어때</a>
33 -
34 - <button class="btn btn-link btn-sm text-white order-1 order-sm-0" id="sidebarToggle" href="#">
35 - <i class="fas fa-bars"></i>
36 - </button>
37 -
38 - </nav>
39 -
40 - <div id="wrapper">
41 -
42 - <!-- Sidebar -->
43 - <ul class="sidebar navbar-nav">
44 -
45 - <li class="nav-item">
46 - <a class="nav-link" href="index.html">
47 - <i class="fas fa-map-marker"></i>
48 - <span>Map</span>
49 - </a>
50 - </li>
51 -
52 - <li class="nav-item">
53 - <a class="nav-link" href="Foods.html">
54 - <i class="fas fa-utensils" area-hidden ="true"></i>
55 - <span>Foods</span>
56 - </a>
57 - </li>
58 -
59 - <li class="nav-item">
60 - <a class="nav-link" href="Entertainment.html">
61 - <i class="fas fa-gamepad"></i>
62 - <span>Entertainment</span>
63 - </a>
64 - </li>
65 -
66 - <li class="nav-item">
67 - <a class="nav-link" href="Rooms.html">
68 - <i class="fas fa-bed"></i>
69 - <span>Rooms</span>
70 - </a>
71 - </li>
72 -
73 - <li class="nav-item active">
74 - <a class="nav-link" href="Favorite.html">
75 - <i class="fas fa-heart"></i>
76 - <span>Favorite</span>
77 - </a>
78 - </li>
79 -
80 -
81 - </ul>
82 - <div id="content-wrapper">
83 -
84 - <div class="container-fluid">
85 -
86 - <!-- Breadcrumbs-->
87 - <ol class="breadcrumb">
88 - <li class="breadcrumb-item">
89 - <a href="#">Favorite</a>
90 - </li>
91 -
92 - </ol>
93 -
94 - <!-- Icon Cards-->
95 - <div class="row">
96 - <div class="col-xl-3 col-sm-6 mb-3">
97 - <div class="card text-white bg-primary o-hidden h-100">
98 - <div class="card-body">
99 - <div class="card-body-icon">
100 - <i class="fas fa-fw fa-comments"></i>
101 - </div>
102 - <div class="mr-5">26 New Messages!</div>
103 - </div>
104 - <a class="card-footer text-white clearfix small z-1" href="#">
105 - <span class="float-left">View Details</span>
106 - <span class="float-right">
107 - <i class="fas fa-angle-right"></i>
108 - </span>
109 - </a>
110 - </div>
111 - </div>
112 - <div class="col-xl-3 col-sm-6 mb-3">
113 - <div class="card text-white bg-warning o-hidden h-100">
114 - <div class="card-body">
115 - <div class="card-body-icon">
116 - <i class="fas fa-fw fa-list"></i>
117 - </div>
118 - <div class="mr-5">11 New Tasks!</div>
119 - </div>
120 - <a class="card-footer text-white clearfix small z-1" href="#">
121 - <span class="float-left">View Details</span>
122 - <span class="float-right">
123 - <i class="fas fa-angle-right"></i>
124 - </span>
125 - </a>
126 - </div>
127 - </div>
128 - <div class="col-xl-3 col-sm-6 mb-3">
129 - <div class="card text-white bg-success o-hidden h-100">
130 - <div class="card-body">
131 - <div class="card-body-icon">
132 - <i class="fas fa-fw fa-shopping-cart"></i>
133 - </div>
134 - <div class="mr-5">123 New Orders!</div>
135 - </div>
136 - <a class="card-footer text-white clearfix small z-1" href="#">
137 - <span class="float-left">View Details</span>
138 - <span class="float-right">
139 - <i class="fas fa-angle-right"></i>
140 - </span>
141 - </a>
142 - </div>
143 - </div>
144 - <div class="col-xl-3 col-sm-6 mb-3">
145 - <div class="card text-white bg-danger o-hidden h-100">
146 - <div class="card-body">
147 - <div class="card-body-icon">
148 - <i class="fas fa-fw fa-life-ring"></i>
149 - </div>
150 - <div class="mr-5">13 New Tickets!</div>
151 - </div>
152 - <a class="card-footer text-white clearfix small z-1" href="#">
153 - <span class="float-left">View Details</span>
154 - <span class="float-right">
155 - <i class="fas fa-angle-right"></i>
156 - </span>
157 - </a>
158 - </div>
159 - </div>
160 - </div>
161 -
162 - <p class="small text-center text-muted my-5">
163 - <em>More chart examples coming soon...</em>
164 - </p>
165 -
166 - </div>
167 - <!-- /.container-fluid -->
168 -
169 - <!-- Sticky Footer -->
170 - <footer class="sticky-footer">
171 - <div class="container my-auto">
172 - <div class="copyright text-center my-auto">
173 - <span>Copyright © Your Website 2018</span>
174 - </div>
175 - </div>
176 - </footer>
177 -
178 - </div>
179 - <!-- /.content-wrapper -->
180 -
181 - </div>
182 - <!-- /#wrapper -->
183 -
184 - <!-- Scroll to Top Button-->
185 - <a class="scroll-to-top rounded" href="#page-top">
186 - <i class="fas fa-angle-up"></i>
187 - </a>
188 -
189 -
190 -
191 - <!-- Bootstrap core JavaScript-->
192 - <script src="vendor/jquery/jquery.min.js"></script>
193 - <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
194 -
195 - <!-- Core plugin JavaScript-->
196 - <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
197 -
198 - <!-- Page level plugin JavaScript-->
199 - <script src="vendor/chart.js/Chart.min.js"></script>
200 -
201 - <!-- Custom scripts for all pages-->
202 - <script src="js/sb-admin.min.js"></script>
203 -
204 - <!-- Demo scripts for this page-->
205 - <script src="js/demo/chart-area-demo.js"></script>
206 - <script src="js/demo/chart-bar-demo.js"></script>
207 - <script src="js/demo/chart-pie-demo.js"></script>
208 -
209 - </body>
210 -
211 -</html>
...@@ -71,14 +71,6 @@ ...@@ -71,14 +71,6 @@
71 </a> 71 </a>
72 </li> 72 </li>
73 73
74 - <li class="nav-item">
75 - <a class="nav-link" href="Favorite.html">
76 - <i class="fas fa-heart"></i>
77 - <span>Favorite</span>
78 - </a>
79 - </li>
80 -
81 -
82 </ul> 74 </ul>
83 <div id="content-wrapper"> 75 <div id="content-wrapper">
84 76
...@@ -93,71 +85,19 @@ ...@@ -93,71 +85,19 @@
93 </ol> 85 </ol>
94 86
95 <!-- Icon Cards--> 87 <!-- Icon Cards-->
96 - <div class="row"> 88 + <div class="row" id="body">
97 - <div class="col-xl-3 col-sm-6 mb-3"> 89 + <!--<script>
98 - <div class="card text-white bg-primary o-hidden h-100"> 90 +
99 - <div class="card-body"> 91 + var queryString = decodeURIComponent(window.location.search);
100 - <div class="card-body-icon"> 92 + queryString = queryString.substring(1);
101 - <i class="fas fa-fw fa-comments"></i> 93 + var queries = queryString.split("&");
102 - </div> 94 + for (var i = 0; i < queries.length; i++)
103 - <div class="mr-5">26 New Messages!</div> 95 + {
104 - </div> 96 + document.write(queries[i] + "<br>");
105 - <a class="card-footer text-white clearfix small z-1" href="#"> 97 + }
106 - <span class="float-left">View Details</span> 98 +
107 - <span class="float-right"> 99 + </script>-->
108 - <i class="fas fa-angle-right"></i> 100 + <script src="js/showFood.js"></script>
109 - </span>
110 - </a>
111 - </div>
112 - </div>
113 - <div class="col-xl-3 col-sm-6 mb-3">
114 - <div class="card text-white bg-warning o-hidden h-100">
115 - <div class="card-body">
116 - <div class="card-body-icon">
117 - <i class="fas fa-fw fa-list"></i>
118 - </div>
119 - <div class="mr-5">11 New Tasks!</div>
120 - </div>
121 - <a class="card-footer text-white clearfix small z-1" href="#">
122 - <span class="float-left">View Details</span>
123 - <span class="float-right">
124 - <i class="fas fa-angle-right"></i>
125 - </span>
126 - </a>
127 - </div>
128 - </div>
129 - <div class="col-xl-3 col-sm-6 mb-3">
130 - <div class="card text-white bg-success o-hidden h-100">
131 - <div class="card-body">
132 - <div class="card-body-icon">
133 - <i class="fas fa-fw fa-shopping-cart"></i>
134 - </div>
135 - <div class="mr-5">123 New Orders!</div>
136 - </div>
137 - <a class="card-footer text-white clearfix small z-1" href="#">
138 - <span class="float-left">View Details</span>
139 - <span class="float-right">
140 - <i class="fas fa-angle-right"></i>
141 - </span>
142 - </a>
143 - </div>
144 - </div>
145 - <div class="col-xl-3 col-sm-6 mb-3">
146 - <div class="card text-white bg-danger o-hidden h-100">
147 - <div class="card-body">
148 - <div class="card-body-icon">
149 - <i class="fas fa-fw fa-life-ring"></i>
150 - </div>
151 - <div class="mr-5">13 New Tickets!</div>
152 - </div>
153 - <a class="card-footer text-white clearfix small z-1" href="#">
154 - <span class="float-left">View Details</span>
155 - <span class="float-right">
156 - <i class="fas fa-angle-right"></i>
157 - </span>
158 - </a>
159 - </div>
160 - </div>
161 </div> 101 </div>
162 102
163 <p class="small text-center text-muted my-5"> 103 <p class="small text-center text-muted my-5">
...@@ -187,8 +127,6 @@ ...@@ -187,8 +127,6 @@
187 <i class="fas fa-angle-up"></i> 127 <i class="fas fa-angle-up"></i>
188 </a> 128 </a>
189 129
190 -
191 -
192 <!-- Bootstrap core JavaScript--> 130 <!-- Bootstrap core JavaScript-->
193 <script src="vendor/jquery/jquery.min.js"></script> 131 <script src="vendor/jquery/jquery.min.js"></script>
194 <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> 132 <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
......
1 -# [Start Bootstrap - SB Admin](https://startbootstrap.com/template-overviews/sb-admin/) 1 +# 저기어때
2 -
3 -[SB Admin](http://startbootstrap.com/template-overviews/sb-admin/) is an open source, admin dashboard template for [Bootstrap](http://getbootstrap.com/) created by [Start Bootstrap](http://startbootstrap.com/).
4 2
5 ## Preview 3 ## Preview
6 -
7 -[![SB Admin Preview](https://startbootstrap.com/assets/img/templates/sb-admin.jpg)](https://blackrockdigital.github.io/startbootstrap-sb-admin/)
8 -
9 -**[View Live Preview](https://blackrockdigital.github.io/startbootstrap-sb-admin/)**
10 -
11 -## Status
12 -
13 -[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/BlackrockDigital/startbootstrap-sb-admin/master/LICENSE)
14 -[![npm version](https://img.shields.io/npm/v/startbootstrap-sb-admin.svg)](https://www.npmjs.com/package/startbootstrap-sb-admin)
15 -[![Build Status](https://travis-ci.org/BlackrockDigital/startbootstrap-sb-admin.svg?branch=master)](https://travis-ci.org/BlackrockDigital/startbootstrap-sb-admin)
16 -[![dependencies Status](https://david-dm.org/BlackrockDigital/startbootstrap-sb-admin/status.svg)](https://david-dm.org/BlackrockDigital/startbootstrap-sb-admin)
17 -[![devDependencies Status](https://david-dm.org/BlackrockDigital/startbootstrap-sb-admin/dev-status.svg)](https://david-dm.org/BlackrockDigital/startbootstrap-sb-admin?type=dev)
18 -
19 -## Download and Installation
20 -
21 -To begin using this template, choose one of the following options to get started:
22 -* [Download the latest release on Start Bootstrap](https://startbootstrap.com/template-overviews/sb-admin/)
23 -* Install via npm: `npm i startbootstrap-sb-admin`
24 -* Clone the repo: `git clone https://github.com/BlackrockDigital/startbootstrap-sb-admin.git`
25 -* [Fork, Clone, or Download on GitHub](https://github.com/BlackrockDigital/startbootstrap-sb-admin)
26 -
27 -## Usage
28 -
29 -### Basic Usage
30 -
31 -After downloading, simply edit the HTML and CSS files included with the template in your favorite text editor to make changes. These are the only files you need to worry about, you can ignore everything else! To preview the changes you make to the code, you can open the `index.html` file in your web browser.
32 -
33 -### Advanced Usage
34 -
35 -After installation, run `npm install` and then run `gulp dev` which will open up a preview of the template in your default browser, watch for changes to core template files, and live reload the browser when changes are saved. You can view the `gulpfile.js` to see which tasks are included with the dev environment.
36 -
37 -#### Gulp Tasks
38 -
39 -- `gulp` the default task that builds everything
40 -- `gulp dev` browserSync opens the project in your default browser and live reloads when changes are made
41 -- `gulp css` compiles SCSS files into CSS and minifies the compiled CSS
42 -- `gulp js` minifies the themes JS file
43 -- `gulp vendor` copies dependencies from node_modules to the vendor directory
44 -
45 -## Bugs and Issues
46 -
47 -Have a bug or an issue with this template? [Open a new issue](https://github.com/BlackrockDigital/startbootstrap-sb-admin/issues) here on GitHub or leave a comment on the [template overview page at Start Bootstrap](http://startbootstrap.com/template-overviews/sb-admin/).
48 -
49 -## Custom Builds
50 -
51 -You can hire Start Bootstrap to create a custom build of any template, or create something from scratch using Bootstrap. For more information, visit the **[custom design services page](https://startbootstrap.com/bootstrap-design-services/)**.
52 -
53 -## About
54 -
55 -Start Bootstrap is an open source library of free Bootstrap templates and themes. All of the free templates and themes on Start Bootstrap are released under the MIT license, which means you can use them for any purpose, even for commercial projects.
56 -
57 -* https://startbootstrap.com
58 -* https://twitter.com/SBootstrap
59 -
60 -Start Bootstrap was created by and is maintained by **[David Miller](http://davidmiller.io/)**, Owner of [Blackrock Digital](http://blackrockdigital.io/).
61 -
62 -* http://davidmiller.io
63 -* https://twitter.com/davidmillerskt
64 -* https://github.com/davidtmiller
65 -
66 -Start Bootstrap is based on the [Bootstrap](http://getbootstrap.com/) framework created by [Mark Otto](https://twitter.com/mdo) and [Jacob Thorton](https://twitter.com/fat).
67 -
68 -## Copyright and License
69 -
70 -Copyright 2013-2018 Blackrock Digital LLC. Code released under the [MIT](https://github.com/BlackrockDigital/startbootstrap-sb-admin/blob/gh-pages/LICENSE) license.
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
9 <meta name="description" content=""> 9 <meta name="description" content="">
10 <meta name="author" content=""> 10 <meta name="author" content="">
11 11
12 - <title>저기어때</title> 12 + <title>뭐라도해</title>
13 13
14 <!-- Bootstrap core CSS--> 14 <!-- Bootstrap core CSS-->
15 <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> 15 <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
...@@ -70,13 +70,6 @@ ...@@ -70,13 +70,6 @@
70 </a> 70 </a>
71 </li> 71 </li>
72 72
73 - <li class="nav-item">
74 - <a class="nav-link" href="Favorite.html">
75 - <i class="fas fa-heart"></i>
76 - <span>Favorite</span>
77 - </a>
78 - </li>
79 -
80 73
81 </ul> 74 </ul>
82 <div id="content-wrapper"> 75 <div id="content-wrapper">
......
...@@ -372,4 +372,27 @@ body.sidebar-toggled footer.sticky-footer { ...@@ -372,4 +372,27 @@ body.sidebar-toggled footer.sticky-footer {
372 body.sidebar-toggled footer.sticky-footer { 372 body.sidebar-toggled footer.sticky-footer {
373 width: calc(100% - 90px); 373 width: calc(100% - 90px);
374 } 374 }
375 +
376 +#nameDiv
377 +{
378 + font-size: 50px;
379 + color: #ffffff;
380 + font-family: "Do Hyeon", sans-serif;
381 + -webkit-text-stroke-color: #000000;
382 + -webkit-text-stroke-width: 1.5px;
383 + position: absolute;
384 + top: 220px;
385 +}
386 +
387 +#typeDiv
388 +{
389 + font-size: 30px;
390 + color: #e9ecef;
391 + font-family: "Do Hyeon", sans-serif;
392 + -webkit-text-stroke-color: #000000;
393 + -webkit-text-stroke-width: 1.5px;
394 + position: absolute;
395 + top: 280px;
396 + left: 22px;
397 +}
375 } 398 }
......
...@@ -85,19 +85,18 @@ ...@@ -85,19 +85,18 @@
85 </a> 85 </a>
86 </li> 86 </li>
87 87
88 - <li class="nav-item">
89 - <a class="nav-link" href="Favorite.html">
90 - <i class="fas fa-heart"></i>
91 - <span>Favorite</span>
92 - </a>
93 - </li>
94 -
95 </ul> 88 </ul>
96 89
97 <div id="content-wrapper"> 90 <div id="content-wrapper">
98 - <script type="text/javascript" src="/../api/getPlaceList.js"></script> 91 + <script>
92 + var result_entertainment = []
93 + var result_food = []
94 + var result_room = []
95 + </script>
96 + <script type="text/javascript" src="/js/getPlaceList.js"></script>
99 <div id="map"></div> 97 <div id="map"></div>
100 <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDg4CkUEEt_96n1ork1nL5t4E_SpdKrgMI&libraries=places&callback=initMap" async defer></script> 98 <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDg4CkUEEt_96n1ork1nL5t4E_SpdKrgMI&libraries=places&callback=initMap" async defer></script>
99 +
101 <!-- Sticky Footer --> 100 <!-- Sticky Footer -->
102 <footer class="sticky-footer"> 101 <footer class="sticky-footer">
103 <div class="container my-auto"> 102 <div class="container my-auto">
......
1 +function searchPlace(str, placeType) {
2 + switch(placeType) {
3 + case 'food':
4 + service.nearbySearch({
5 + location: pos,
6 + radius: 500,
7 + type: [str]
8 + }, callback_foods);
9 + break;
10 + case 'entertainment':
11 + service.nearbySearch({
12 + location: pos,
13 + radius: 500,
14 + type: [str]
15 + }, callback_entertainment);
16 + break;
17 + case 'room':
18 + service.nearbySearch({
19 + location: pos,
20 + radius: 500,
21 + type: [str]
22 + }, callback_rooms);
23 + break;
24 + default:
25 + break;
26 + }
27 +}
28 +
29 +
30 +function callback_foods(results, status) {
31 + if (status === google.maps.places.PlacesServiceStatus.OK) {
32 + for (var i = 0; i < results.length; i++) {
33 + putDataToDB(results[i], 'food')
34 + createMarker_foods(results[i]);
35 + }
36 + }
37 +}
38 +
39 +function callback_entertainment(results, status) {
40 + if (status === google.maps.places.PlacesServiceStatus.OK) {
41 + for (var i = 0; i < results.length; i++) {
42 + putDataToDB(results[i], 'entertainment')
43 + createMarker_entertainment(results[i]);
44 + }
45 + }
46 +}
47 +
48 +function callback_rooms(results, status) {
49 + if (status === google.maps.places.PlacesServiceStatus.OK) {
50 + for (var i = 0; i < results.length; i++) {
51 + putDataToDB(results[i], 'room')
52 + createMarker_rooms(results[i]);
53 + }
54 + }
55 +}
56 +
57 +function createMarker_foods(place) {
58 + var marker = new google.maps.Marker({
59 + map: map,
60 + position: place.geometry.location,
61 + icon : "./icons/restaurant-15.svg",
62 + //fillcolor : "#FF0000"
63 + });
64 +
65 + google.maps.event.addListener(marker, 'click', function() {
66 + infowindow.setContent(place.name);
67 + infowindow.open(map, this);
68 + });
69 +}
70 +
71 +function createMarker_entertainment(place) {
72 + var placeLoc = place.geometry.location;
73 + var marker = new google.maps.Marker({
74 + map: map,
75 + position: place.geometry.location,
76 + icon : "./icons/gaming-15.svg"
77 + });
78 +
79 + google.maps.event.addListener(marker, 'click', function() {
80 + infowindow.setContent(place.name);
81 + infowindow.open(map, this);
82 + });
83 +}
84 +
85 +function createMarker_rooms(place) {
86 + var placeLoc = place.geometry.location;
87 + var marker = new google.maps.Marker({
88 + map: map,
89 + position: place.geometry.location,
90 + icon : "./icons/lodging-15.svg"
91 + });
92 +
93 + google.maps.event.addListener(marker, 'click', function() {
94 + infowindow.setContent(place.name);
95 + infowindow.open(map, this);
96 + });
97 +}
98 +
99 +function putDataToDB(result, category1) {
100 + const id = result['id'];
101 + const place_id =result['place_id'];
102 + const name = result['name'];
103 + const address = result['vicinity'];
104 + let category_big = category1
105 + const category_small = result.types[0];
106 + const image = "default"
107 + const rating = result.rating;
108 + const lng = result.geometry.viewport.ea.j;
109 + const lat =result.geometry.viewport.la.j;
1 +//import position from 'getPlaceList'
2 +
3 +var entName = '';
4 +var entType = '';
5 +var entPhoto = '';
6 +var card = '<div class="col-xl-6 col-sm-6 mb-3">'+
7 +'<div class="card text-white bg-light o-hidden h-100">'+
8 +'<div class="card-body"' + ' style="height:300px; background-size: 100% 100%; background-repeat: no-repeat; background-image:url(' + "'" + entPhoto + "');" + '">' + // place photo
9 +'<div class="mr-5" id="nameDiv">'+entName+'</div>'+ // place name
10 +'<div class="mr-5" id="typeDiv">'+entType+'</div>'+ // place type
11 +'</div>'+
12 +'</div>'+
13 +'</div>';
14 +
15 +
16 +for(var i=0; i<entList.size(); i++){
17 + entName = entList[i][name];
18 + entType = entList[i][type];
19 + if(entList[i][photo]==null){
20 + entPhoto = "noimage.png";
21 + }
22 + else{
23 + entPhoto = entList[i][photo];
24 + }
25 + card+=card;
26 +}
27 +document.getElementById("body").innerHTML=card;
...\ No newline at end of file ...\ No newline at end of file