UNPKG

206 kBJavaScriptView Raw
1/*!
2 * alpaca@6.3.19
3 * released under the permissive ISC license
4 */
5
6(function (global, factory) {
7 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('util')) :
8 typeof define === 'function' && define.amd ? define(['exports', 'util'], factory) :
9 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.alpaca = {}, global.require$$0$3));
10}(this, (function (exports, require$$0$3) { 'use strict';
11
12 function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
13
14 var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$3);
15
16 /* eslint complexity: [2, 18], max-statements: [2, 33] */
17 var shams = function hasSymbols() {
18 if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
19 if (typeof Symbol.iterator === 'symbol') { return true; }
20
21 var obj = {};
22 var sym = Symbol('test');
23 var symObj = Object(sym);
24 if (typeof sym === 'string') { return false; }
25
26 if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
27 if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
28
29 // temp disabled per https://github.com/ljharb/object.assign/issues/17
30 // if (sym instanceof Symbol) { return false; }
31 // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
32 // if (!(symObj instanceof Symbol)) { return false; }
33
34 // if (typeof Symbol.prototype.toString !== 'function') { return false; }
35 // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
36
37 var symVal = 42;
38 obj[sym] = symVal;
39 for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
40 if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
41
42 if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
43
44 var syms = Object.getOwnPropertySymbols(obj);
45 if (syms.length !== 1 || syms[0] !== sym) { return false; }
46
47 if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
48
49 if (typeof Object.getOwnPropertyDescriptor === 'function') {
50 var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
51 if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
52 }
53
54 return true;
55 };
56
57 var origSymbol = typeof Symbol !== 'undefined' && Symbol;
58
59
60 var hasSymbols$1 = function hasNativeSymbols() {
61 if (typeof origSymbol !== 'function') { return false; }
62 if (typeof Symbol !== 'function') { return false; }
63 if (typeof origSymbol('foo') !== 'symbol') { return false; }
64 if (typeof Symbol('bar') !== 'symbol') { return false; }
65
66 return shams();
67 };
68
69 /* eslint no-invalid-this: 1 */
70
71 var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
72 var slice = Array.prototype.slice;
73 var toStr$1 = Object.prototype.toString;
74 var funcType = '[object Function]';
75
76 var implementation = function bind(that) {
77 var target = this;
78 if (typeof target !== 'function' || toStr$1.call(target) !== funcType) {
79 throw new TypeError(ERROR_MESSAGE + target);
80 }
81 var args = slice.call(arguments, 1);
82
83 var bound;
84 var binder = function () {
85 if (this instanceof bound) {
86 var result = target.apply(
87 this,
88 args.concat(slice.call(arguments))
89 );
90 if (Object(result) === result) {
91 return result;
92 }
93 return this;
94 } else {
95 return target.apply(
96 that,
97 args.concat(slice.call(arguments))
98 );
99 }
100 };
101
102 var boundLength = Math.max(0, target.length - args.length);
103 var boundArgs = [];
104 for (var i = 0; i < boundLength; i++) {
105 boundArgs.push('$' + i);
106 }
107
108 bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
109
110 if (target.prototype) {
111 var Empty = function Empty() {};
112 Empty.prototype = target.prototype;
113 bound.prototype = new Empty();
114 Empty.prototype = null;
115 }
116
117 return bound;
118 };
119
120 var functionBind = Function.prototype.bind || implementation;
121
122 var src = functionBind.call(Function.call, Object.prototype.hasOwnProperty);
123
124 var undefined$1;
125
126 var $SyntaxError = SyntaxError;
127 var $Function = Function;
128 var $TypeError$1 = TypeError;
129
130 // eslint-disable-next-line consistent-return
131 var getEvalledConstructor = function (expressionSyntax) {
132 try {
133 return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
134 } catch (e) {}
135 };
136
137 var $gOPD = Object.getOwnPropertyDescriptor;
138 if ($gOPD) {
139 try {
140 $gOPD({}, '');
141 } catch (e) {
142 $gOPD = null; // this is IE 8, which has a broken gOPD
143 }
144 }
145
146 var throwTypeError = function () {
147 throw new $TypeError$1();
148 };
149 var ThrowTypeError = $gOPD
150 ? (function () {
151 try {
152 // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
153 arguments.callee; // IE 8 does not throw here
154 return throwTypeError;
155 } catch (calleeThrows) {
156 try {
157 // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
158 return $gOPD(arguments, 'callee').get;
159 } catch (gOPDthrows) {
160 return throwTypeError;
161 }
162 }
163 }())
164 : throwTypeError;
165
166 var hasSymbols = hasSymbols$1();
167
168 var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
169
170 var needsEval = {};
171
172 var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array);
173
174 var INTRINSICS = {
175 '%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError,
176 '%Array%': Array,
177 '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
178 '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined$1,
179 '%AsyncFromSyncIteratorPrototype%': undefined$1,
180 '%AsyncFunction%': needsEval,
181 '%AsyncGenerator%': needsEval,
182 '%AsyncGeneratorFunction%': needsEval,
183 '%AsyncIteratorPrototype%': needsEval,
184 '%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
185 '%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt,
186 '%Boolean%': Boolean,
187 '%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
188 '%Date%': Date,
189 '%decodeURI%': decodeURI,
190 '%decodeURIComponent%': decodeURIComponent,
191 '%encodeURI%': encodeURI,
192 '%encodeURIComponent%': encodeURIComponent,
193 '%Error%': Error,
194 '%eval%': eval, // eslint-disable-line no-eval
195 '%EvalError%': EvalError,
196 '%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
197 '%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
198 '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry,
199 '%Function%': $Function,
200 '%GeneratorFunction%': needsEval,
201 '%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
202 '%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
203 '%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
204 '%isFinite%': isFinite,
205 '%isNaN%': isNaN,
206 '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
207 '%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
208 '%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
209 '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
210 '%Math%': Math,
211 '%Number%': Number,
212 '%Object%': Object,
213 '%parseFloat%': parseFloat,
214 '%parseInt%': parseInt,
215 '%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
216 '%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
217 '%RangeError%': RangeError,
218 '%ReferenceError%': ReferenceError,
219 '%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
220 '%RegExp%': RegExp,
221 '%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
222 '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
223 '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
224 '%String%': String,
225 '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined$1,
226 '%Symbol%': hasSymbols ? Symbol : undefined$1,
227 '%SyntaxError%': $SyntaxError,
228 '%ThrowTypeError%': ThrowTypeError,
229 '%TypedArray%': TypedArray,
230 '%TypeError%': $TypeError$1,
231 '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
232 '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
233 '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
234 '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
235 '%URIError%': URIError,
236 '%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
237 '%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef,
238 '%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet
239 };
240
241 var doEval = function doEval(name) {
242 var value;
243 if (name === '%AsyncFunction%') {
244 value = getEvalledConstructor('async function () {}');
245 } else if (name === '%GeneratorFunction%') {
246 value = getEvalledConstructor('function* () {}');
247 } else if (name === '%AsyncGeneratorFunction%') {
248 value = getEvalledConstructor('async function* () {}');
249 } else if (name === '%AsyncGenerator%') {
250 var fn = doEval('%AsyncGeneratorFunction%');
251 if (fn) {
252 value = fn.prototype;
253 }
254 } else if (name === '%AsyncIteratorPrototype%') {
255 var gen = doEval('%AsyncGenerator%');
256 if (gen) {
257 value = getProto(gen.prototype);
258 }
259 }
260
261 INTRINSICS[name] = value;
262
263 return value;
264 };
265
266 var LEGACY_ALIASES = {
267 '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
268 '%ArrayPrototype%': ['Array', 'prototype'],
269 '%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
270 '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
271 '%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
272 '%ArrayProto_values%': ['Array', 'prototype', 'values'],
273 '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
274 '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
275 '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
276 '%BooleanPrototype%': ['Boolean', 'prototype'],
277 '%DataViewPrototype%': ['DataView', 'prototype'],
278 '%DatePrototype%': ['Date', 'prototype'],
279 '%ErrorPrototype%': ['Error', 'prototype'],
280 '%EvalErrorPrototype%': ['EvalError', 'prototype'],
281 '%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
282 '%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
283 '%FunctionPrototype%': ['Function', 'prototype'],
284 '%Generator%': ['GeneratorFunction', 'prototype'],
285 '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
286 '%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
287 '%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
288 '%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
289 '%JSONParse%': ['JSON', 'parse'],
290 '%JSONStringify%': ['JSON', 'stringify'],
291 '%MapPrototype%': ['Map', 'prototype'],
292 '%NumberPrototype%': ['Number', 'prototype'],
293 '%ObjectPrototype%': ['Object', 'prototype'],
294 '%ObjProto_toString%': ['Object', 'prototype', 'toString'],
295 '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
296 '%PromisePrototype%': ['Promise', 'prototype'],
297 '%PromiseProto_then%': ['Promise', 'prototype', 'then'],
298 '%Promise_all%': ['Promise', 'all'],
299 '%Promise_reject%': ['Promise', 'reject'],
300 '%Promise_resolve%': ['Promise', 'resolve'],
301 '%RangeErrorPrototype%': ['RangeError', 'prototype'],
302 '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
303 '%RegExpPrototype%': ['RegExp', 'prototype'],
304 '%SetPrototype%': ['Set', 'prototype'],
305 '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
306 '%StringPrototype%': ['String', 'prototype'],
307 '%SymbolPrototype%': ['Symbol', 'prototype'],
308 '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
309 '%TypedArrayPrototype%': ['TypedArray', 'prototype'],
310 '%TypeErrorPrototype%': ['TypeError', 'prototype'],
311 '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
312 '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
313 '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
314 '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
315 '%URIErrorPrototype%': ['URIError', 'prototype'],
316 '%WeakMapPrototype%': ['WeakMap', 'prototype'],
317 '%WeakSetPrototype%': ['WeakSet', 'prototype']
318 };
319
320
321
322 var $concat = functionBind.call(Function.call, Array.prototype.concat);
323 var $spliceApply = functionBind.call(Function.apply, Array.prototype.splice);
324 var $replace = functionBind.call(Function.call, String.prototype.replace);
325 var $strSlice = functionBind.call(Function.call, String.prototype.slice);
326
327 /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
328 var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
329 var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
330 var stringToPath = function stringToPath(string) {
331 var first = $strSlice(string, 0, 1);
332 var last = $strSlice(string, -1);
333 if (first === '%' && last !== '%') {
334 throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
335 } else if (last === '%' && first !== '%') {
336 throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
337 }
338 var result = [];
339 $replace(string, rePropName, function (match, number, quote, subString) {
340 result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
341 });
342 return result;
343 };
344 /* end adaptation */
345
346 var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
347 var intrinsicName = name;
348 var alias;
349 if (src(LEGACY_ALIASES, intrinsicName)) {
350 alias = LEGACY_ALIASES[intrinsicName];
351 intrinsicName = '%' + alias[0] + '%';
352 }
353
354 if (src(INTRINSICS, intrinsicName)) {
355 var value = INTRINSICS[intrinsicName];
356 if (value === needsEval) {
357 value = doEval(intrinsicName);
358 }
359 if (typeof value === 'undefined' && !allowMissing) {
360 throw new $TypeError$1('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
361 }
362
363 return {
364 alias: alias,
365 name: intrinsicName,
366 value: value
367 };
368 }
369
370 throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
371 };
372
373 var getIntrinsic = function GetIntrinsic(name, allowMissing) {
374 if (typeof name !== 'string' || name.length === 0) {
375 throw new $TypeError$1('intrinsic name must be a non-empty string');
376 }
377 if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
378 throw new $TypeError$1('"allowMissing" argument must be a boolean');
379 }
380
381 var parts = stringToPath(name);
382 var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
383
384 var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
385 var intrinsicRealName = intrinsic.name;
386 var value = intrinsic.value;
387 var skipFurtherCaching = false;
388
389 var alias = intrinsic.alias;
390 if (alias) {
391 intrinsicBaseName = alias[0];
392 $spliceApply(parts, $concat([0, 1], alias));
393 }
394
395 for (var i = 1, isOwn = true; i < parts.length; i += 1) {
396 var part = parts[i];
397 var first = $strSlice(part, 0, 1);
398 var last = $strSlice(part, -1);
399 if (
400 (
401 (first === '"' || first === "'" || first === '`')
402 || (last === '"' || last === "'" || last === '`')
403 )
404 && first !== last
405 ) {
406 throw new $SyntaxError('property names with quotes must have matching quotes');
407 }
408 if (part === 'constructor' || !isOwn) {
409 skipFurtherCaching = true;
410 }
411
412 intrinsicBaseName += '.' + part;
413 intrinsicRealName = '%' + intrinsicBaseName + '%';
414
415 if (src(INTRINSICS, intrinsicRealName)) {
416 value = INTRINSICS[intrinsicRealName];
417 } else if (value != null) {
418 if (!(part in value)) {
419 if (!allowMissing) {
420 throw new $TypeError$1('base intrinsic for ' + name + ' exists, but the property is not available.');
421 }
422 return void undefined$1;
423 }
424 if ($gOPD && (i + 1) >= parts.length) {
425 var desc = $gOPD(value, part);
426 isOwn = !!desc;
427
428 // By convention, when a data property is converted to an accessor
429 // property to emulate a data property that does not suffer from
430 // the override mistake, that accessor's getter is marked with
431 // an `originalValue` property. Here, when we detect this, we
432 // uphold the illusion by pretending to see that original data
433 // property, i.e., returning the value rather than the getter
434 // itself.
435 if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
436 value = desc.get;
437 } else {
438 value = value[part];
439 }
440 } else {
441 isOwn = src(value, part);
442 value = value[part];
443 }
444
445 if (isOwn && !skipFurtherCaching) {
446 INTRINSICS[intrinsicRealName] = value;
447 }
448 }
449 }
450 return value;
451 };
452
453 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
454
455 function getAugmentedNamespace(n) {
456 if (n.__esModule) return n;
457 var a = Object.defineProperty({}, '__esModule', {value: true});
458 Object.keys(n).forEach(function (k) {
459 var d = Object.getOwnPropertyDescriptor(n, k);
460 Object.defineProperty(a, k, d.get ? d : {
461 enumerable: true,
462 get: function () {
463 return n[k];
464 }
465 });
466 });
467 return a;
468 }
469
470 function createCommonjsModule(fn) {
471 var module = { exports: {} };
472 return fn(module, module.exports), module.exports;
473 }
474
475 var callBind = createCommonjsModule(function (module) {
476
477
478
479
480 var $apply = getIntrinsic('%Function.prototype.apply%');
481 var $call = getIntrinsic('%Function.prototype.call%');
482 var $reflectApply = getIntrinsic('%Reflect.apply%', true) || functionBind.call($call, $apply);
483
484 var $gOPD = getIntrinsic('%Object.getOwnPropertyDescriptor%', true);
485 var $defineProperty = getIntrinsic('%Object.defineProperty%', true);
486 var $max = getIntrinsic('%Math.max%');
487
488 if ($defineProperty) {
489 try {
490 $defineProperty({}, 'a', { value: 1 });
491 } catch (e) {
492 // IE 8 has a broken defineProperty
493 $defineProperty = null;
494 }
495 }
496
497 module.exports = function callBind(originalFunction) {
498 var func = $reflectApply(functionBind, $call, arguments);
499 if ($gOPD && $defineProperty) {
500 var desc = $gOPD(func, 'length');
501 if (desc.configurable) {
502 // original length, plus the receiver, minus any additional arguments (after the receiver)
503 $defineProperty(
504 func,
505 'length',
506 { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
507 );
508 }
509 }
510 return func;
511 };
512
513 var applyBind = function applyBind() {
514 return $reflectApply(functionBind, $apply, arguments);
515 };
516
517 if ($defineProperty) {
518 $defineProperty(module.exports, 'apply', { value: applyBind });
519 } else {
520 module.exports.apply = applyBind;
521 }
522 });
523
524 var $indexOf = callBind(getIntrinsic('String.prototype.indexOf'));
525
526 var callBound = function callBoundIntrinsic(name, allowMissing) {
527 var intrinsic = getIntrinsic(name, !!allowMissing);
528 if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
529 return callBind(intrinsic);
530 }
531 return intrinsic;
532 };
533
534 var util_inspect = require$$0__default['default'].inspect;
535
536 var hasMap = typeof Map === 'function' && Map.prototype;
537 var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
538 var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
539 var mapForEach = hasMap && Map.prototype.forEach;
540 var hasSet = typeof Set === 'function' && Set.prototype;
541 var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
542 var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
543 var setForEach = hasSet && Set.prototype.forEach;
544 var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
545 var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
546 var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
547 var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
548 var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
549 var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
550 var booleanValueOf = Boolean.prototype.valueOf;
551 var objectToString = Object.prototype.toString;
552 var functionToString = Function.prototype.toString;
553 var match = String.prototype.match;
554 var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
555 var gOPS = Object.getOwnPropertySymbols;
556 var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
557 var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
558 var isEnumerable = Object.prototype.propertyIsEnumerable;
559
560 var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (
561 [].__proto__ === Array.prototype // eslint-disable-line no-proto
562 ? function (O) {
563 return O.__proto__; // eslint-disable-line no-proto
564 }
565 : null
566 );
567
568 var inspectCustom = util_inspect.custom;
569 var inspectSymbol = inspectCustom && isSymbol(inspectCustom) ? inspectCustom : null;
570 var toStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag !== 'undefined' ? Symbol.toStringTag : null;
571
572 var objectInspect = function inspect_(obj, options, depth, seen) {
573 var opts = options || {};
574
575 if (has$3(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
576 throw new TypeError('option "quoteStyle" must be "single" or "double"');
577 }
578 if (
579 has$3(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'
580 ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity
581 : opts.maxStringLength !== null
582 )
583 ) {
584 throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
585 }
586 var customInspect = has$3(opts, 'customInspect') ? opts.customInspect : true;
587 if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {
588 throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');
589 }
590
591 if (
592 has$3(opts, 'indent')
593 && opts.indent !== null
594 && opts.indent !== '\t'
595 && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)
596 ) {
597 throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');
598 }
599
600 if (typeof obj === 'undefined') {
601 return 'undefined';
602 }
603 if (obj === null) {
604 return 'null';
605 }
606 if (typeof obj === 'boolean') {
607 return obj ? 'true' : 'false';
608 }
609
610 if (typeof obj === 'string') {
611 return inspectString(obj, opts);
612 }
613 if (typeof obj === 'number') {
614 if (obj === 0) {
615 return Infinity / obj > 0 ? '0' : '-0';
616 }
617 return String(obj);
618 }
619 if (typeof obj === 'bigint') {
620 return String(obj) + 'n';
621 }
622
623 var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
624 if (typeof depth === 'undefined') { depth = 0; }
625 if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
626 return isArray$3(obj) ? '[Array]' : '[Object]';
627 }
628
629 var indent = getIndent(opts, depth);
630
631 if (typeof seen === 'undefined') {
632 seen = [];
633 } else if (indexOf(seen, obj) >= 0) {
634 return '[Circular]';
635 }
636
637 function inspect(value, from, noIndent) {
638 if (from) {
639 seen = seen.slice();
640 seen.push(from);
641 }
642 if (noIndent) {
643 var newOpts = {
644 depth: opts.depth
645 };
646 if (has$3(opts, 'quoteStyle')) {
647 newOpts.quoteStyle = opts.quoteStyle;
648 }
649 return inspect_(value, newOpts, depth + 1, seen);
650 }
651 return inspect_(value, opts, depth + 1, seen);
652 }
653
654 if (typeof obj === 'function') {
655 var name = nameOf(obj);
656 var keys = arrObjKeys(obj, inspect);
657 return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + keys.join(', ') + ' }' : '');
658 }
659 if (isSymbol(obj)) {
660 var symString = hasShammedSymbols ? String(obj).replace(/^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
661 return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
662 }
663 if (isElement(obj)) {
664 var s = '<' + String(obj.nodeName).toLowerCase();
665 var attrs = obj.attributes || [];
666 for (var i = 0; i < attrs.length; i++) {
667 s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
668 }
669 s += '>';
670 if (obj.childNodes && obj.childNodes.length) { s += '...'; }
671 s += '</' + String(obj.nodeName).toLowerCase() + '>';
672 return s;
673 }
674 if (isArray$3(obj)) {
675 if (obj.length === 0) { return '[]'; }
676 var xs = arrObjKeys(obj, inspect);
677 if (indent && !singleLineValues(xs)) {
678 return '[' + indentedJoin(xs, indent) + ']';
679 }
680 return '[ ' + xs.join(', ') + ' ]';
681 }
682 if (isError(obj)) {
683 var parts = arrObjKeys(obj, inspect);
684 if (parts.length === 0) { return '[' + String(obj) + ']'; }
685 return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }';
686 }
687 if (typeof obj === 'object' && customInspect) {
688 if (inspectSymbol && typeof obj[inspectSymbol] === 'function') {
689 return obj[inspectSymbol]();
690 } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
691 return obj.inspect();
692 }
693 }
694 if (isMap(obj)) {
695 var mapParts = [];
696 mapForEach.call(obj, function (value, key) {
697 mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
698 });
699 return collectionOf('Map', mapSize.call(obj), mapParts, indent);
700 }
701 if (isSet(obj)) {
702 var setParts = [];
703 setForEach.call(obj, function (value) {
704 setParts.push(inspect(value, obj));
705 });
706 return collectionOf('Set', setSize.call(obj), setParts, indent);
707 }
708 if (isWeakMap(obj)) {
709 return weakCollectionOf('WeakMap');
710 }
711 if (isWeakSet(obj)) {
712 return weakCollectionOf('WeakSet');
713 }
714 if (isWeakRef(obj)) {
715 return weakCollectionOf('WeakRef');
716 }
717 if (isNumber(obj)) {
718 return markBoxed(inspect(Number(obj)));
719 }
720 if (isBigInt(obj)) {
721 return markBoxed(inspect(bigIntValueOf.call(obj)));
722 }
723 if (isBoolean(obj)) {
724 return markBoxed(booleanValueOf.call(obj));
725 }
726 if (isString(obj)) {
727 return markBoxed(inspect(String(obj)));
728 }
729 if (!isDate(obj) && !isRegExp$1(obj)) {
730 var ys = arrObjKeys(obj, inspect);
731 var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
732 var protoTag = obj instanceof Object ? '' : 'null prototype';
733 var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? toStr(obj).slice(8, -1) : protoTag ? 'Object' : '';
734 var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
735 var tag = constructorTag + (stringTag || protoTag ? '[' + [].concat(stringTag || [], protoTag || []).join(': ') + '] ' : '');
736 if (ys.length === 0) { return tag + '{}'; }
737 if (indent) {
738 return tag + '{' + indentedJoin(ys, indent) + '}';
739 }
740 return tag + '{ ' + ys.join(', ') + ' }';
741 }
742 return String(obj);
743 };
744
745 function wrapQuotes(s, defaultStyle, opts) {
746 var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
747 return quoteChar + s + quoteChar;
748 }
749
750 function quote(s) {
751 return String(s).replace(/"/g, '&quot;');
752 }
753
754 function isArray$3(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
755 function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
756 function isRegExp$1(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
757 function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
758 function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
759 function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
760 function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
761
762 // Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
763 function isSymbol(obj) {
764 if (hasShammedSymbols) {
765 return obj && typeof obj === 'object' && obj instanceof Symbol;
766 }
767 if (typeof obj === 'symbol') {
768 return true;
769 }
770 if (!obj || typeof obj !== 'object' || !symToString) {
771 return false;
772 }
773 try {
774 symToString.call(obj);
775 return true;
776 } catch (e) {}
777 return false;
778 }
779
780 function isBigInt(obj) {
781 if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
782 return false;
783 }
784 try {
785 bigIntValueOf.call(obj);
786 return true;
787 } catch (e) {}
788 return false;
789 }
790
791 var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
792 function has$3(obj, key) {
793 return hasOwn.call(obj, key);
794 }
795
796 function toStr(obj) {
797 return objectToString.call(obj);
798 }
799
800 function nameOf(f) {
801 if (f.name) { return f.name; }
802 var m = match.call(functionToString.call(f), /^function\s*([\w$]+)/);
803 if (m) { return m[1]; }
804 return null;
805 }
806
807 function indexOf(xs, x) {
808 if (xs.indexOf) { return xs.indexOf(x); }
809 for (var i = 0, l = xs.length; i < l; i++) {
810 if (xs[i] === x) { return i; }
811 }
812 return -1;
813 }
814
815 function isMap(x) {
816 if (!mapSize || !x || typeof x !== 'object') {
817 return false;
818 }
819 try {
820 mapSize.call(x);
821 try {
822 setSize.call(x);
823 } catch (s) {
824 return true;
825 }
826 return x instanceof Map; // core-js workaround, pre-v2.5.0
827 } catch (e) {}
828 return false;
829 }
830
831 function isWeakMap(x) {
832 if (!weakMapHas || !x || typeof x !== 'object') {
833 return false;
834 }
835 try {
836 weakMapHas.call(x, weakMapHas);
837 try {
838 weakSetHas.call(x, weakSetHas);
839 } catch (s) {
840 return true;
841 }
842 return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
843 } catch (e) {}
844 return false;
845 }
846
847 function isWeakRef(x) {
848 if (!weakRefDeref || !x || typeof x !== 'object') {
849 return false;
850 }
851 try {
852 weakRefDeref.call(x);
853 return true;
854 } catch (e) {}
855 return false;
856 }
857
858 function isSet(x) {
859 if (!setSize || !x || typeof x !== 'object') {
860 return false;
861 }
862 try {
863 setSize.call(x);
864 try {
865 mapSize.call(x);
866 } catch (m) {
867 return true;
868 }
869 return x instanceof Set; // core-js workaround, pre-v2.5.0
870 } catch (e) {}
871 return false;
872 }
873
874 function isWeakSet(x) {
875 if (!weakSetHas || !x || typeof x !== 'object') {
876 return false;
877 }
878 try {
879 weakSetHas.call(x, weakSetHas);
880 try {
881 weakMapHas.call(x, weakMapHas);
882 } catch (s) {
883 return true;
884 }
885 return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
886 } catch (e) {}
887 return false;
888 }
889
890 function isElement(x) {
891 if (!x || typeof x !== 'object') { return false; }
892 if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
893 return true;
894 }
895 return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
896 }
897
898 function inspectString(str, opts) {
899 if (str.length > opts.maxStringLength) {
900 var remaining = str.length - opts.maxStringLength;
901 var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
902 return inspectString(str.slice(0, opts.maxStringLength), opts) + trailer;
903 }
904 // eslint-disable-next-line no-control-regex
905 var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
906 return wrapQuotes(s, 'single', opts);
907 }
908
909 function lowbyte(c) {
910 var n = c.charCodeAt(0);
911 var x = {
912 8: 'b',
913 9: 't',
914 10: 'n',
915 12: 'f',
916 13: 'r'
917 }[n];
918 if (x) { return '\\' + x; }
919 return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16).toUpperCase();
920 }
921
922 function markBoxed(str) {
923 return 'Object(' + str + ')';
924 }
925
926 function weakCollectionOf(type) {
927 return type + ' { ? }';
928 }
929
930 function collectionOf(type, size, entries, indent) {
931 var joinedEntries = indent ? indentedJoin(entries, indent) : entries.join(', ');
932 return type + ' (' + size + ') {' + joinedEntries + '}';
933 }
934
935 function singleLineValues(xs) {
936 for (var i = 0; i < xs.length; i++) {
937 if (indexOf(xs[i], '\n') >= 0) {
938 return false;
939 }
940 }
941 return true;
942 }
943
944 function getIndent(opts, depth) {
945 var baseIndent;
946 if (opts.indent === '\t') {
947 baseIndent = '\t';
948 } else if (typeof opts.indent === 'number' && opts.indent > 0) {
949 baseIndent = Array(opts.indent + 1).join(' ');
950 } else {
951 return null;
952 }
953 return {
954 base: baseIndent,
955 prev: Array(depth + 1).join(baseIndent)
956 };
957 }
958
959 function indentedJoin(xs, indent) {
960 if (xs.length === 0) { return ''; }
961 var lineJoiner = '\n' + indent.prev + indent.base;
962 return lineJoiner + xs.join(',' + lineJoiner) + '\n' + indent.prev;
963 }
964
965 function arrObjKeys(obj, inspect) {
966 var isArr = isArray$3(obj);
967 var xs = [];
968 if (isArr) {
969 xs.length = obj.length;
970 for (var i = 0; i < obj.length; i++) {
971 xs[i] = has$3(obj, i) ? inspect(obj[i], obj) : '';
972 }
973 }
974 var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
975 var symMap;
976 if (hasShammedSymbols) {
977 symMap = {};
978 for (var k = 0; k < syms.length; k++) {
979 symMap['$' + syms[k]] = syms[k];
980 }
981 }
982
983 for (var key in obj) { // eslint-disable-line no-restricted-syntax
984 if (!has$3(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
985 if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
986 if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
987 // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
988 continue; // eslint-disable-line no-restricted-syntax, no-continue
989 } else if ((/[^\w$]/).test(key)) {
990 xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
991 } else {
992 xs.push(key + ': ' + inspect(obj[key], obj));
993 }
994 }
995 if (typeof gOPS === 'function') {
996 for (var j = 0; j < syms.length; j++) {
997 if (isEnumerable.call(obj, syms[j])) {
998 xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
999 }
1000 }
1001 }
1002 return xs;
1003 }
1004
1005 var $TypeError = getIntrinsic('%TypeError%');
1006 var $WeakMap = getIntrinsic('%WeakMap%', true);
1007 var $Map = getIntrinsic('%Map%', true);
1008
1009 var $weakMapGet = callBound('WeakMap.prototype.get', true);
1010 var $weakMapSet = callBound('WeakMap.prototype.set', true);
1011 var $weakMapHas = callBound('WeakMap.prototype.has', true);
1012 var $mapGet = callBound('Map.prototype.get', true);
1013 var $mapSet = callBound('Map.prototype.set', true);
1014 var $mapHas = callBound('Map.prototype.has', true);
1015
1016 /*
1017 * This function traverses the list returning the node corresponding to the
1018 * given key.
1019 *
1020 * That node is also moved to the head of the list, so that if it's accessed
1021 * again we don't need to traverse the whole list. By doing so, all the recently
1022 * used nodes can be accessed relatively quickly.
1023 */
1024 var listGetNode = function (list, key) { // eslint-disable-line consistent-return
1025 for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) {
1026 if (curr.key === key) {
1027 prev.next = curr.next;
1028 curr.next = list.next;
1029 list.next = curr; // eslint-disable-line no-param-reassign
1030 return curr;
1031 }
1032 }
1033 };
1034
1035 var listGet = function (objects, key) {
1036 var node = listGetNode(objects, key);
1037 return node && node.value;
1038 };
1039 var listSet = function (objects, key, value) {
1040 var node = listGetNode(objects, key);
1041 if (node) {
1042 node.value = value;
1043 } else {
1044 // Prepend the new node to the beginning of the list
1045 objects.next = { // eslint-disable-line no-param-reassign
1046 key: key,
1047 next: objects.next,
1048 value: value
1049 };
1050 }
1051 };
1052 var listHas = function (objects, key) {
1053 return !!listGetNode(objects, key);
1054 };
1055
1056 var sideChannel = function getSideChannel() {
1057 var $wm;
1058 var $m;
1059 var $o;
1060 var channel = {
1061 assert: function (key) {
1062 if (!channel.has(key)) {
1063 throw new $TypeError('Side channel does not contain ' + objectInspect(key));
1064 }
1065 },
1066 get: function (key) { // eslint-disable-line consistent-return
1067 if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
1068 if ($wm) {
1069 return $weakMapGet($wm, key);
1070 }
1071 } else if ($Map) {
1072 if ($m) {
1073 return $mapGet($m, key);
1074 }
1075 } else {
1076 if ($o) { // eslint-disable-line no-lonely-if
1077 return listGet($o, key);
1078 }
1079 }
1080 },
1081 has: function (key) {
1082 if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
1083 if ($wm) {
1084 return $weakMapHas($wm, key);
1085 }
1086 } else if ($Map) {
1087 if ($m) {
1088 return $mapHas($m, key);
1089 }
1090 } else {
1091 if ($o) { // eslint-disable-line no-lonely-if
1092 return listHas($o, key);
1093 }
1094 }
1095 return false;
1096 },
1097 set: function (key, value) {
1098 if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
1099 if (!$wm) {
1100 $wm = new $WeakMap();
1101 }
1102 $weakMapSet($wm, key, value);
1103 } else if ($Map) {
1104 if (!$m) {
1105 $m = new $Map();
1106 }
1107 $mapSet($m, key, value);
1108 } else {
1109 if (!$o) {
1110 /*
1111 * Initialize the linked list as an empty node, so that we don't have
1112 * to special-case handling of the first node: we can always refer to
1113 * it as (previous node).next, instead of something like (list).head
1114 */
1115 $o = { key: {}, next: null };
1116 }
1117 listSet($o, key, value);
1118 }
1119 }
1120 };
1121 return channel;
1122 };
1123
1124 var replace = String.prototype.replace;
1125 var percentTwenties = /%20/g;
1126
1127 var Format = {
1128 RFC1738: 'RFC1738',
1129 RFC3986: 'RFC3986'
1130 };
1131
1132 var formats = {
1133 'default': Format.RFC3986,
1134 formatters: {
1135 RFC1738: function (value) {
1136 return replace.call(value, percentTwenties, '+');
1137 },
1138 RFC3986: function (value) {
1139 return String(value);
1140 }
1141 },
1142 RFC1738: Format.RFC1738,
1143 RFC3986: Format.RFC3986
1144 };
1145
1146 var has$2 = Object.prototype.hasOwnProperty;
1147 var isArray$2 = Array.isArray;
1148
1149 var hexTable = (function () {
1150 var array = [];
1151 for (var i = 0; i < 256; ++i) {
1152 array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
1153 }
1154
1155 return array;
1156 }());
1157
1158 var compactQueue = function compactQueue(queue) {
1159 while (queue.length > 1) {
1160 var item = queue.pop();
1161 var obj = item.obj[item.prop];
1162
1163 if (isArray$2(obj)) {
1164 var compacted = [];
1165
1166 for (var j = 0; j < obj.length; ++j) {
1167 if (typeof obj[j] !== 'undefined') {
1168 compacted.push(obj[j]);
1169 }
1170 }
1171
1172 item.obj[item.prop] = compacted;
1173 }
1174 }
1175 };
1176
1177 var arrayToObject = function arrayToObject(source, options) {
1178 var obj = options && options.plainObjects ? Object.create(null) : {};
1179 for (var i = 0; i < source.length; ++i) {
1180 if (typeof source[i] !== 'undefined') {
1181 obj[i] = source[i];
1182 }
1183 }
1184
1185 return obj;
1186 };
1187
1188 var merge = function merge(target, source, options) {
1189 /* eslint no-param-reassign: 0 */
1190 if (!source) {
1191 return target;
1192 }
1193
1194 if (typeof source !== 'object') {
1195 if (isArray$2(target)) {
1196 target.push(source);
1197 } else if (target && typeof target === 'object') {
1198 if ((options && (options.plainObjects || options.allowPrototypes)) || !has$2.call(Object.prototype, source)) {
1199 target[source] = true;
1200 }
1201 } else {
1202 return [target, source];
1203 }
1204
1205 return target;
1206 }
1207
1208 if (!target || typeof target !== 'object') {
1209 return [target].concat(source);
1210 }
1211
1212 var mergeTarget = target;
1213 if (isArray$2(target) && !isArray$2(source)) {
1214 mergeTarget = arrayToObject(target, options);
1215 }
1216
1217 if (isArray$2(target) && isArray$2(source)) {
1218 source.forEach(function (item, i) {
1219 if (has$2.call(target, i)) {
1220 var targetItem = target[i];
1221 if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
1222 target[i] = merge(targetItem, item, options);
1223 } else {
1224 target.push(item);
1225 }
1226 } else {
1227 target[i] = item;
1228 }
1229 });
1230 return target;
1231 }
1232
1233 return Object.keys(source).reduce(function (acc, key) {
1234 var value = source[key];
1235
1236 if (has$2.call(acc, key)) {
1237 acc[key] = merge(acc[key], value, options);
1238 } else {
1239 acc[key] = value;
1240 }
1241 return acc;
1242 }, mergeTarget);
1243 };
1244
1245 var assign = function assignSingleSource(target, source) {
1246 return Object.keys(source).reduce(function (acc, key) {
1247 acc[key] = source[key];
1248 return acc;
1249 }, target);
1250 };
1251
1252 var decode = function (str, decoder, charset) {
1253 var strWithoutPlus = str.replace(/\+/g, ' ');
1254 if (charset === 'iso-8859-1') {
1255 // unescape never throws, no try...catch needed:
1256 return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
1257 }
1258 // utf-8
1259 try {
1260 return decodeURIComponent(strWithoutPlus);
1261 } catch (e) {
1262 return strWithoutPlus;
1263 }
1264 };
1265
1266 var encode = function encode(str, defaultEncoder, charset, kind, format) {
1267 // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
1268 // It has been adapted here for stricter adherence to RFC 3986
1269 if (str.length === 0) {
1270 return str;
1271 }
1272
1273 var string = str;
1274 if (typeof str === 'symbol') {
1275 string = Symbol.prototype.toString.call(str);
1276 } else if (typeof str !== 'string') {
1277 string = String(str);
1278 }
1279
1280 if (charset === 'iso-8859-1') {
1281 return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
1282 return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
1283 });
1284 }
1285
1286 var out = '';
1287 for (var i = 0; i < string.length; ++i) {
1288 var c = string.charCodeAt(i);
1289
1290 if (
1291 c === 0x2D // -
1292 || c === 0x2E // .
1293 || c === 0x5F // _
1294 || c === 0x7E // ~
1295 || (c >= 0x30 && c <= 0x39) // 0-9
1296 || (c >= 0x41 && c <= 0x5A) // a-z
1297 || (c >= 0x61 && c <= 0x7A) // A-Z
1298 || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( )
1299 ) {
1300 out += string.charAt(i);
1301 continue;
1302 }
1303
1304 if (c < 0x80) {
1305 out = out + hexTable[c];
1306 continue;
1307 }
1308
1309 if (c < 0x800) {
1310 out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
1311 continue;
1312 }
1313
1314 if (c < 0xD800 || c >= 0xE000) {
1315 out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
1316 continue;
1317 }
1318
1319 i += 1;
1320 c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
1321 out += hexTable[0xF0 | (c >> 18)]
1322 + hexTable[0x80 | ((c >> 12) & 0x3F)]
1323 + hexTable[0x80 | ((c >> 6) & 0x3F)]
1324 + hexTable[0x80 | (c & 0x3F)];
1325 }
1326
1327 return out;
1328 };
1329
1330 var compact = function compact(value) {
1331 var queue = [{ obj: { o: value }, prop: 'o' }];
1332 var refs = [];
1333
1334 for (var i = 0; i < queue.length; ++i) {
1335 var item = queue[i];
1336 var obj = item.obj[item.prop];
1337
1338 var keys = Object.keys(obj);
1339 for (var j = 0; j < keys.length; ++j) {
1340 var key = keys[j];
1341 var val = obj[key];
1342 if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
1343 queue.push({ obj: obj, prop: key });
1344 refs.push(val);
1345 }
1346 }
1347 }
1348
1349 compactQueue(queue);
1350
1351 return value;
1352 };
1353
1354 var isRegExp = function isRegExp(obj) {
1355 return Object.prototype.toString.call(obj) === '[object RegExp]';
1356 };
1357
1358 var isBuffer = function isBuffer(obj) {
1359 if (!obj || typeof obj !== 'object') {
1360 return false;
1361 }
1362
1363 return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
1364 };
1365
1366 var combine = function combine(a, b) {
1367 return [].concat(a, b);
1368 };
1369
1370 var maybeMap = function maybeMap(val, fn) {
1371 if (isArray$2(val)) {
1372 var mapped = [];
1373 for (var i = 0; i < val.length; i += 1) {
1374 mapped.push(fn(val[i]));
1375 }
1376 return mapped;
1377 }
1378 return fn(val);
1379 };
1380
1381 var utils = {
1382 arrayToObject: arrayToObject,
1383 assign: assign,
1384 combine: combine,
1385 compact: compact,
1386 decode: decode,
1387 encode: encode,
1388 isBuffer: isBuffer,
1389 isRegExp: isRegExp,
1390 maybeMap: maybeMap,
1391 merge: merge
1392 };
1393
1394 var has$1 = Object.prototype.hasOwnProperty;
1395
1396 var arrayPrefixGenerators = {
1397 brackets: function brackets(prefix) {
1398 return prefix + '[]';
1399 },
1400 comma: 'comma',
1401 indices: function indices(prefix, key) {
1402 return prefix + '[' + key + ']';
1403 },
1404 repeat: function repeat(prefix) {
1405 return prefix;
1406 }
1407 };
1408
1409 var isArray$1 = Array.isArray;
1410 var push = Array.prototype.push;
1411 var pushToArray = function (arr, valueOrArray) {
1412 push.apply(arr, isArray$1(valueOrArray) ? valueOrArray : [valueOrArray]);
1413 };
1414
1415 var toISO = Date.prototype.toISOString;
1416
1417 var defaultFormat = formats['default'];
1418 var defaults$1 = {
1419 addQueryPrefix: false,
1420 allowDots: false,
1421 charset: 'utf-8',
1422 charsetSentinel: false,
1423 delimiter: '&',
1424 encode: true,
1425 encoder: utils.encode,
1426 encodeValuesOnly: false,
1427 format: defaultFormat,
1428 formatter: formats.formatters[defaultFormat],
1429 // deprecated
1430 indices: false,
1431 serializeDate: function serializeDate(date) {
1432 return toISO.call(date);
1433 },
1434 skipNulls: false,
1435 strictNullHandling: false
1436 };
1437
1438 var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
1439 return typeof v === 'string'
1440 || typeof v === 'number'
1441 || typeof v === 'boolean'
1442 || typeof v === 'symbol'
1443 || typeof v === 'bigint';
1444 };
1445
1446 var stringify = function stringify(
1447 object,
1448 prefix,
1449 generateArrayPrefix,
1450 strictNullHandling,
1451 skipNulls,
1452 encoder,
1453 filter,
1454 sort,
1455 allowDots,
1456 serializeDate,
1457 format,
1458 formatter,
1459 encodeValuesOnly,
1460 charset,
1461 sideChannel$1
1462 ) {
1463 var obj = object;
1464
1465 if (sideChannel$1.has(object)) {
1466 throw new RangeError('Cyclic object value');
1467 }
1468
1469 if (typeof filter === 'function') {
1470 obj = filter(prefix, obj);
1471 } else if (obj instanceof Date) {
1472 obj = serializeDate(obj);
1473 } else if (generateArrayPrefix === 'comma' && isArray$1(obj)) {
1474 obj = utils.maybeMap(obj, function (value) {
1475 if (value instanceof Date) {
1476 return serializeDate(value);
1477 }
1478 return value;
1479 });
1480 }
1481
1482 if (obj === null) {
1483 if (strictNullHandling) {
1484 return encoder && !encodeValuesOnly ? encoder(prefix, defaults$1.encoder, charset, 'key', format) : prefix;
1485 }
1486
1487 obj = '';
1488 }
1489
1490 if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
1491 if (encoder) {
1492 var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$1.encoder, charset, 'key', format);
1493 return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$1.encoder, charset, 'value', format))];
1494 }
1495 return [formatter(prefix) + '=' + formatter(String(obj))];
1496 }
1497
1498 var values = [];
1499
1500 if (typeof obj === 'undefined') {
1501 return values;
1502 }
1503
1504 var objKeys;
1505 if (generateArrayPrefix === 'comma' && isArray$1(obj)) {
1506 // we need to join elements in
1507 objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : undefined }];
1508 } else if (isArray$1(filter)) {
1509 objKeys = filter;
1510 } else {
1511 var keys = Object.keys(obj);
1512 objKeys = sort ? keys.sort(sort) : keys;
1513 }
1514
1515 for (var i = 0; i < objKeys.length; ++i) {
1516 var key = objKeys[i];
1517 var value = typeof key === 'object' && key.value !== undefined ? key.value : obj[key];
1518
1519 if (skipNulls && value === null) {
1520 continue;
1521 }
1522
1523 var keyPrefix = isArray$1(obj)
1524 ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix
1525 : prefix + (allowDots ? '.' + key : '[' + key + ']');
1526
1527 sideChannel$1.set(object, true);
1528 var valueSideChannel = sideChannel();
1529 pushToArray(values, stringify(
1530 value,
1531 keyPrefix,
1532 generateArrayPrefix,
1533 strictNullHandling,
1534 skipNulls,
1535 encoder,
1536 filter,
1537 sort,
1538 allowDots,
1539 serializeDate,
1540 format,
1541 formatter,
1542 encodeValuesOnly,
1543 charset,
1544 valueSideChannel
1545 ));
1546 }
1547
1548 return values;
1549 };
1550
1551 var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
1552 if (!opts) {
1553 return defaults$1;
1554 }
1555
1556 if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') {
1557 throw new TypeError('Encoder has to be a function.');
1558 }
1559
1560 var charset = opts.charset || defaults$1.charset;
1561 if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
1562 throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
1563 }
1564
1565 var format = formats['default'];
1566 if (typeof opts.format !== 'undefined') {
1567 if (!has$1.call(formats.formatters, opts.format)) {
1568 throw new TypeError('Unknown format option provided.');
1569 }
1570 format = opts.format;
1571 }
1572 var formatter = formats.formatters[format];
1573
1574 var filter = defaults$1.filter;
1575 if (typeof opts.filter === 'function' || isArray$1(opts.filter)) {
1576 filter = opts.filter;
1577 }
1578
1579 return {
1580 addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults$1.addQueryPrefix,
1581 allowDots: typeof opts.allowDots === 'undefined' ? defaults$1.allowDots : !!opts.allowDots,
1582 charset: charset,
1583 charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults$1.charsetSentinel,
1584 delimiter: typeof opts.delimiter === 'undefined' ? defaults$1.delimiter : opts.delimiter,
1585 encode: typeof opts.encode === 'boolean' ? opts.encode : defaults$1.encode,
1586 encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults$1.encoder,
1587 encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults$1.encodeValuesOnly,
1588 filter: filter,
1589 format: format,
1590 formatter: formatter,
1591 serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults$1.serializeDate,
1592 skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults$1.skipNulls,
1593 sort: typeof opts.sort === 'function' ? opts.sort : null,
1594 strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults$1.strictNullHandling
1595 };
1596 };
1597
1598 var stringify_1 = function (object, opts) {
1599 var obj = object;
1600 var options = normalizeStringifyOptions(opts);
1601
1602 var objKeys;
1603 var filter;
1604
1605 if (typeof options.filter === 'function') {
1606 filter = options.filter;
1607 obj = filter('', obj);
1608 } else if (isArray$1(options.filter)) {
1609 filter = options.filter;
1610 objKeys = filter;
1611 }
1612
1613 var keys = [];
1614
1615 if (typeof obj !== 'object' || obj === null) {
1616 return '';
1617 }
1618
1619 var arrayFormat;
1620 if (opts && opts.arrayFormat in arrayPrefixGenerators) {
1621 arrayFormat = opts.arrayFormat;
1622 } else if (opts && 'indices' in opts) {
1623 arrayFormat = opts.indices ? 'indices' : 'repeat';
1624 } else {
1625 arrayFormat = 'indices';
1626 }
1627
1628 var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
1629
1630 if (!objKeys) {
1631 objKeys = Object.keys(obj);
1632 }
1633
1634 if (options.sort) {
1635 objKeys.sort(options.sort);
1636 }
1637
1638 var sideChannel$1 = sideChannel();
1639 for (var i = 0; i < objKeys.length; ++i) {
1640 var key = objKeys[i];
1641
1642 if (options.skipNulls && obj[key] === null) {
1643 continue;
1644 }
1645 pushToArray(keys, stringify(
1646 obj[key],
1647 key,
1648 generateArrayPrefix,
1649 options.strictNullHandling,
1650 options.skipNulls,
1651 options.encode ? options.encoder : null,
1652 options.filter,
1653 options.sort,
1654 options.allowDots,
1655 options.serializeDate,
1656 options.format,
1657 options.formatter,
1658 options.encodeValuesOnly,
1659 options.charset,
1660 sideChannel$1
1661 ));
1662 }
1663
1664 var joined = keys.join(options.delimiter);
1665 var prefix = options.addQueryPrefix === true ? '?' : '';
1666
1667 if (options.charsetSentinel) {
1668 if (options.charset === 'iso-8859-1') {
1669 // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark
1670 prefix += 'utf8=%26%2310003%3B&';
1671 } else {
1672 // encodeURIComponent('✓')
1673 prefix += 'utf8=%E2%9C%93&';
1674 }
1675 }
1676
1677 return joined.length > 0 ? prefix + joined : '';
1678 };
1679
1680 var has = Object.prototype.hasOwnProperty;
1681 var isArray = Array.isArray;
1682
1683 var defaults = {
1684 allowDots: false,
1685 allowPrototypes: false,
1686 allowSparse: false,
1687 arrayLimit: 20,
1688 charset: 'utf-8',
1689 charsetSentinel: false,
1690 comma: false,
1691 decoder: utils.decode,
1692 delimiter: '&',
1693 depth: 5,
1694 ignoreQueryPrefix: false,
1695 interpretNumericEntities: false,
1696 parameterLimit: 1000,
1697 parseArrays: true,
1698 plainObjects: false,
1699 strictNullHandling: false
1700 };
1701
1702 var interpretNumericEntities = function (str) {
1703 return str.replace(/&#(\d+);/g, function ($0, numberStr) {
1704 return String.fromCharCode(parseInt(numberStr, 10));
1705 });
1706 };
1707
1708 var parseArrayValue = function (val, options) {
1709 if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
1710 return val.split(',');
1711 }
1712
1713 return val;
1714 };
1715
1716 // This is what browsers will submit when the ✓ character occurs in an
1717 // application/x-www-form-urlencoded body and the encoding of the page containing
1718 // the form is iso-8859-1, or when the submitted form has an accept-charset
1719 // attribute of iso-8859-1. Presumably also with other charsets that do not contain
1720 // the ✓ character, such as us-ascii.
1721 var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;')
1722
1723 // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
1724 var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
1725
1726 var parseValues = function parseQueryStringValues(str, options) {
1727 var obj = {};
1728 var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
1729 var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
1730 var parts = cleanStr.split(options.delimiter, limit);
1731 var skipIndex = -1; // Keep track of where the utf8 sentinel was found
1732 var i;
1733
1734 var charset = options.charset;
1735 if (options.charsetSentinel) {
1736 for (i = 0; i < parts.length; ++i) {
1737 if (parts[i].indexOf('utf8=') === 0) {
1738 if (parts[i] === charsetSentinel) {
1739 charset = 'utf-8';
1740 } else if (parts[i] === isoSentinel) {
1741 charset = 'iso-8859-1';
1742 }
1743 skipIndex = i;
1744 i = parts.length; // The eslint settings do not allow break;
1745 }
1746 }
1747 }
1748
1749 for (i = 0; i < parts.length; ++i) {
1750 if (i === skipIndex) {
1751 continue;
1752 }
1753 var part = parts[i];
1754
1755 var bracketEqualsPos = part.indexOf(']=');
1756 var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
1757
1758 var key, val;
1759 if (pos === -1) {
1760 key = options.decoder(part, defaults.decoder, charset, 'key');
1761 val = options.strictNullHandling ? null : '';
1762 } else {
1763 key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');
1764 val = utils.maybeMap(
1765 parseArrayValue(part.slice(pos + 1), options),
1766 function (encodedVal) {
1767 return options.decoder(encodedVal, defaults.decoder, charset, 'value');
1768 }
1769 );
1770 }
1771
1772 if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
1773 val = interpretNumericEntities(val);
1774 }
1775
1776 if (part.indexOf('[]=') > -1) {
1777 val = isArray(val) ? [val] : val;
1778 }
1779
1780 if (has.call(obj, key)) {
1781 obj[key] = utils.combine(obj[key], val);
1782 } else {
1783 obj[key] = val;
1784 }
1785 }
1786
1787 return obj;
1788 };
1789
1790 var parseObject = function (chain, val, options, valuesParsed) {
1791 var leaf = valuesParsed ? val : parseArrayValue(val, options);
1792
1793 for (var i = chain.length - 1; i >= 0; --i) {
1794 var obj;
1795 var root = chain[i];
1796
1797 if (root === '[]' && options.parseArrays) {
1798 obj = [].concat(leaf);
1799 } else {
1800 obj = options.plainObjects ? Object.create(null) : {};
1801 var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
1802 var index = parseInt(cleanRoot, 10);
1803 if (!options.parseArrays && cleanRoot === '') {
1804 obj = { 0: leaf };
1805 } else if (
1806 !isNaN(index)
1807 && root !== cleanRoot
1808 && String(index) === cleanRoot
1809 && index >= 0
1810 && (options.parseArrays && index <= options.arrayLimit)
1811 ) {
1812 obj = [];
1813 obj[index] = leaf;
1814 } else {
1815 obj[cleanRoot] = leaf;
1816 }
1817 }
1818
1819 leaf = obj;
1820 }
1821
1822 return leaf;
1823 };
1824
1825 var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
1826 if (!givenKey) {
1827 return;
1828 }
1829
1830 // Transform dot notation to bracket notation
1831 var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
1832
1833 // The regex chunks
1834
1835 var brackets = /(\[[^[\]]*])/;
1836 var child = /(\[[^[\]]*])/g;
1837
1838 // Get the parent
1839
1840 var segment = options.depth > 0 && brackets.exec(key);
1841 var parent = segment ? key.slice(0, segment.index) : key;
1842
1843 // Stash the parent if it exists
1844
1845 var keys = [];
1846 if (parent) {
1847 // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
1848 if (!options.plainObjects && has.call(Object.prototype, parent)) {
1849 if (!options.allowPrototypes) {
1850 return;
1851 }
1852 }
1853
1854 keys.push(parent);
1855 }
1856
1857 // Loop through children appending to the array until we hit depth
1858
1859 var i = 0;
1860 while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
1861 i += 1;
1862 if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
1863 if (!options.allowPrototypes) {
1864 return;
1865 }
1866 }
1867 keys.push(segment[1]);
1868 }
1869
1870 // If there's a remainder, just add whatever is left
1871
1872 if (segment) {
1873 keys.push('[' + key.slice(segment.index) + ']');
1874 }
1875
1876 return parseObject(keys, val, options, valuesParsed);
1877 };
1878
1879 var normalizeParseOptions = function normalizeParseOptions(opts) {
1880 if (!opts) {
1881 return defaults;
1882 }
1883
1884 if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
1885 throw new TypeError('Decoder has to be a function.');
1886 }
1887
1888 if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
1889 throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
1890 }
1891 var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;
1892
1893 return {
1894 allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
1895 allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
1896 allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,
1897 arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
1898 charset: charset,
1899 charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
1900 comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
1901 decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
1902 delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
1903 // eslint-disable-next-line no-implicit-coercion, no-extra-parens
1904 depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
1905 ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
1906 interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
1907 parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
1908 parseArrays: opts.parseArrays !== false,
1909 plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
1910 strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
1911 };
1912 };
1913
1914 var parse$1 = function (str, opts) {
1915 var options = normalizeParseOptions(opts);
1916
1917 if (str === '' || str === null || typeof str === 'undefined') {
1918 return options.plainObjects ? Object.create(null) : {};
1919 }
1920
1921 var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
1922 var obj = options.plainObjects ? Object.create(null) : {};
1923
1924 // Iterate over the keys and setup the new object
1925
1926 var keys = Object.keys(tempObj);
1927 for (var i = 0; i < keys.length; ++i) {
1928 var key = keys[i];
1929 var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
1930 obj = utils.merge(obj, newObj, options);
1931 }
1932
1933 if (options.allowSparse === true) {
1934 return obj;
1935 }
1936
1937 return utils.compact(obj);
1938 };
1939
1940 var lib$1 = {
1941 formats: formats,
1942 parse: parse$1,
1943 stringify: stringify_1
1944 };
1945
1946 function account(rawAccount) {
1947 if (!rawAccount) {
1948 return undefined;
1949 }
1950 try {
1951 return {
1952 ...rawAccount,
1953 raw: () => rawAccount,
1954 buying_power: number(rawAccount.buying_power),
1955 regt_buying_power: number(rawAccount.regt_buying_power),
1956 daytrading_buying_power: number(rawAccount.daytrading_buying_power),
1957 cash: number(rawAccount.cash),
1958 created_at: new Date(rawAccount.created_at),
1959 portfolio_value: number(rawAccount.portfolio_value),
1960 multiplier: number(rawAccount.multiplier),
1961 equity: number(rawAccount.equity),
1962 last_equity: number(rawAccount.last_equity),
1963 long_market_value: number(rawAccount.long_market_value),
1964 short_market_value: number(rawAccount.short_market_value),
1965 initial_margin: number(rawAccount.initial_margin),
1966 maintenance_margin: number(rawAccount.maintenance_margin),
1967 last_maintenance_margin: number(rawAccount.last_maintenance_margin),
1968 sma: number(rawAccount.sma),
1969 status: rawAccount.status,
1970 };
1971 }
1972 catch (err) {
1973 throw new Error(`Account parsing failed. ${err.message}`);
1974 }
1975 }
1976 function clock(rawClock) {
1977 if (!rawClock) {
1978 return undefined;
1979 }
1980 try {
1981 return {
1982 raw: () => rawClock,
1983 timestamp: new Date(rawClock.timestamp),
1984 is_open: rawClock.is_open,
1985 next_open: new Date(rawClock.next_open),
1986 next_close: new Date(rawClock.next_close),
1987 };
1988 }
1989 catch (err) {
1990 throw new Error(`Order parsing failed. ${err.message}`);
1991 }
1992 }
1993 function latestTrade(raw) {
1994 if (!raw) {
1995 return undefined;
1996 }
1997 try {
1998 return {
1999 ...raw,
2000 raw: () => raw,
2001 trade: {
2002 ...raw.trade,
2003 t: new Date(raw.trade.t),
2004 },
2005 };
2006 }
2007 catch (err) {
2008 throw new Error(`Latest trade parsing failed. ${err.message}`);
2009 }
2010 }
2011 function order(rawOrder) {
2012 if (!rawOrder) {
2013 return undefined;
2014 }
2015 try {
2016 return {
2017 ...rawOrder,
2018 raw: () => rawOrder,
2019 created_at: new Date(rawOrder.created_at),
2020 updated_at: new Date(rawOrder.updated_at),
2021 submitted_at: new Date(rawOrder.submitted_at),
2022 filled_at: new Date(rawOrder.filled_at),
2023 expired_at: new Date(rawOrder.expired_at),
2024 canceled_at: new Date(rawOrder.canceled_at),
2025 failed_at: new Date(rawOrder.failed_at),
2026 replaced_at: new Date(rawOrder.replaced_at),
2027 qty: number(rawOrder.qty),
2028 filled_qty: number(rawOrder.filled_qty),
2029 type: rawOrder.type,
2030 side: rawOrder.side,
2031 time_in_force: rawOrder.time_in_force,
2032 limit_price: number(rawOrder.limit_price),
2033 stop_price: number(rawOrder.stop_price),
2034 filled_avg_price: number(rawOrder.filled_avg_price),
2035 status: rawOrder.status,
2036 legs: orders(rawOrder.legs),
2037 trail_price: number(rawOrder.trail_price),
2038 trail_percent: number(rawOrder.trail_percent),
2039 hwm: number(rawOrder.hwm),
2040 order_class: rawOrder.order_class,
2041 };
2042 }
2043 catch (err) {
2044 throw new Error(`Order parsing failed. ${err.message}`);
2045 }
2046 }
2047 function orders(rawOrders) {
2048 return rawOrders ? rawOrders.map((value) => order(value)) : undefined;
2049 }
2050 function canceled_order(input) {
2051 if (!input) {
2052 return undefined;
2053 }
2054 let order = input.body;
2055 delete input.body;
2056 try {
2057 return {
2058 ...input,
2059 order: {
2060 ...order,
2061 raw: () => order,
2062 created_at: new Date(order.created_at),
2063 updated_at: new Date(order.updated_at),
2064 submitted_at: new Date(order.submitted_at),
2065 filled_at: new Date(order.filled_at),
2066 expired_at: new Date(order.expired_at),
2067 canceled_at: new Date(order.canceled_at),
2068 failed_at: new Date(order.failed_at),
2069 replaced_at: new Date(order.replaced_at),
2070 qty: number(order.qty),
2071 filled_qty: number(order.filled_qty),
2072 type: order.type,
2073 side: order.side,
2074 time_in_force: order.time_in_force,
2075 limit_price: number(order.limit_price),
2076 stop_price: number(order.stop_price),
2077 filled_avg_price: number(order.filled_avg_price),
2078 status: order.status,
2079 legs: orders(order.legs),
2080 trail_price: number(order.trail_price),
2081 trail_percent: number(order.trail_percent),
2082 hwm: number(order.hwm),
2083 order_class: order.order_class,
2084 },
2085 };
2086 }
2087 catch (err) {
2088 throw new Error(`Order parsing failed. ${err.message}`);
2089 }
2090 }
2091 function canceled_orders(rawOrderCancelations) {
2092 return rawOrderCancelations
2093 ? rawOrderCancelations.map((value) => canceled_order(value))
2094 : undefined;
2095 }
2096 function position(rawPosition) {
2097 if (!rawPosition) {
2098 return undefined;
2099 }
2100 try {
2101 return {
2102 ...rawPosition,
2103 raw: () => rawPosition,
2104 avg_entry_price: number(rawPosition.avg_entry_price),
2105 qty: number(rawPosition.qty),
2106 side: rawPosition.side,
2107 market_value: number(rawPosition.market_value),
2108 cost_basis: number(rawPosition.cost_basis),
2109 unrealized_pl: number(rawPosition.unrealized_pl),
2110 unrealized_plpc: number(rawPosition.unrealized_plpc),
2111 unrealized_intraday_pl: number(rawPosition.unrealized_intraday_pl),
2112 unrealized_intraday_plpc: number(rawPosition.unrealized_intraday_plpc),
2113 current_price: number(rawPosition.current_price),
2114 lastday_price: number(rawPosition.lastday_price),
2115 change_today: number(rawPosition.change_today),
2116 };
2117 }
2118 catch (err) {
2119 throw new Error(`Position parsing failed. ${err.message}`);
2120 }
2121 }
2122 function positions(rawPositions) {
2123 return rawPositions ? rawPositions.map((pos) => position(pos)) : undefined;
2124 }
2125 function tradeActivity(rawTradeActivity) {
2126 if (!rawTradeActivity) {
2127 return undefined;
2128 }
2129 try {
2130 return {
2131 ...rawTradeActivity,
2132 raw: () => rawTradeActivity,
2133 cum_qty: number(rawTradeActivity.cum_qty),
2134 leaves_qty: number(rawTradeActivity.leaves_qty),
2135 price: number(rawTradeActivity.price),
2136 qty: number(rawTradeActivity.qty),
2137 side: rawTradeActivity.side,
2138 type: rawTradeActivity.type,
2139 };
2140 }
2141 catch (err) {
2142 throw new Error(`TradeActivity parsing failed. ${err.message}`);
2143 }
2144 }
2145 function nonTradeActivity(rawNonTradeActivity) {
2146 if (!rawNonTradeActivity) {
2147 return undefined;
2148 }
2149 try {
2150 return {
2151 ...rawNonTradeActivity,
2152 raw: () => rawNonTradeActivity,
2153 net_amount: number(rawNonTradeActivity.net_amount),
2154 qty: number(rawNonTradeActivity.qty),
2155 per_share_amount: number(rawNonTradeActivity.per_share_amount),
2156 };
2157 }
2158 catch (err) {
2159 throw new Error(`NonTradeActivity parsing failed. ${err.message}`);
2160 }
2161 }
2162 function activities(rawActivities) {
2163 if (!rawActivities) {
2164 return undefined;
2165 }
2166 try {
2167 return rawActivities.map((rawActivity) => rawActivity.activity_type === 'FILL'
2168 ? tradeActivity(rawActivity)
2169 : nonTradeActivity(rawActivity));
2170 }
2171 catch (err) {
2172 throw new Error(`Activity parsing failed. ${err.message}`);
2173 }
2174 }
2175 function pageOfTrades(page) {
2176 if (!page) {
2177 return undefined;
2178 }
2179 try {
2180 return {
2181 raw: () => page,
2182 trades: (page.trades == null ? [] : page.trades).map((trade) => ({
2183 raw: () => trade,
2184 ...trade,
2185 t: new Date(trade.t),
2186 })),
2187 symbol: page.symbol,
2188 next_page_token: page.next_page_token,
2189 };
2190 }
2191 catch (err) {
2192 throw new Error(`PageOfTrades parsing failed "${err.message}"`);
2193 }
2194 }
2195 function pageOfQuotes(page) {
2196 if (!page) {
2197 return undefined;
2198 }
2199 try {
2200 return {
2201 raw: () => page,
2202 quotes: (page.quotes == null ? [] : page.quotes).map((quote) => ({
2203 raw: () => quote,
2204 ...quote,
2205 t: new Date(quote.t),
2206 })),
2207 symbol: page.symbol,
2208 next_page_token: page.next_page_token,
2209 };
2210 }
2211 catch (err) {
2212 throw new Error(`PageOfTrades parsing failed "${err.message}"`);
2213 }
2214 }
2215 function pageOfBars(page) {
2216 if (!page) {
2217 return undefined;
2218 }
2219 try {
2220 return {
2221 raw: () => page,
2222 bars: (page.bars == null ? [] : page.bars).map((bar) => ({
2223 raw: () => bar,
2224 ...bar,
2225 t: new Date(bar.t),
2226 })),
2227 symbol: page.symbol,
2228 next_page_token: page.next_page_token,
2229 };
2230 }
2231 catch (err) {
2232 throw new Error(`PageOfTrades parsing failed "${err.message}"`);
2233 }
2234 }
2235 function snapshot(raw) {
2236 if (!raw) {
2237 return undefined;
2238 }
2239 try {
2240 return {
2241 ...raw,
2242 raw: () => raw,
2243 latestTrade: raw.latestTrade
2244 ? {
2245 ...raw.latestTrade,
2246 t: new Date(raw.latestTrade.t),
2247 }
2248 : null,
2249 latestQuote: raw.latestQuote
2250 ? {
2251 ...raw.latestQuote,
2252 t: new Date(raw.latestQuote.t),
2253 }
2254 : null,
2255 minuteBar: raw.minuteBar
2256 ? {
2257 ...raw.minuteBar,
2258 t: new Date(raw.minuteBar.t),
2259 }
2260 : null,
2261 dailyBar: raw.dailyBar
2262 ? {
2263 ...raw.dailyBar,
2264 t: new Date(raw.dailyBar.t),
2265 }
2266 : null,
2267 prevDailyBar: raw.prevDailyBar
2268 ? {
2269 ...raw.prevDailyBar,
2270 t: new Date(raw.prevDailyBar.t),
2271 }
2272 : null,
2273 };
2274 }
2275 catch (err) {
2276 throw new Error(`Snapshot parsing failed "${err.message}"`);
2277 }
2278 }
2279 function snapshots(raw) {
2280 let parsed = {};
2281 for (let [key, value] of Object.entries(raw)) {
2282 parsed[key] = snapshot(value);
2283 }
2284 return parsed;
2285 }
2286 function number(numStr) {
2287 if (typeof numStr === 'undefined' || numStr == null) {
2288 return numStr;
2289 }
2290 const value = parseFloat(numStr);
2291 if (Number.isNaN(value)) {
2292 return null;
2293 }
2294 return value;
2295 }
2296 function trade_update(rawTradeUpdate) {
2297 if (!rawTradeUpdate)
2298 return undefined;
2299 return {
2300 raw: () => rawTradeUpdate,
2301 event: rawTradeUpdate.event,
2302 execution_id: rawTradeUpdate.execution_id,
2303 order: order(rawTradeUpdate.order),
2304 ...(rawTradeUpdate.event_id && {
2305 event_id: number(rawTradeUpdate.event_id),
2306 }),
2307 ...(rawTradeUpdate.at && { at: new Date(rawTradeUpdate.at) }),
2308 ...(rawTradeUpdate.timestamp && {
2309 timestamp: new Date(rawTradeUpdate.timestamp),
2310 }),
2311 ...(rawTradeUpdate.position_qty && {
2312 position_qty: number(rawTradeUpdate.position_qty),
2313 }),
2314 ...(rawTradeUpdate.price && { price: number(rawTradeUpdate.price) }),
2315 ...(rawTradeUpdate.qty && { qty: number(rawTradeUpdate.qty) }),
2316 };
2317 }
2318 var parse = {
2319 account,
2320 activities,
2321 clock,
2322 nonTradeActivity,
2323 order,
2324 orders,
2325 canceled_orders,
2326 position,
2327 positions,
2328 tradeActivity,
2329 pageOfTrades,
2330 pageOfQuotes,
2331 pageOfBars,
2332 snapshot,
2333 snapshots,
2334 trade_update,
2335 latestTrade,
2336 };
2337
2338 function unfetch_module(e,n){return n=n||{},new Promise(function(t,r){var s=new XMLHttpRequest,o=[],u=[],i={},a=function(){return {ok:2==(s.status/100|0),statusText:s.statusText,status:s.status,url:s.responseURL,text:function(){return Promise.resolve(s.responseText)},json:function(){return Promise.resolve(s.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([s.response]))},clone:a,headers:{keys:function(){return o},entries:function(){return u},get:function(e){return i[e.toLowerCase()]},has:function(e){return e.toLowerCase()in i}}}};for(var l in s.open(n.method||"get",e,!0),s.onload=function(){s.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,n,t){o.push(n=n.toLowerCase()),u.push([n,t]),i[n]=i[n]?i[n]+","+t:t;}),t(a());},s.onerror=r,s.withCredentials="include"==n.credentials,n.headers)s.setRequestHeader(l,n.headers[l]);s.send(n.body||null);})}
2339
2340 var unfetch_module$1 = /*#__PURE__*/Object.freeze({
2341 __proto__: null,
2342 'default': unfetch_module
2343 });
2344
2345 var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(unfetch_module$1);
2346
2347 var browser$1 = self.fetch || (self.fetch = require$$0$2.default || require$$0$2);
2348
2349 const endpoints = {
2350 rest: {
2351 beta: 'https://data.alpaca.markets/v1beta1',
2352 account: 'https://api.alpaca.markets/v2',
2353 market_data_v2: 'https://data.alpaca.markets/v2',
2354 market_data_v1: 'https://data.alpaca.markets/v1',
2355 },
2356 websocket: {
2357 account: 'wss://api.alpaca.markets/stream',
2358 market_data: (source = 'iex') => `wss://stream.data.alpaca.markets/v2/${source}`,
2359 },
2360 };
2361
2362 var load = function (received, defaults, onto = {}) {
2363 var k, ref, v;
2364
2365 for (k in defaults) {
2366 v = defaults[k];
2367 onto[k] = (ref = received[k]) != null ? ref : v;
2368 }
2369
2370 return onto;
2371 };
2372
2373 var overwrite = function (received, defaults, onto = {}) {
2374 var k, v;
2375
2376 for (k in received) {
2377 v = received[k];
2378
2379 if (defaults[k] !== void 0) {
2380 onto[k] = v;
2381 }
2382 }
2383
2384 return onto;
2385 };
2386
2387 var parser$8 = {
2388 load: load,
2389 overwrite: overwrite
2390 };
2391
2392 var DLList$2;
2393 DLList$2 = class DLList {
2394 constructor(incr, decr) {
2395 this.incr = incr;
2396 this.decr = decr;
2397 this._first = null;
2398 this._last = null;
2399 this.length = 0;
2400 }
2401
2402 push(value) {
2403 var node;
2404 this.length++;
2405
2406 if (typeof this.incr === "function") {
2407 this.incr();
2408 }
2409
2410 node = {
2411 value,
2412 prev: this._last,
2413 next: null
2414 };
2415
2416 if (this._last != null) {
2417 this._last.next = node;
2418 this._last = node;
2419 } else {
2420 this._first = this._last = node;
2421 }
2422
2423 return void 0;
2424 }
2425
2426 shift() {
2427 var value;
2428
2429 if (this._first == null) {
2430 return;
2431 } else {
2432 this.length--;
2433
2434 if (typeof this.decr === "function") {
2435 this.decr();
2436 }
2437 }
2438
2439 value = this._first.value;
2440
2441 if ((this._first = this._first.next) != null) {
2442 this._first.prev = null;
2443 } else {
2444 this._last = null;
2445 }
2446
2447 return value;
2448 }
2449
2450 first() {
2451 if (this._first != null) {
2452 return this._first.value;
2453 }
2454 }
2455
2456 getArray() {
2457 var node, ref, results;
2458 node = this._first;
2459 results = [];
2460
2461 while (node != null) {
2462 results.push((ref = node, node = node.next, ref.value));
2463 }
2464
2465 return results;
2466 }
2467
2468 forEachShift(cb) {
2469 var node;
2470 node = this.shift();
2471
2472 while (node != null) {
2473 cb(node), node = this.shift();
2474 }
2475
2476 return void 0;
2477 }
2478
2479 debug() {
2480 var node, ref, ref1, ref2, results;
2481 node = this._first;
2482 results = [];
2483
2484 while (node != null) {
2485 results.push((ref = node, node = node.next, {
2486 value: ref.value,
2487 prev: (ref1 = ref.prev) != null ? ref1.value : void 0,
2488 next: (ref2 = ref.next) != null ? ref2.value : void 0
2489 }));
2490 }
2491
2492 return results;
2493 }
2494
2495 };
2496 var DLList_1 = DLList$2;
2497
2498 function asyncGeneratorStep$8(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
2499
2500 function _asyncToGenerator$8(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$8(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$8(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
2501
2502 var Events$6;
2503 Events$6 = class Events {
2504 constructor(instance) {
2505 this.instance = instance;
2506 this._events = {};
2507
2508 if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) {
2509 throw new Error("An Emitter already exists for this object");
2510 }
2511
2512 this.instance.on = (name, cb) => {
2513 return this._addListener(name, "many", cb);
2514 };
2515
2516 this.instance.once = (name, cb) => {
2517 return this._addListener(name, "once", cb);
2518 };
2519
2520 this.instance.removeAllListeners = (name = null) => {
2521 if (name != null) {
2522 return delete this._events[name];
2523 } else {
2524 return this._events = {};
2525 }
2526 };
2527 }
2528
2529 _addListener(name, status, cb) {
2530 var base;
2531
2532 if ((base = this._events)[name] == null) {
2533 base[name] = [];
2534 }
2535
2536 this._events[name].push({
2537 cb,
2538 status
2539 });
2540
2541 return this.instance;
2542 }
2543
2544 listenerCount(name) {
2545 if (this._events[name] != null) {
2546 return this._events[name].length;
2547 } else {
2548 return 0;
2549 }
2550 }
2551
2552 trigger(name, ...args) {
2553 var _this = this;
2554
2555 return _asyncToGenerator$8(function* () {
2556 var e, promises;
2557
2558 try {
2559 if (name !== "debug") {
2560 _this.trigger("debug", `Event triggered: ${name}`, args);
2561 }
2562
2563 if (_this._events[name] == null) {
2564 return;
2565 }
2566
2567 _this._events[name] = _this._events[name].filter(function (listener) {
2568 return listener.status !== "none";
2569 });
2570 promises = _this._events[name].map(
2571 /*#__PURE__*/
2572 function () {
2573 var _ref = _asyncToGenerator$8(function* (listener) {
2574 var e, returned;
2575
2576 if (listener.status === "none") {
2577 return;
2578 }
2579
2580 if (listener.status === "once") {
2581 listener.status = "none";
2582 }
2583
2584 try {
2585 returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0;
2586
2587 if (typeof (returned != null ? returned.then : void 0) === "function") {
2588 return yield returned;
2589 } else {
2590 return returned;
2591 }
2592 } catch (error) {
2593 e = error;
2594
2595 if ("name" !== "error") {
2596 _this.trigger("error", e);
2597 }
2598
2599 return null;
2600 }
2601 });
2602
2603 return function (_x) {
2604 return _ref.apply(this, arguments);
2605 };
2606 }());
2607 return (yield Promise.all(promises)).find(function (x) {
2608 return x != null;
2609 });
2610 } catch (error) {
2611 e = error;
2612
2613 {
2614 _this.trigger("error", e);
2615 }
2616
2617 return null;
2618 }
2619 })();
2620 }
2621
2622 };
2623 var Events_1 = Events$6;
2624
2625 var DLList$1, Events$5, Queues$1;
2626 DLList$1 = DLList_1;
2627 Events$5 = Events_1;
2628 Queues$1 = class Queues {
2629 constructor(num_priorities) {
2630 this.Events = new Events$5(this);
2631 this._length = 0;
2632
2633 this._lists = function () {
2634 var j, ref, results;
2635 results = [];
2636
2637 for (j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; 1 <= ref ? ++j : --j) {
2638 results.push(new DLList$1(() => {
2639 return this.incr();
2640 }, () => {
2641 return this.decr();
2642 }));
2643 }
2644
2645 return results;
2646 }.call(this);
2647 }
2648
2649 incr() {
2650 if (this._length++ === 0) {
2651 return this.Events.trigger("leftzero");
2652 }
2653 }
2654
2655 decr() {
2656 if (--this._length === 0) {
2657 return this.Events.trigger("zero");
2658 }
2659 }
2660
2661 push(job) {
2662 return this._lists[job.options.priority].push(job);
2663 }
2664
2665 queued(priority) {
2666 if (priority != null) {
2667 return this._lists[priority].length;
2668 } else {
2669 return this._length;
2670 }
2671 }
2672
2673 shiftAll(fn) {
2674 return this._lists.forEach(function (list) {
2675 return list.forEachShift(fn);
2676 });
2677 }
2678
2679 getFirst(arr = this._lists) {
2680 var j, len, list;
2681
2682 for (j = 0, len = arr.length; j < len; j++) {
2683 list = arr[j];
2684
2685 if (list.length > 0) {
2686 return list;
2687 }
2688 }
2689
2690 return [];
2691 }
2692
2693 shiftLastFrom(priority) {
2694 return this.getFirst(this._lists.slice(priority).reverse()).shift();
2695 }
2696
2697 };
2698 var Queues_1 = Queues$1;
2699
2700 var BottleneckError$4;
2701 BottleneckError$4 = class BottleneckError extends Error {};
2702 var BottleneckError_1 = BottleneckError$4;
2703
2704 function asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
2705
2706 function _asyncToGenerator$7(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$7(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
2707
2708 var BottleneckError$3, DEFAULT_PRIORITY$1, Job$1, NUM_PRIORITIES$1, parser$7;
2709 NUM_PRIORITIES$1 = 10;
2710 DEFAULT_PRIORITY$1 = 5;
2711 parser$7 = parser$8;
2712 BottleneckError$3 = BottleneckError_1;
2713 Job$1 = class Job {
2714 constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) {
2715 this.task = task;
2716 this.args = args;
2717 this.rejectOnDrop = rejectOnDrop;
2718 this.Events = Events;
2719 this._states = _states;
2720 this.Promise = Promise;
2721 this.options = parser$7.load(options, jobDefaults);
2722 this.options.priority = this._sanitizePriority(this.options.priority);
2723
2724 if (this.options.id === jobDefaults.id) {
2725 this.options.id = `${this.options.id}-${this._randomIndex()}`;
2726 }
2727
2728 this.promise = new this.Promise((_resolve, _reject) => {
2729 this._resolve = _resolve;
2730 this._reject = _reject;
2731 });
2732 this.retryCount = 0;
2733 }
2734
2735 _sanitizePriority(priority) {
2736 var sProperty;
2737 sProperty = ~~priority !== priority ? DEFAULT_PRIORITY$1 : priority;
2738
2739 if (sProperty < 0) {
2740 return 0;
2741 } else if (sProperty > NUM_PRIORITIES$1 - 1) {
2742 return NUM_PRIORITIES$1 - 1;
2743 } else {
2744 return sProperty;
2745 }
2746 }
2747
2748 _randomIndex() {
2749 return Math.random().toString(36).slice(2);
2750 }
2751
2752 doDrop({
2753 error,
2754 message = "This job has been dropped by Bottleneck"
2755 } = {}) {
2756 if (this._states.remove(this.options.id)) {
2757 if (this.rejectOnDrop) {
2758 this._reject(error != null ? error : new BottleneckError$3(message));
2759 }
2760
2761 this.Events.trigger("dropped", {
2762 args: this.args,
2763 options: this.options,
2764 task: this.task,
2765 promise: this.promise
2766 });
2767 return true;
2768 } else {
2769 return false;
2770 }
2771 }
2772
2773 _assertStatus(expected) {
2774 var status;
2775 status = this._states.jobStatus(this.options.id);
2776
2777 if (!(status === expected || expected === "DONE" && status === null)) {
2778 throw new BottleneckError$3(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`);
2779 }
2780 }
2781
2782 doReceive() {
2783 this._states.start(this.options.id);
2784
2785 return this.Events.trigger("received", {
2786 args: this.args,
2787 options: this.options
2788 });
2789 }
2790
2791 doQueue(reachedHWM, blocked) {
2792 this._assertStatus("RECEIVED");
2793
2794 this._states.next(this.options.id);
2795
2796 return this.Events.trigger("queued", {
2797 args: this.args,
2798 options: this.options,
2799 reachedHWM,
2800 blocked
2801 });
2802 }
2803
2804 doRun() {
2805 if (this.retryCount === 0) {
2806 this._assertStatus("QUEUED");
2807
2808 this._states.next(this.options.id);
2809 } else {
2810 this._assertStatus("EXECUTING");
2811 }
2812
2813 return this.Events.trigger("scheduled", {
2814 args: this.args,
2815 options: this.options
2816 });
2817 }
2818
2819 doExecute(chained, clearGlobalState, run, free) {
2820 var _this = this;
2821
2822 return _asyncToGenerator$7(function* () {
2823 var error, eventInfo, passed;
2824
2825 if (_this.retryCount === 0) {
2826 _this._assertStatus("RUNNING");
2827
2828 _this._states.next(_this.options.id);
2829 } else {
2830 _this._assertStatus("EXECUTING");
2831 }
2832
2833 eventInfo = {
2834 args: _this.args,
2835 options: _this.options,
2836 retryCount: _this.retryCount
2837 };
2838
2839 _this.Events.trigger("executing", eventInfo);
2840
2841 try {
2842 passed = yield chained != null ? chained.schedule(_this.options, _this.task, ..._this.args) : _this.task(..._this.args);
2843
2844 if (clearGlobalState()) {
2845 _this.doDone(eventInfo);
2846
2847 yield free(_this.options, eventInfo);
2848
2849 _this._assertStatus("DONE");
2850
2851 return _this._resolve(passed);
2852 }
2853 } catch (error1) {
2854 error = error1;
2855 return _this._onFailure(error, eventInfo, clearGlobalState, run, free);
2856 }
2857 })();
2858 }
2859
2860 doExpire(clearGlobalState, run, free) {
2861 var error, eventInfo;
2862
2863 if (this._states.jobStatus(this.options.id === "RUNNING")) {
2864 this._states.next(this.options.id);
2865 }
2866
2867 this._assertStatus("EXECUTING");
2868
2869 eventInfo = {
2870 args: this.args,
2871 options: this.options,
2872 retryCount: this.retryCount
2873 };
2874 error = new BottleneckError$3(`This job timed out after ${this.options.expiration} ms.`);
2875 return this._onFailure(error, eventInfo, clearGlobalState, run, free);
2876 }
2877
2878 _onFailure(error, eventInfo, clearGlobalState, run, free) {
2879 var _this2 = this;
2880
2881 return _asyncToGenerator$7(function* () {
2882 var retry, retryAfter;
2883
2884 if (clearGlobalState()) {
2885 retry = yield _this2.Events.trigger("failed", error, eventInfo);
2886
2887 if (retry != null) {
2888 retryAfter = ~~retry;
2889
2890 _this2.Events.trigger("retry", `Retrying ${_this2.options.id} after ${retryAfter} ms`, eventInfo);
2891
2892 _this2.retryCount++;
2893 return run(retryAfter);
2894 } else {
2895 _this2.doDone(eventInfo);
2896
2897 yield free(_this2.options, eventInfo);
2898
2899 _this2._assertStatus("DONE");
2900
2901 return _this2._reject(error);
2902 }
2903 }
2904 })();
2905 }
2906
2907 doDone(eventInfo) {
2908 this._assertStatus("EXECUTING");
2909
2910 this._states.next(this.options.id);
2911
2912 return this.Events.trigger("done", eventInfo);
2913 }
2914
2915 };
2916 var Job_1 = Job$1;
2917
2918 function asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
2919
2920 function _asyncToGenerator$6(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
2921
2922 var BottleneckError$2, LocalDatastore$1, parser$6;
2923 parser$6 = parser$8;
2924 BottleneckError$2 = BottleneckError_1;
2925 LocalDatastore$1 = class LocalDatastore {
2926 constructor(instance, storeOptions, storeInstanceOptions) {
2927 this.instance = instance;
2928 this.storeOptions = storeOptions;
2929 this.clientId = this.instance._randomIndex();
2930 parser$6.load(storeInstanceOptions, storeInstanceOptions, this);
2931 this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now();
2932 this._running = 0;
2933 this._done = 0;
2934 this._unblockTime = 0;
2935 this.ready = this.Promise.resolve();
2936 this.clients = {};
2937
2938 this._startHeartbeat();
2939 }
2940
2941 _startHeartbeat() {
2942 var base;
2943
2944 if (this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null)) {
2945 return typeof (base = this.heartbeat = setInterval(() => {
2946 var amount, incr, maximum, now, reservoir;
2947 now = Date.now();
2948
2949 if (this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) {
2950 this._lastReservoirRefresh = now;
2951 this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount;
2952
2953 this.instance._drainAll(this.computeCapacity());
2954 }
2955
2956 if (this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) {
2957 var _this$storeOptions = this.storeOptions;
2958 amount = _this$storeOptions.reservoirIncreaseAmount;
2959 maximum = _this$storeOptions.reservoirIncreaseMaximum;
2960 reservoir = _this$storeOptions.reservoir;
2961 this._lastReservoirIncrease = now;
2962 incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount;
2963
2964 if (incr > 0) {
2965 this.storeOptions.reservoir += incr;
2966 return this.instance._drainAll(this.computeCapacity());
2967 }
2968 }
2969 }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0;
2970 } else {
2971 return clearInterval(this.heartbeat);
2972 }
2973 }
2974
2975 __publish__(message) {
2976 var _this = this;
2977
2978 return _asyncToGenerator$6(function* () {
2979 yield _this.yieldLoop();
2980 return _this.instance.Events.trigger("message", message.toString());
2981 })();
2982 }
2983
2984 __disconnect__(flush) {
2985 var _this2 = this;
2986
2987 return _asyncToGenerator$6(function* () {
2988 yield _this2.yieldLoop();
2989 clearInterval(_this2.heartbeat);
2990 return _this2.Promise.resolve();
2991 })();
2992 }
2993
2994 yieldLoop(t = 0) {
2995 return new this.Promise(function (resolve, reject) {
2996 return setTimeout(resolve, t);
2997 });
2998 }
2999
3000 computePenalty() {
3001 var ref;
3002 return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000;
3003 }
3004
3005 __updateSettings__(options) {
3006 var _this3 = this;
3007
3008 return _asyncToGenerator$6(function* () {
3009 yield _this3.yieldLoop();
3010 parser$6.overwrite(options, options, _this3.storeOptions);
3011
3012 _this3._startHeartbeat();
3013
3014 _this3.instance._drainAll(_this3.computeCapacity());
3015
3016 return true;
3017 })();
3018 }
3019
3020 __running__() {
3021 var _this4 = this;
3022
3023 return _asyncToGenerator$6(function* () {
3024 yield _this4.yieldLoop();
3025 return _this4._running;
3026 })();
3027 }
3028
3029 __queued__() {
3030 var _this5 = this;
3031
3032 return _asyncToGenerator$6(function* () {
3033 yield _this5.yieldLoop();
3034 return _this5.instance.queued();
3035 })();
3036 }
3037
3038 __done__() {
3039 var _this6 = this;
3040
3041 return _asyncToGenerator$6(function* () {
3042 yield _this6.yieldLoop();
3043 return _this6._done;
3044 })();
3045 }
3046
3047 __groupCheck__(time) {
3048 var _this7 = this;
3049
3050 return _asyncToGenerator$6(function* () {
3051 yield _this7.yieldLoop();
3052 return _this7._nextRequest + _this7.timeout < time;
3053 })();
3054 }
3055
3056 computeCapacity() {
3057 var maxConcurrent, reservoir;
3058 var _this$storeOptions2 = this.storeOptions;
3059 maxConcurrent = _this$storeOptions2.maxConcurrent;
3060 reservoir = _this$storeOptions2.reservoir;
3061
3062 if (maxConcurrent != null && reservoir != null) {
3063 return Math.min(maxConcurrent - this._running, reservoir);
3064 } else if (maxConcurrent != null) {
3065 return maxConcurrent - this._running;
3066 } else if (reservoir != null) {
3067 return reservoir;
3068 } else {
3069 return null;
3070 }
3071 }
3072
3073 conditionsCheck(weight) {
3074 var capacity;
3075 capacity = this.computeCapacity();
3076 return capacity == null || weight <= capacity;
3077 }
3078
3079 __incrementReservoir__(incr) {
3080 var _this8 = this;
3081
3082 return _asyncToGenerator$6(function* () {
3083 var reservoir;
3084 yield _this8.yieldLoop();
3085 reservoir = _this8.storeOptions.reservoir += incr;
3086
3087 _this8.instance._drainAll(_this8.computeCapacity());
3088
3089 return reservoir;
3090 })();
3091 }
3092
3093 __currentReservoir__() {
3094 var _this9 = this;
3095
3096 return _asyncToGenerator$6(function* () {
3097 yield _this9.yieldLoop();
3098 return _this9.storeOptions.reservoir;
3099 })();
3100 }
3101
3102 isBlocked(now) {
3103 return this._unblockTime >= now;
3104 }
3105
3106 check(weight, now) {
3107 return this.conditionsCheck(weight) && this._nextRequest - now <= 0;
3108 }
3109
3110 __check__(weight) {
3111 var _this10 = this;
3112
3113 return _asyncToGenerator$6(function* () {
3114 var now;
3115 yield _this10.yieldLoop();
3116 now = Date.now();
3117 return _this10.check(weight, now);
3118 })();
3119 }
3120
3121 __register__(index, weight, expiration) {
3122 var _this11 = this;
3123
3124 return _asyncToGenerator$6(function* () {
3125 var now, wait;
3126 yield _this11.yieldLoop();
3127 now = Date.now();
3128
3129 if (_this11.conditionsCheck(weight)) {
3130 _this11._running += weight;
3131
3132 if (_this11.storeOptions.reservoir != null) {
3133 _this11.storeOptions.reservoir -= weight;
3134 }
3135
3136 wait = Math.max(_this11._nextRequest - now, 0);
3137 _this11._nextRequest = now + wait + _this11.storeOptions.minTime;
3138 return {
3139 success: true,
3140 wait,
3141 reservoir: _this11.storeOptions.reservoir
3142 };
3143 } else {
3144 return {
3145 success: false
3146 };
3147 }
3148 })();
3149 }
3150
3151 strategyIsBlock() {
3152 return this.storeOptions.strategy === 3;
3153 }
3154
3155 __submit__(queueLength, weight) {
3156 var _this12 = this;
3157
3158 return _asyncToGenerator$6(function* () {
3159 var blocked, now, reachedHWM;
3160 yield _this12.yieldLoop();
3161
3162 if (_this12.storeOptions.maxConcurrent != null && weight > _this12.storeOptions.maxConcurrent) {
3163 throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${_this12.storeOptions.maxConcurrent}`);
3164 }
3165
3166 now = Date.now();
3167 reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now);
3168 blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now));
3169
3170 if (blocked) {
3171 _this12._unblockTime = now + _this12.computePenalty();
3172 _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime;
3173
3174 _this12.instance._dropAllQueued();
3175 }
3176
3177 return {
3178 reachedHWM,
3179 blocked,
3180 strategy: _this12.storeOptions.strategy
3181 };
3182 })();
3183 }
3184
3185 __free__(index, weight) {
3186 var _this13 = this;
3187
3188 return _asyncToGenerator$6(function* () {
3189 yield _this13.yieldLoop();
3190 _this13._running -= weight;
3191 _this13._done += weight;
3192
3193 _this13.instance._drainAll(_this13.computeCapacity());
3194
3195 return {
3196 running: _this13._running
3197 };
3198 })();
3199 }
3200
3201 };
3202 var LocalDatastore_1 = LocalDatastore$1;
3203
3204 var require$$0$1 = {
3205 "blacklist_client.lua": "local blacklist = ARGV[num_static_argv + 1]\n\nif redis.call('zscore', client_last_seen_key, blacklist) then\n redis.call('zadd', client_last_seen_key, 0, blacklist)\nend\n\n\nreturn {}\n",
3206 "check.lua": "local weight = tonumber(ARGV[num_static_argv + 1])\n\nlocal capacity = process_tick(now, false)['capacity']\nlocal nextRequest = tonumber(redis.call('hget', settings_key, 'nextRequest'))\n\nreturn conditions_check(capacity, weight) and nextRequest - now <= 0\n",
3207 "conditions_check.lua": "local conditions_check = function (capacity, weight)\n return capacity == nil or weight <= capacity\nend\n",
3208 "current_reservoir.lua": "return process_tick(now, false)['reservoir']\n",
3209 "done.lua": "process_tick(now, false)\n\nreturn tonumber(redis.call('hget', settings_key, 'done'))\n",
3210 "free.lua": "local index = ARGV[num_static_argv + 1]\n\nredis.call('zadd', job_expirations_key, 0, index)\n\nreturn process_tick(now, false)['running']\n",
3211 "get_time.lua": "redis.replicate_commands()\n\nlocal get_time = function ()\n local time = redis.call('time')\n\n return tonumber(time[1]..string.sub(time[2], 1, 3))\nend\n",
3212 "group_check.lua": "return not (redis.call('exists', settings_key) == 1)\n",
3213 "heartbeat.lua": "process_tick(now, true)\n",
3214 "increment_reservoir.lua": "local incr = tonumber(ARGV[num_static_argv + 1])\n\nredis.call('hincrby', settings_key, 'reservoir', incr)\n\nlocal reservoir = process_tick(now, true)['reservoir']\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn reservoir\n",
3215 "init.lua": "local clear = tonumber(ARGV[num_static_argv + 1])\nlocal limiter_version = ARGV[num_static_argv + 2]\nlocal num_local_argv = num_static_argv + 2\n\nif clear == 1 then\n redis.call('del', unpack(KEYS))\nend\n\nif redis.call('exists', settings_key) == 0 then\n -- Create\n local args = {'hmset', settings_key}\n\n for i = num_local_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\n end\n\n redis.call(unpack(args))\n redis.call('hmset', settings_key,\n 'nextRequest', now,\n 'lastReservoirRefresh', now,\n 'lastReservoirIncrease', now,\n 'running', 0,\n 'done', 0,\n 'unblockTime', 0,\n 'capacityPriorityCounter', 0\n )\n\nelse\n -- Apply migrations\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'version'\n )\n local id = settings[1]\n local current_version = settings[2]\n\n if current_version ~= limiter_version then\n local version_digits = {}\n for k, v in string.gmatch(current_version, \"([^.]+)\") do\n table.insert(version_digits, tonumber(k))\n end\n\n -- 2.10.0\n if version_digits[2] < 10 then\n redis.call('hsetnx', settings_key, 'reservoirRefreshInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirRefreshAmount', '')\n redis.call('hsetnx', settings_key, 'lastReservoirRefresh', '')\n redis.call('hsetnx', settings_key, 'done', 0)\n redis.call('hset', settings_key, 'version', '2.10.0')\n end\n\n -- 2.11.1\n if version_digits[2] < 11 or (version_digits[2] == 11 and version_digits[3] < 1) then\n if redis.call('hstrlen', settings_key, 'lastReservoirRefresh') == 0 then\n redis.call('hmset', settings_key,\n 'lastReservoirRefresh', now,\n 'version', '2.11.1'\n )\n end\n end\n\n -- 2.14.0\n if version_digits[2] < 14 then\n local old_running_key = 'b_'..id..'_running'\n local old_executing_key = 'b_'..id..'_executing'\n\n if redis.call('exists', old_running_key) == 1 then\n redis.call('rename', old_running_key, job_weights_key)\n end\n if redis.call('exists', old_executing_key) == 1 then\n redis.call('rename', old_executing_key, job_expirations_key)\n end\n redis.call('hset', settings_key, 'version', '2.14.0')\n end\n\n -- 2.15.2\n if version_digits[2] < 15 or (version_digits[2] == 15 and version_digits[3] < 2) then\n redis.call('hsetnx', settings_key, 'capacityPriorityCounter', 0)\n redis.call('hset', settings_key, 'version', '2.15.2')\n end\n\n -- 2.17.0\n if version_digits[2] < 17 then\n redis.call('hsetnx', settings_key, 'clientTimeout', 10000)\n redis.call('hset', settings_key, 'version', '2.17.0')\n end\n\n -- 2.18.0\n if version_digits[2] < 18 then\n redis.call('hsetnx', settings_key, 'reservoirIncreaseInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirIncreaseAmount', '')\n redis.call('hsetnx', settings_key, 'reservoirIncreaseMaximum', '')\n redis.call('hsetnx', settings_key, 'lastReservoirIncrease', now)\n redis.call('hset', settings_key, 'version', '2.18.0')\n end\n\n end\n\n process_tick(now, false)\nend\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n",
3216 "process_tick.lua": "local process_tick = function (now, always_publish)\n\n local compute_capacity = function (maxConcurrent, running, reservoir)\n if maxConcurrent ~= nil and reservoir ~= nil then\n return math.min((maxConcurrent - running), reservoir)\n elseif maxConcurrent ~= nil then\n return maxConcurrent - running\n elseif reservoir ~= nil then\n return reservoir\n else\n return nil\n end\n end\n\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'running',\n 'reservoir',\n 'reservoirRefreshInterval',\n 'reservoirRefreshAmount',\n 'lastReservoirRefresh',\n 'reservoirIncreaseInterval',\n 'reservoirIncreaseAmount',\n 'reservoirIncreaseMaximum',\n 'lastReservoirIncrease',\n 'capacityPriorityCounter',\n 'clientTimeout'\n )\n local id = settings[1]\n local maxConcurrent = tonumber(settings[2])\n local running = tonumber(settings[3])\n local reservoir = tonumber(settings[4])\n local reservoirRefreshInterval = tonumber(settings[5])\n local reservoirRefreshAmount = tonumber(settings[6])\n local lastReservoirRefresh = tonumber(settings[7])\n local reservoirIncreaseInterval = tonumber(settings[8])\n local reservoirIncreaseAmount = tonumber(settings[9])\n local reservoirIncreaseMaximum = tonumber(settings[10])\n local lastReservoirIncrease = tonumber(settings[11])\n local capacityPriorityCounter = tonumber(settings[12])\n local clientTimeout = tonumber(settings[13])\n\n local initial_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n --\n -- Process 'running' changes\n --\n local expired = redis.call('zrangebyscore', job_expirations_key, '-inf', '('..now)\n\n if #expired > 0 then\n redis.call('zremrangebyscore', job_expirations_key, '-inf', '('..now)\n\n local flush_batch = function (batch, acc)\n local weights = redis.call('hmget', job_weights_key, unpack(batch))\n redis.call('hdel', job_weights_key, unpack(batch))\n local clients = redis.call('hmget', job_clients_key, unpack(batch))\n redis.call('hdel', job_clients_key, unpack(batch))\n\n -- Calculate sum of removed weights\n for i = 1, #weights do\n acc['total'] = acc['total'] + (tonumber(weights[i]) or 0)\n end\n\n -- Calculate sum of removed weights by client\n local client_weights = {}\n for i = 1, #clients do\n local removed = tonumber(weights[i]) or 0\n if removed > 0 then\n acc['client_weights'][clients[i]] = (acc['client_weights'][clients[i]] or 0) + removed\n end\n end\n end\n\n local acc = {\n ['total'] = 0,\n ['client_weights'] = {}\n }\n local batch_size = 1000\n\n -- Compute changes to Zsets and apply changes to Hashes\n for i = 1, #expired, batch_size do\n local batch = {}\n for j = i, math.min(i + batch_size - 1, #expired) do\n table.insert(batch, expired[j])\n end\n\n flush_batch(batch, acc)\n end\n\n -- Apply changes to Zsets\n if acc['total'] > 0 then\n redis.call('hincrby', settings_key, 'done', acc['total'])\n running = tonumber(redis.call('hincrby', settings_key, 'running', -acc['total']))\n end\n\n for client, weight in pairs(acc['client_weights']) do\n redis.call('zincrby', client_running_key, -weight, client)\n end\n end\n\n --\n -- Process 'reservoir' changes\n --\n local reservoirRefreshActive = reservoirRefreshInterval ~= nil and reservoirRefreshAmount ~= nil\n if reservoirRefreshActive and now >= lastReservoirRefresh + reservoirRefreshInterval then\n reservoir = reservoirRefreshAmount\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirRefresh', now\n )\n end\n\n local reservoirIncreaseActive = reservoirIncreaseInterval ~= nil and reservoirIncreaseAmount ~= nil\n if reservoirIncreaseActive and now >= lastReservoirIncrease + reservoirIncreaseInterval then\n local num_intervals = math.floor((now - lastReservoirIncrease) / reservoirIncreaseInterval)\n local incr = reservoirIncreaseAmount * num_intervals\n if reservoirIncreaseMaximum ~= nil then\n incr = math.min(incr, reservoirIncreaseMaximum - (reservoir or 0))\n end\n if incr > 0 then\n reservoir = (reservoir or 0) + incr\n end\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirIncrease', lastReservoirIncrease + (num_intervals * reservoirIncreaseInterval)\n )\n end\n\n --\n -- Clear unresponsive clients\n --\n local unresponsive = redis.call('zrangebyscore', client_last_seen_key, '-inf', (now - clientTimeout))\n local unresponsive_lookup = {}\n local terminated_clients = {}\n for i = 1, #unresponsive do\n unresponsive_lookup[unresponsive[i]] = true\n if tonumber(redis.call('zscore', client_running_key, unresponsive[i])) == 0 then\n table.insert(terminated_clients, unresponsive[i])\n end\n end\n if #terminated_clients > 0 then\n redis.call('zrem', client_running_key, unpack(terminated_clients))\n redis.call('hdel', client_num_queued_key, unpack(terminated_clients))\n redis.call('zrem', client_last_registered_key, unpack(terminated_clients))\n redis.call('zrem', client_last_seen_key, unpack(terminated_clients))\n end\n\n --\n -- Broadcast capacity changes\n --\n local final_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n if always_publish or (initial_capacity ~= nil and final_capacity == nil) then\n -- always_publish or was not unlimited, now unlimited\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n\n elseif initial_capacity ~= nil and final_capacity ~= nil and final_capacity > initial_capacity then\n -- capacity was increased\n -- send the capacity message to the limiter having the lowest number of running jobs\n -- the tiebreaker is the limiter having not registered a job in the longest time\n\n local lowest_concurrency_value = nil\n local lowest_concurrency_clients = {}\n local lowest_concurrency_last_registered = {}\n local client_concurrencies = redis.call('zrange', client_running_key, 0, -1, 'withscores')\n\n for i = 1, #client_concurrencies, 2 do\n local client = client_concurrencies[i]\n local concurrency = tonumber(client_concurrencies[i+1])\n\n if (\n lowest_concurrency_value == nil or lowest_concurrency_value == concurrency\n ) and (\n not unresponsive_lookup[client]\n ) and (\n tonumber(redis.call('hget', client_num_queued_key, client)) > 0\n ) then\n lowest_concurrency_value = concurrency\n table.insert(lowest_concurrency_clients, client)\n local last_registered = tonumber(redis.call('zscore', client_last_registered_key, client))\n table.insert(lowest_concurrency_last_registered, last_registered)\n end\n end\n\n if #lowest_concurrency_clients > 0 then\n local position = 1\n local earliest = lowest_concurrency_last_registered[1]\n\n for i,v in ipairs(lowest_concurrency_last_registered) do\n if v < earliest then\n position = i\n earliest = v\n end\n end\n\n local next_client = lowest_concurrency_clients[position]\n redis.call('publish', 'b_'..id,\n 'capacity-priority:'..(final_capacity or '')..\n ':'..next_client..\n ':'..capacityPriorityCounter\n )\n redis.call('hincrby', settings_key, 'capacityPriorityCounter', '1')\n else\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n end\n end\n\n return {\n ['capacity'] = final_capacity,\n ['running'] = running,\n ['reservoir'] = reservoir\n }\nend\n",
3217 "queued.lua": "local clientTimeout = tonumber(redis.call('hget', settings_key, 'clientTimeout'))\nlocal valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - clientTimeout), 'inf')\nlocal client_queued = redis.call('hmget', client_num_queued_key, unpack(valid_clients))\n\nlocal sum = 0\nfor i = 1, #client_queued do\n sum = sum + tonumber(client_queued[i])\nend\n\nreturn sum\n",
3218 "refresh_expiration.lua": "local refresh_expiration = function (now, nextRequest, groupTimeout)\n\n if groupTimeout ~= nil then\n local ttl = (nextRequest + groupTimeout) - now\n\n for i = 1, #KEYS do\n redis.call('pexpire', KEYS[i], ttl)\n end\n end\n\nend\n",
3219 "refs.lua": "local settings_key = KEYS[1]\nlocal job_weights_key = KEYS[2]\nlocal job_expirations_key = KEYS[3]\nlocal job_clients_key = KEYS[4]\nlocal client_running_key = KEYS[5]\nlocal client_num_queued_key = KEYS[6]\nlocal client_last_registered_key = KEYS[7]\nlocal client_last_seen_key = KEYS[8]\n\nlocal now = tonumber(ARGV[1])\nlocal client = ARGV[2]\n\nlocal num_static_argv = 2\n",
3220 "register.lua": "local index = ARGV[num_static_argv + 1]\nlocal weight = tonumber(ARGV[num_static_argv + 2])\nlocal expiration = tonumber(ARGV[num_static_argv + 3])\n\nlocal state = process_tick(now, false)\nlocal capacity = state['capacity']\nlocal reservoir = state['reservoir']\n\nlocal settings = redis.call('hmget', settings_key,\n 'nextRequest',\n 'minTime',\n 'groupTimeout'\n)\nlocal nextRequest = tonumber(settings[1])\nlocal minTime = tonumber(settings[2])\nlocal groupTimeout = tonumber(settings[3])\n\nif conditions_check(capacity, weight) then\n\n redis.call('hincrby', settings_key, 'running', weight)\n redis.call('hset', job_weights_key, index, weight)\n if expiration ~= nil then\n redis.call('zadd', job_expirations_key, now + expiration, index)\n end\n redis.call('hset', job_clients_key, index, client)\n redis.call('zincrby', client_running_key, weight, client)\n redis.call('hincrby', client_num_queued_key, client, -1)\n redis.call('zadd', client_last_registered_key, now, client)\n\n local wait = math.max(nextRequest - now, 0)\n local newNextRequest = now + wait + minTime\n\n if reservoir == nil then\n redis.call('hset', settings_key,\n 'nextRequest', newNextRequest\n )\n else\n reservoir = reservoir - weight\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'nextRequest', newNextRequest\n )\n end\n\n refresh_expiration(now, newNextRequest, groupTimeout)\n\n return {true, wait, reservoir}\n\nelse\n return {false}\nend\n",
3221 "register_client.lua": "local queued = tonumber(ARGV[num_static_argv + 1])\n\n-- Could have been re-registered concurrently\nif not redis.call('zscore', client_last_seen_key, client) then\n redis.call('zadd', client_running_key, 0, client)\n redis.call('hset', client_num_queued_key, client, queued)\n redis.call('zadd', client_last_registered_key, 0, client)\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n\nreturn {}\n",
3222 "running.lua": "return process_tick(now, false)['running']\n",
3223 "submit.lua": "local queueLength = tonumber(ARGV[num_static_argv + 1])\nlocal weight = tonumber(ARGV[num_static_argv + 2])\n\nlocal capacity = process_tick(now, false)['capacity']\n\nlocal settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'highWater',\n 'nextRequest',\n 'strategy',\n 'unblockTime',\n 'penalty',\n 'minTime',\n 'groupTimeout'\n)\nlocal id = settings[1]\nlocal maxConcurrent = tonumber(settings[2])\nlocal highWater = tonumber(settings[3])\nlocal nextRequest = tonumber(settings[4])\nlocal strategy = tonumber(settings[5])\nlocal unblockTime = tonumber(settings[6])\nlocal penalty = tonumber(settings[7])\nlocal minTime = tonumber(settings[8])\nlocal groupTimeout = tonumber(settings[9])\n\nif maxConcurrent ~= nil and weight > maxConcurrent then\n return redis.error_reply('OVERWEIGHT:'..weight..':'..maxConcurrent)\nend\n\nlocal reachedHWM = (highWater ~= nil and queueLength == highWater\n and not (\n conditions_check(capacity, weight)\n and nextRequest - now <= 0\n )\n)\n\nlocal blocked = strategy == 3 and (reachedHWM or unblockTime >= now)\n\nif blocked then\n local computedPenalty = penalty\n if computedPenalty == nil then\n if minTime == 0 then\n computedPenalty = 5000\n else\n computedPenalty = 15 * minTime\n end\n end\n\n local newNextRequest = now + computedPenalty + minTime\n\n redis.call('hmset', settings_key,\n 'unblockTime', now + computedPenalty,\n 'nextRequest', newNextRequest\n )\n\n local clients_queued_reset = redis.call('hkeys', client_num_queued_key)\n local queued_reset = {}\n for i = 1, #clients_queued_reset do\n table.insert(queued_reset, clients_queued_reset[i])\n table.insert(queued_reset, 0)\n end\n redis.call('hmset', client_num_queued_key, unpack(queued_reset))\n\n redis.call('publish', 'b_'..id, 'blocked:')\n\n refresh_expiration(now, newNextRequest, groupTimeout)\nend\n\nif not blocked and not reachedHWM then\n redis.call('hincrby', client_num_queued_key, client, 1)\nend\n\nreturn {reachedHWM, blocked, strategy}\n",
3224 "update_settings.lua": "local args = {'hmset', settings_key}\n\nfor i = num_static_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\nend\n\nredis.call(unpack(args))\n\nprocess_tick(now, true)\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n",
3225 "validate_client.lua": "if not redis.call('zscore', client_last_seen_key, client) then\n return redis.error_reply('UNKNOWN_CLIENT')\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n",
3226 "validate_keys.lua": "if not (redis.call('exists', settings_key) == 1) then\n return redis.error_reply('SETTINGS_KEY_NOT_FOUND')\nend\n"
3227 };
3228
3229 var Scripts$3 = createCommonjsModule(function (module, exports) {
3230
3231 var headers, lua, templates;
3232 lua = require$$0$1;
3233 headers = {
3234 refs: lua["refs.lua"],
3235 validate_keys: lua["validate_keys.lua"],
3236 validate_client: lua["validate_client.lua"],
3237 refresh_expiration: lua["refresh_expiration.lua"],
3238 process_tick: lua["process_tick.lua"],
3239 conditions_check: lua["conditions_check.lua"],
3240 get_time: lua["get_time.lua"]
3241 };
3242
3243 exports.allKeys = function (id) {
3244 return [
3245 /*
3246 HASH
3247 */
3248 `b_${id}_settings`,
3249 /*
3250 HASH
3251 job index -> weight
3252 */
3253 `b_${id}_job_weights`,
3254 /*
3255 ZSET
3256 job index -> expiration
3257 */
3258 `b_${id}_job_expirations`,
3259 /*
3260 HASH
3261 job index -> client
3262 */
3263 `b_${id}_job_clients`,
3264 /*
3265 ZSET
3266 client -> sum running
3267 */
3268 `b_${id}_client_running`,
3269 /*
3270 HASH
3271 client -> num queued
3272 */
3273 `b_${id}_client_num_queued`,
3274 /*
3275 ZSET
3276 client -> last job registered
3277 */
3278 `b_${id}_client_last_registered`,
3279 /*
3280 ZSET
3281 client -> last seen
3282 */
3283 `b_${id}_client_last_seen`];
3284 };
3285
3286 templates = {
3287 init: {
3288 keys: exports.allKeys,
3289 headers: ["process_tick"],
3290 refresh_expiration: true,
3291 code: lua["init.lua"]
3292 },
3293 group_check: {
3294 keys: exports.allKeys,
3295 headers: [],
3296 refresh_expiration: false,
3297 code: lua["group_check.lua"]
3298 },
3299 register_client: {
3300 keys: exports.allKeys,
3301 headers: ["validate_keys"],
3302 refresh_expiration: false,
3303 code: lua["register_client.lua"]
3304 },
3305 blacklist_client: {
3306 keys: exports.allKeys,
3307 headers: ["validate_keys", "validate_client"],
3308 refresh_expiration: false,
3309 code: lua["blacklist_client.lua"]
3310 },
3311 heartbeat: {
3312 keys: exports.allKeys,
3313 headers: ["validate_keys", "validate_client", "process_tick"],
3314 refresh_expiration: false,
3315 code: lua["heartbeat.lua"]
3316 },
3317 update_settings: {
3318 keys: exports.allKeys,
3319 headers: ["validate_keys", "validate_client", "process_tick"],
3320 refresh_expiration: true,
3321 code: lua["update_settings.lua"]
3322 },
3323 running: {
3324 keys: exports.allKeys,
3325 headers: ["validate_keys", "validate_client", "process_tick"],
3326 refresh_expiration: false,
3327 code: lua["running.lua"]
3328 },
3329 queued: {
3330 keys: exports.allKeys,
3331 headers: ["validate_keys", "validate_client"],
3332 refresh_expiration: false,
3333 code: lua["queued.lua"]
3334 },
3335 done: {
3336 keys: exports.allKeys,
3337 headers: ["validate_keys", "validate_client", "process_tick"],
3338 refresh_expiration: false,
3339 code: lua["done.lua"]
3340 },
3341 check: {
3342 keys: exports.allKeys,
3343 headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"],
3344 refresh_expiration: false,
3345 code: lua["check.lua"]
3346 },
3347 submit: {
3348 keys: exports.allKeys,
3349 headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"],
3350 refresh_expiration: true,
3351 code: lua["submit.lua"]
3352 },
3353 register: {
3354 keys: exports.allKeys,
3355 headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"],
3356 refresh_expiration: true,
3357 code: lua["register.lua"]
3358 },
3359 free: {
3360 keys: exports.allKeys,
3361 headers: ["validate_keys", "validate_client", "process_tick"],
3362 refresh_expiration: true,
3363 code: lua["free.lua"]
3364 },
3365 current_reservoir: {
3366 keys: exports.allKeys,
3367 headers: ["validate_keys", "validate_client", "process_tick"],
3368 refresh_expiration: false,
3369 code: lua["current_reservoir.lua"]
3370 },
3371 increment_reservoir: {
3372 keys: exports.allKeys,
3373 headers: ["validate_keys", "validate_client", "process_tick"],
3374 refresh_expiration: true,
3375 code: lua["increment_reservoir.lua"]
3376 }
3377 };
3378 exports.names = Object.keys(templates);
3379
3380 exports.keys = function (name, id) {
3381 return templates[name].keys(id);
3382 };
3383
3384 exports.payload = function (name) {
3385 var template;
3386 template = templates[name];
3387 return Array.prototype.concat(headers.refs, template.headers.map(function (h) {
3388 return headers[h];
3389 }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join("\n");
3390 };
3391 });
3392
3393 function asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
3394
3395 function _asyncToGenerator$5(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
3396
3397 var Events$4, RedisConnection$2, Scripts$2, parser$5;
3398 parser$5 = parser$8;
3399 Events$4 = Events_1;
3400 Scripts$2 = Scripts$3;
3401
3402 RedisConnection$2 = function () {
3403 class RedisConnection {
3404 constructor(options = {}) {
3405 parser$5.load(options, this.defaults, this);
3406
3407 if (this.Redis == null) {
3408 this.Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module. To override this behavior: pass the redis module to Bottleneck as the 'Redis' option.
3409 }
3410
3411 if (this.Events == null) {
3412 this.Events = new Events$4(this);
3413 }
3414
3415 this.terminated = false;
3416
3417 if (this.client == null) {
3418 this.client = this.Redis.createClient(this.clientOptions);
3419 }
3420
3421 this.subscriber = this.client.duplicate();
3422 this.limiters = {};
3423 this.shas = {};
3424 this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => {
3425 return this._loadScripts();
3426 }).then(() => {
3427 return {
3428 client: this.client,
3429 subscriber: this.subscriber
3430 };
3431 });
3432 }
3433
3434 _setup(client, sub) {
3435 client.setMaxListeners(0);
3436 return new this.Promise((resolve, reject) => {
3437 client.on("error", e => {
3438 return this.Events.trigger("error", e);
3439 });
3440
3441 if (sub) {
3442 client.on("message", (channel, message) => {
3443 var ref;
3444 return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
3445 });
3446 }
3447
3448 if (client.ready) {
3449 return resolve();
3450 } else {
3451 return client.once("ready", resolve);
3452 }
3453 });
3454 }
3455
3456 _loadScript(name) {
3457 return new this.Promise((resolve, reject) => {
3458 var payload;
3459 payload = Scripts$2.payload(name);
3460 return this.client.multi([["script", "load", payload]]).exec((err, replies) => {
3461 if (err != null) {
3462 return reject(err);
3463 }
3464
3465 this.shas[name] = replies[0];
3466 return resolve(replies[0]);
3467 });
3468 });
3469 }
3470
3471 _loadScripts() {
3472 return this.Promise.all(Scripts$2.names.map(k => {
3473 return this._loadScript(k);
3474 }));
3475 }
3476
3477 __runCommand__(cmd) {
3478 var _this = this;
3479
3480 return _asyncToGenerator$5(function* () {
3481 yield _this.ready;
3482 return new _this.Promise((resolve, reject) => {
3483 return _this.client.multi([cmd]).exec_atomic(function (err, replies) {
3484 if (err != null) {
3485 return reject(err);
3486 } else {
3487 return resolve(replies[0]);
3488 }
3489 });
3490 });
3491 })();
3492 }
3493
3494 __addLimiter__(instance) {
3495 return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => {
3496 return new this.Promise((resolve, reject) => {
3497 var handler;
3498
3499 handler = chan => {
3500 if (chan === channel) {
3501 this.subscriber.removeListener("subscribe", handler);
3502 this.limiters[channel] = instance;
3503 return resolve();
3504 }
3505 };
3506
3507 this.subscriber.on("subscribe", handler);
3508 return this.subscriber.subscribe(channel);
3509 });
3510 }));
3511 }
3512
3513 __removeLimiter__(instance) {
3514 var _this2 = this;
3515
3516 return this.Promise.all([instance.channel(), instance.channel_client()].map(
3517 /*#__PURE__*/
3518 function () {
3519 var _ref = _asyncToGenerator$5(function* (channel) {
3520 if (!_this2.terminated) {
3521 yield new _this2.Promise((resolve, reject) => {
3522 return _this2.subscriber.unsubscribe(channel, function (err, chan) {
3523 if (err != null) {
3524 return reject(err);
3525 }
3526
3527 if (chan === channel) {
3528 return resolve();
3529 }
3530 });
3531 });
3532 }
3533
3534 return delete _this2.limiters[channel];
3535 });
3536
3537 return function (_x) {
3538 return _ref.apply(this, arguments);
3539 };
3540 }()));
3541 }
3542
3543 __scriptArgs__(name, id, args, cb) {
3544 var keys;
3545 keys = Scripts$2.keys(name, id);
3546 return [this.shas[name], keys.length].concat(keys, args, cb);
3547 }
3548
3549 __scriptFn__(name) {
3550 return this.client.evalsha.bind(this.client);
3551 }
3552
3553 disconnect(flush = true) {
3554 var i, k, len, ref;
3555 ref = Object.keys(this.limiters);
3556
3557 for (i = 0, len = ref.length; i < len; i++) {
3558 k = ref[i];
3559 clearInterval(this.limiters[k]._store.heartbeat);
3560 }
3561
3562 this.limiters = {};
3563 this.terminated = true;
3564 this.client.end(flush);
3565 this.subscriber.end(flush);
3566 return this.Promise.resolve();
3567 }
3568
3569 }
3570 RedisConnection.prototype.datastore = "redis";
3571 RedisConnection.prototype.defaults = {
3572 Redis: null,
3573 clientOptions: {},
3574 client: null,
3575 Promise: Promise,
3576 Events: null
3577 };
3578 return RedisConnection;
3579 }.call(void 0);
3580
3581 var RedisConnection_1 = RedisConnection$2;
3582
3583 function _slicedToArray$3(arr, i) { return _arrayWithHoles$3(arr) || _iterableToArrayLimit$3(arr, i) || _nonIterableRest$3(); }
3584
3585 function _nonIterableRest$3() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
3586
3587 function _iterableToArrayLimit$3(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
3588
3589 function _arrayWithHoles$3(arr) { if (Array.isArray(arr)) return arr; }
3590
3591 function asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
3592
3593 function _asyncToGenerator$4(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
3594
3595 var Events$3, IORedisConnection$2, Scripts$1, parser$4;
3596 parser$4 = parser$8;
3597 Events$3 = Events_1;
3598 Scripts$1 = Scripts$3;
3599
3600 IORedisConnection$2 = function () {
3601 class IORedisConnection {
3602 constructor(options = {}) {
3603 parser$4.load(options, this.defaults, this);
3604
3605 if (this.Redis == null) {
3606 this.Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module. To override this behavior: pass the ioredis module to Bottleneck as the 'Redis' option.
3607 }
3608
3609 if (this.Events == null) {
3610 this.Events = new Events$3(this);
3611 }
3612
3613 this.terminated = false;
3614
3615 if (this.clusterNodes != null) {
3616 this.client = new this.Redis.Cluster(this.clusterNodes, this.clientOptions);
3617 this.subscriber = new this.Redis.Cluster(this.clusterNodes, this.clientOptions);
3618 } else if (this.client != null && this.client.duplicate == null) {
3619 this.subscriber = new this.Redis.Cluster(this.client.startupNodes, this.client.options);
3620 } else {
3621 if (this.client == null) {
3622 this.client = new this.Redis(this.clientOptions);
3623 }
3624
3625 this.subscriber = this.client.duplicate();
3626 }
3627
3628 this.limiters = {};
3629 this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => {
3630 this._loadScripts();
3631
3632 return {
3633 client: this.client,
3634 subscriber: this.subscriber
3635 };
3636 });
3637 }
3638
3639 _setup(client, sub) {
3640 client.setMaxListeners(0);
3641 return new this.Promise((resolve, reject) => {
3642 client.on("error", e => {
3643 return this.Events.trigger("error", e);
3644 });
3645
3646 if (sub) {
3647 client.on("message", (channel, message) => {
3648 var ref;
3649 return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
3650 });
3651 }
3652
3653 if (client.status === "ready") {
3654 return resolve();
3655 } else {
3656 return client.once("ready", resolve);
3657 }
3658 });
3659 }
3660
3661 _loadScripts() {
3662 return Scripts$1.names.forEach(name => {
3663 return this.client.defineCommand(name, {
3664 lua: Scripts$1.payload(name)
3665 });
3666 });
3667 }
3668
3669 __runCommand__(cmd) {
3670 var _this = this;
3671
3672 return _asyncToGenerator$4(function* () {
3673 var deleted;
3674
3675 yield _this.ready;
3676
3677 var _ref = yield _this.client.pipeline([cmd]).exec();
3678
3679 var _ref2 = _slicedToArray$3(_ref, 1);
3680
3681 var _ref2$ = _slicedToArray$3(_ref2[0], 2);
3682 deleted = _ref2$[1];
3683 return deleted;
3684 })();
3685 }
3686
3687 __addLimiter__(instance) {
3688 return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => {
3689 return new this.Promise((resolve, reject) => {
3690 return this.subscriber.subscribe(channel, () => {
3691 this.limiters[channel] = instance;
3692 return resolve();
3693 });
3694 });
3695 }));
3696 }
3697
3698 __removeLimiter__(instance) {
3699 var _this2 = this;
3700
3701 return [instance.channel(), instance.channel_client()].forEach(
3702 /*#__PURE__*/
3703 function () {
3704 var _ref3 = _asyncToGenerator$4(function* (channel) {
3705 if (!_this2.terminated) {
3706 yield _this2.subscriber.unsubscribe(channel);
3707 }
3708
3709 return delete _this2.limiters[channel];
3710 });
3711
3712 return function (_x) {
3713 return _ref3.apply(this, arguments);
3714 };
3715 }());
3716 }
3717
3718 __scriptArgs__(name, id, args, cb) {
3719 var keys;
3720 keys = Scripts$1.keys(name, id);
3721 return [keys.length].concat(keys, args, cb);
3722 }
3723
3724 __scriptFn__(name) {
3725 return this.client[name].bind(this.client);
3726 }
3727
3728 disconnect(flush = true) {
3729 var i, k, len, ref;
3730 ref = Object.keys(this.limiters);
3731
3732 for (i = 0, len = ref.length; i < len; i++) {
3733 k = ref[i];
3734 clearInterval(this.limiters[k]._store.heartbeat);
3735 }
3736
3737 this.limiters = {};
3738 this.terminated = true;
3739
3740 if (flush) {
3741 return this.Promise.all([this.client.quit(), this.subscriber.quit()]);
3742 } else {
3743 this.client.disconnect();
3744 this.subscriber.disconnect();
3745 return this.Promise.resolve();
3746 }
3747 }
3748
3749 }
3750 IORedisConnection.prototype.datastore = "ioredis";
3751 IORedisConnection.prototype.defaults = {
3752 Redis: null,
3753 clientOptions: {},
3754 clusterNodes: null,
3755 client: null,
3756 Promise: Promise,
3757 Events: null
3758 };
3759 return IORedisConnection;
3760 }.call(void 0);
3761
3762 var IORedisConnection_1 = IORedisConnection$2;
3763
3764 function _slicedToArray$2(arr, i) { return _arrayWithHoles$2(arr) || _iterableToArrayLimit$2(arr, i) || _nonIterableRest$2(); }
3765
3766 function _nonIterableRest$2() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
3767
3768 function _iterableToArrayLimit$2(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
3769
3770 function _arrayWithHoles$2(arr) { if (Array.isArray(arr)) return arr; }
3771
3772 function asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
3773
3774 function _asyncToGenerator$3(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
3775
3776 var BottleneckError$1, IORedisConnection$1, RedisConnection$1, RedisDatastore$1, parser$3;
3777 parser$3 = parser$8;
3778 BottleneckError$1 = BottleneckError_1;
3779 RedisConnection$1 = RedisConnection_1;
3780 IORedisConnection$1 = IORedisConnection_1;
3781 RedisDatastore$1 = class RedisDatastore {
3782 constructor(instance, storeOptions, storeInstanceOptions) {
3783 this.instance = instance;
3784 this.storeOptions = storeOptions;
3785 this.originalId = this.instance.id;
3786 this.clientId = this.instance._randomIndex();
3787 parser$3.load(storeInstanceOptions, storeInstanceOptions, this);
3788 this.clients = {};
3789 this.capacityPriorityCounters = {};
3790 this.sharedConnection = this.connection != null;
3791
3792 if (this.connection == null) {
3793 this.connection = this.instance.datastore === "redis" ? new RedisConnection$1({
3794 Redis: this.Redis,
3795 clientOptions: this.clientOptions,
3796 Promise: this.Promise,
3797 Events: this.instance.Events
3798 }) : this.instance.datastore === "ioredis" ? new IORedisConnection$1({
3799 Redis: this.Redis,
3800 clientOptions: this.clientOptions,
3801 clusterNodes: this.clusterNodes,
3802 Promise: this.Promise,
3803 Events: this.instance.Events
3804 }) : void 0;
3805 }
3806
3807 this.instance.connection = this.connection;
3808 this.instance.datastore = this.connection.datastore;
3809 this.ready = this.connection.ready.then(clients => {
3810 this.clients = clients;
3811 return this.runScript("init", this.prepareInitSettings(this.clearDatastore));
3812 }).then(() => {
3813 return this.connection.__addLimiter__(this.instance);
3814 }).then(() => {
3815 return this.runScript("register_client", [this.instance.queued()]);
3816 }).then(() => {
3817 var base;
3818
3819 if (typeof (base = this.heartbeat = setInterval(() => {
3820 return this.runScript("heartbeat", []).catch(e => {
3821 return this.instance.Events.trigger("error", e);
3822 });
3823 }, this.heartbeatInterval)).unref === "function") {
3824 base.unref();
3825 }
3826
3827 return this.clients;
3828 });
3829 }
3830
3831 __publish__(message) {
3832 var _this = this;
3833
3834 return _asyncToGenerator$3(function* () {
3835 var client;
3836
3837 var _ref = yield _this.ready;
3838
3839 client = _ref.client;
3840 return client.publish(_this.instance.channel(), `message:${message.toString()}`);
3841 })();
3842 }
3843
3844 onMessage(channel, message) {
3845 var _this2 = this;
3846
3847 return _asyncToGenerator$3(function* () {
3848 var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type;
3849
3850 try {
3851 pos = message.indexOf(":");
3852 var _ref2 = [message.slice(0, pos), message.slice(pos + 1)];
3853 type = _ref2[0];
3854 data = _ref2[1];
3855
3856 if (type === "capacity") {
3857 return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0);
3858 } else if (type === "capacity-priority") {
3859 var _data$split = data.split(":");
3860
3861 var _data$split2 = _slicedToArray$2(_data$split, 3);
3862
3863 rawCapacity = _data$split2[0];
3864 priorityClient = _data$split2[1];
3865 counter = _data$split2[2];
3866 capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0;
3867
3868 if (priorityClient === _this2.clientId) {
3869 drained = yield _this2.instance._drainAll(capacity);
3870 newCapacity = capacity != null ? capacity - (drained || 0) : "";
3871 return yield _this2.clients.client.publish(_this2.instance.channel(), `capacity-priority:${newCapacity}::${counter}`);
3872 } else if (priorityClient === "") {
3873 clearTimeout(_this2.capacityPriorityCounters[counter]);
3874 delete _this2.capacityPriorityCounters[counter];
3875 return _this2.instance._drainAll(capacity);
3876 } else {
3877 return _this2.capacityPriorityCounters[counter] = setTimeout(
3878 /*#__PURE__*/
3879 _asyncToGenerator$3(function* () {
3880 var e;
3881
3882 try {
3883 delete _this2.capacityPriorityCounters[counter];
3884 yield _this2.runScript("blacklist_client", [priorityClient]);
3885 return yield _this2.instance._drainAll(capacity);
3886 } catch (error) {
3887 e = error;
3888 return _this2.instance.Events.trigger("error", e);
3889 }
3890 }), 1000);
3891 }
3892 } else if (type === "message") {
3893 return _this2.instance.Events.trigger("message", data);
3894 } else if (type === "blocked") {
3895 return yield _this2.instance._dropAllQueued();
3896 }
3897 } catch (error) {
3898 e = error;
3899 return _this2.instance.Events.trigger("error", e);
3900 }
3901 })();
3902 }
3903
3904 __disconnect__(flush) {
3905 clearInterval(this.heartbeat);
3906
3907 if (this.sharedConnection) {
3908 return this.connection.__removeLimiter__(this.instance);
3909 } else {
3910 return this.connection.disconnect(flush);
3911 }
3912 }
3913
3914 runScript(name, args) {
3915 var _this3 = this;
3916
3917 return _asyncToGenerator$3(function* () {
3918 if (!(name === "init" || name === "register_client")) {
3919 yield _this3.ready;
3920 }
3921
3922 return new _this3.Promise((resolve, reject) => {
3923 var all_args, arr;
3924 all_args = [Date.now(), _this3.clientId].concat(args);
3925
3926 _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args);
3927
3928 arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) {
3929 if (err != null) {
3930 return reject(err);
3931 }
3932
3933 return resolve(replies);
3934 });
3935 return _this3.connection.__scriptFn__(name)(...arr);
3936 }).catch(e => {
3937 if (e.message === "SETTINGS_KEY_NOT_FOUND") {
3938 if (name === "heartbeat") {
3939 return _this3.Promise.resolve();
3940 } else {
3941 return _this3.runScript("init", _this3.prepareInitSettings(false)).then(() => {
3942 return _this3.runScript(name, args);
3943 });
3944 }
3945 } else if (e.message === "UNKNOWN_CLIENT") {
3946 return _this3.runScript("register_client", [_this3.instance.queued()]).then(() => {
3947 return _this3.runScript(name, args);
3948 });
3949 } else {
3950 return _this3.Promise.reject(e);
3951 }
3952 });
3953 })();
3954 }
3955
3956 prepareArray(arr) {
3957 var i, len, results, x;
3958 results = [];
3959
3960 for (i = 0, len = arr.length; i < len; i++) {
3961 x = arr[i];
3962 results.push(x != null ? x.toString() : "");
3963 }
3964
3965 return results;
3966 }
3967
3968 prepareObject(obj) {
3969 var arr, k, v;
3970 arr = [];
3971
3972 for (k in obj) {
3973 v = obj[k];
3974 arr.push(k, v != null ? v.toString() : "");
3975 }
3976
3977 return arr;
3978 }
3979
3980 prepareInitSettings(clear) {
3981 var args;
3982 args = this.prepareObject(Object.assign({}, this.storeOptions, {
3983 id: this.originalId,
3984 version: this.instance.version,
3985 groupTimeout: this.timeout,
3986 clientTimeout: this.clientTimeout
3987 }));
3988 args.unshift(clear ? 1 : 0, this.instance.version);
3989 return args;
3990 }
3991
3992 convertBool(b) {
3993 return !!b;
3994 }
3995
3996 __updateSettings__(options) {
3997 var _this4 = this;
3998
3999 return _asyncToGenerator$3(function* () {
4000 yield _this4.runScript("update_settings", _this4.prepareObject(options));
4001 return parser$3.overwrite(options, options, _this4.storeOptions);
4002 })();
4003 }
4004
4005 __running__() {
4006 return this.runScript("running", []);
4007 }
4008
4009 __queued__() {
4010 return this.runScript("queued", []);
4011 }
4012
4013 __done__() {
4014 return this.runScript("done", []);
4015 }
4016
4017 __groupCheck__() {
4018 var _this5 = this;
4019
4020 return _asyncToGenerator$3(function* () {
4021 return _this5.convertBool((yield _this5.runScript("group_check", [])));
4022 })();
4023 }
4024
4025 __incrementReservoir__(incr) {
4026 return this.runScript("increment_reservoir", [incr]);
4027 }
4028
4029 __currentReservoir__() {
4030 return this.runScript("current_reservoir", []);
4031 }
4032
4033 __check__(weight) {
4034 var _this6 = this;
4035
4036 return _asyncToGenerator$3(function* () {
4037 return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight]))));
4038 })();
4039 }
4040
4041 __register__(index, weight, expiration) {
4042 var _this7 = this;
4043
4044 return _asyncToGenerator$3(function* () {
4045 var reservoir, success, wait;
4046
4047 var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration]));
4048
4049 var _ref5 = _slicedToArray$2(_ref4, 3);
4050
4051 success = _ref5[0];
4052 wait = _ref5[1];
4053 reservoir = _ref5[2];
4054 return {
4055 success: _this7.convertBool(success),
4056 wait,
4057 reservoir
4058 };
4059 })();
4060 }
4061
4062 __submit__(queueLength, weight) {
4063 var _this8 = this;
4064
4065 return _asyncToGenerator$3(function* () {
4066 var blocked, e, maxConcurrent, reachedHWM, strategy;
4067
4068 try {
4069 var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight]));
4070
4071 var _ref7 = _slicedToArray$2(_ref6, 3);
4072
4073 reachedHWM = _ref7[0];
4074 blocked = _ref7[1];
4075 strategy = _ref7[2];
4076 return {
4077 reachedHWM: _this8.convertBool(reachedHWM),
4078 blocked: _this8.convertBool(blocked),
4079 strategy
4080 };
4081 } catch (error) {
4082 e = error;
4083
4084 if (e.message.indexOf("OVERWEIGHT") === 0) {
4085 var _e$message$split = e.message.split(":");
4086
4087 var _e$message$split2 = _slicedToArray$2(_e$message$split, 3);
4088 weight = _e$message$split2[1];
4089 maxConcurrent = _e$message$split2[2];
4090 throw new BottleneckError$1(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${maxConcurrent}`);
4091 } else {
4092 throw e;
4093 }
4094 }
4095 })();
4096 }
4097
4098 __free__(index, weight) {
4099 var _this9 = this;
4100
4101 return _asyncToGenerator$3(function* () {
4102 var running;
4103 running = yield _this9.runScript("free", _this9.prepareArray([index]));
4104 return {
4105 running
4106 };
4107 })();
4108 }
4109
4110 };
4111 var RedisDatastore_1 = RedisDatastore$1;
4112
4113 var BottleneckError, States$1;
4114 BottleneckError = BottleneckError_1;
4115 States$1 = class States {
4116 constructor(status1) {
4117 this.status = status1;
4118 this._jobs = {};
4119 this.counts = this.status.map(function () {
4120 return 0;
4121 });
4122 }
4123
4124 next(id) {
4125 var current, next;
4126 current = this._jobs[id];
4127 next = current + 1;
4128
4129 if (current != null && next < this.status.length) {
4130 this.counts[current]--;
4131 this.counts[next]++;
4132 return this._jobs[id]++;
4133 } else if (current != null) {
4134 this.counts[current]--;
4135 return delete this._jobs[id];
4136 }
4137 }
4138
4139 start(id) {
4140 var initial;
4141 initial = 0;
4142 this._jobs[id] = initial;
4143 return this.counts[initial]++;
4144 }
4145
4146 remove(id) {
4147 var current;
4148 current = this._jobs[id];
4149
4150 if (current != null) {
4151 this.counts[current]--;
4152 delete this._jobs[id];
4153 }
4154
4155 return current != null;
4156 }
4157
4158 jobStatus(id) {
4159 var ref;
4160 return (ref = this.status[this._jobs[id]]) != null ? ref : null;
4161 }
4162
4163 statusJobs(status) {
4164 var k, pos, ref, results, v;
4165
4166 if (status != null) {
4167 pos = this.status.indexOf(status);
4168
4169 if (pos < 0) {
4170 throw new BottleneckError(`status must be one of ${this.status.join(', ')}`);
4171 }
4172
4173 ref = this._jobs;
4174 results = [];
4175
4176 for (k in ref) {
4177 v = ref[k];
4178
4179 if (v === pos) {
4180 results.push(k);
4181 }
4182 }
4183
4184 return results;
4185 } else {
4186 return Object.keys(this._jobs);
4187 }
4188 }
4189
4190 statusCounts() {
4191 return this.counts.reduce((acc, v, i) => {
4192 acc[this.status[i]] = v;
4193 return acc;
4194 }, {});
4195 }
4196
4197 };
4198 var States_1 = States$1;
4199
4200 function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4201
4202 function _asyncToGenerator$2(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
4203
4204 var DLList, Sync$1;
4205 DLList = DLList_1;
4206 Sync$1 = class Sync {
4207 constructor(name, Promise) {
4208 this.schedule = this.schedule.bind(this);
4209 this.name = name;
4210 this.Promise = Promise;
4211 this._running = 0;
4212 this._queue = new DLList();
4213 }
4214
4215 isEmpty() {
4216 return this._queue.length === 0;
4217 }
4218
4219 _tryToRun() {
4220 var _this = this;
4221
4222 return _asyncToGenerator$2(function* () {
4223 var args, cb, error, reject, resolve, returned, task;
4224
4225 if (_this._running < 1 && _this._queue.length > 0) {
4226 _this._running++;
4227
4228 var _this$_queue$shift = _this._queue.shift();
4229
4230 task = _this$_queue$shift.task;
4231 args = _this$_queue$shift.args;
4232 resolve = _this$_queue$shift.resolve;
4233 reject = _this$_queue$shift.reject;
4234 cb = yield _asyncToGenerator$2(function* () {
4235 try {
4236 returned = yield task(...args);
4237 return function () {
4238 return resolve(returned);
4239 };
4240 } catch (error1) {
4241 error = error1;
4242 return function () {
4243 return reject(error);
4244 };
4245 }
4246 })();
4247 _this._running--;
4248
4249 _this._tryToRun();
4250
4251 return cb();
4252 }
4253 })();
4254 }
4255
4256 schedule(task, ...args) {
4257 var promise, reject, resolve;
4258 resolve = reject = null;
4259 promise = new this.Promise(function (_resolve, _reject) {
4260 resolve = _resolve;
4261 return reject = _reject;
4262 });
4263
4264 this._queue.push({
4265 task,
4266 args,
4267 resolve,
4268 reject
4269 });
4270
4271 this._tryToRun();
4272
4273 return promise;
4274 }
4275
4276 };
4277 var Sync_1 = Sync$1;
4278
4279 var version = "2.19.5";
4280 var require$$8 = {
4281 version: version
4282 };
4283
4284 var require$$0 = Bottleneck_1;
4285
4286 function _slicedToArray$1(arr, i) { return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _nonIterableRest$1(); }
4287
4288 function _nonIterableRest$1() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
4289
4290 function _iterableToArrayLimit$1(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
4291
4292 function _arrayWithHoles$1(arr) { if (Array.isArray(arr)) return arr; }
4293
4294 function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4295
4296 function _asyncToGenerator$1(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
4297
4298 var Events$2, Group, IORedisConnection, RedisConnection, Scripts, parser$2;
4299 parser$2 = parser$8;
4300 Events$2 = Events_1;
4301 RedisConnection = RedisConnection_1;
4302 IORedisConnection = IORedisConnection_1;
4303 Scripts = Scripts$3;
4304
4305 Group = function () {
4306 class Group {
4307 constructor(limiterOptions = {}) {
4308 this.deleteKey = this.deleteKey.bind(this);
4309 this.limiterOptions = limiterOptions;
4310 parser$2.load(this.limiterOptions, this.defaults, this);
4311 this.Events = new Events$2(this);
4312 this.instances = {};
4313 this.Bottleneck = require$$0;
4314
4315 this._startAutoCleanup();
4316
4317 this.sharedConnection = this.connection != null;
4318
4319 if (this.connection == null) {
4320 if (this.limiterOptions.datastore === "redis") {
4321 this.connection = new RedisConnection(Object.assign({}, this.limiterOptions, {
4322 Events: this.Events
4323 }));
4324 } else if (this.limiterOptions.datastore === "ioredis") {
4325 this.connection = new IORedisConnection(Object.assign({}, this.limiterOptions, {
4326 Events: this.Events
4327 }));
4328 }
4329 }
4330 }
4331
4332 key(key = "") {
4333 var ref;
4334 return (ref = this.instances[key]) != null ? ref : (() => {
4335 var limiter;
4336 limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, {
4337 id: `${this.id}-${key}`,
4338 timeout: this.timeout,
4339 connection: this.connection
4340 }));
4341 this.Events.trigger("created", limiter, key);
4342 return limiter;
4343 })();
4344 }
4345
4346 deleteKey(key = "") {
4347 var _this = this;
4348
4349 return _asyncToGenerator$1(function* () {
4350 var deleted, instance;
4351 instance = _this.instances[key];
4352
4353 if (_this.connection) {
4354 deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]);
4355 }
4356
4357 if (instance != null) {
4358 delete _this.instances[key];
4359 yield instance.disconnect();
4360 }
4361
4362 return instance != null || deleted > 0;
4363 })();
4364 }
4365
4366 limiters() {
4367 var k, ref, results, v;
4368 ref = this.instances;
4369 results = [];
4370
4371 for (k in ref) {
4372 v = ref[k];
4373 results.push({
4374 key: k,
4375 limiter: v
4376 });
4377 }
4378
4379 return results;
4380 }
4381
4382 keys() {
4383 return Object.keys(this.instances);
4384 }
4385
4386 clusterKeys() {
4387 var _this2 = this;
4388
4389 return _asyncToGenerator$1(function* () {
4390 var cursor, end, found, i, k, keys, len, next, start;
4391
4392 if (_this2.connection == null) {
4393 return _this2.Promise.resolve(_this2.keys());
4394 }
4395
4396 keys = [];
4397 cursor = null;
4398 start = `b_${_this2.id}-`.length;
4399 end = "_settings".length;
4400
4401 while (cursor !== 0) {
4402 var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]);
4403
4404 var _ref2 = _slicedToArray$1(_ref, 2);
4405
4406 next = _ref2[0];
4407 found = _ref2[1];
4408 cursor = ~~next;
4409
4410 for (i = 0, len = found.length; i < len; i++) {
4411 k = found[i];
4412 keys.push(k.slice(start, -end));
4413 }
4414 }
4415
4416 return keys;
4417 })();
4418 }
4419
4420 _startAutoCleanup() {
4421 var _this3 = this;
4422
4423 var base;
4424 clearInterval(this.interval);
4425 return typeof (base = this.interval = setInterval(
4426 /*#__PURE__*/
4427 _asyncToGenerator$1(function* () {
4428 var e, k, ref, results, time, v;
4429 time = Date.now();
4430 ref = _this3.instances;
4431 results = [];
4432
4433 for (k in ref) {
4434 v = ref[k];
4435
4436 try {
4437 if (yield v._store.__groupCheck__(time)) {
4438 results.push(_this3.deleteKey(k));
4439 } else {
4440 results.push(void 0);
4441 }
4442 } catch (error) {
4443 e = error;
4444 results.push(v.Events.trigger("error", e));
4445 }
4446 }
4447
4448 return results;
4449 }), this.timeout / 2)).unref === "function" ? base.unref() : void 0;
4450 }
4451
4452 updateSettings(options = {}) {
4453 parser$2.overwrite(options, this.defaults, this);
4454 parser$2.overwrite(options, options, this.limiterOptions);
4455
4456 if (options.timeout != null) {
4457 return this._startAutoCleanup();
4458 }
4459 }
4460
4461 disconnect(flush = true) {
4462 var ref;
4463
4464 if (!this.sharedConnection) {
4465 return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;
4466 }
4467 }
4468
4469 }
4470 Group.prototype.defaults = {
4471 timeout: 1000 * 60 * 5,
4472 connection: null,
4473 Promise: Promise,
4474 id: "group-key"
4475 };
4476 return Group;
4477 }.call(void 0);
4478
4479 var Group_1 = Group;
4480
4481 var Batcher, Events$1, parser$1;
4482 parser$1 = parser$8;
4483 Events$1 = Events_1;
4484
4485 Batcher = function () {
4486 class Batcher {
4487 constructor(options = {}) {
4488 this.options = options;
4489 parser$1.load(this.options, this.defaults, this);
4490 this.Events = new Events$1(this);
4491 this._arr = [];
4492
4493 this._resetPromise();
4494
4495 this._lastFlush = Date.now();
4496 }
4497
4498 _resetPromise() {
4499 return this._promise = new this.Promise((res, rej) => {
4500 return this._resolve = res;
4501 });
4502 }
4503
4504 _flush() {
4505 clearTimeout(this._timeout);
4506 this._lastFlush = Date.now();
4507
4508 this._resolve();
4509
4510 this.Events.trigger("batch", this._arr);
4511 this._arr = [];
4512 return this._resetPromise();
4513 }
4514
4515 add(data) {
4516 var ret;
4517
4518 this._arr.push(data);
4519
4520 ret = this._promise;
4521
4522 if (this._arr.length === this.maxSize) {
4523 this._flush();
4524 } else if (this.maxTime != null && this._arr.length === 1) {
4525 this._timeout = setTimeout(() => {
4526 return this._flush();
4527 }, this.maxTime);
4528 }
4529
4530 return ret;
4531 }
4532
4533 }
4534 Batcher.prototype.defaults = {
4535 maxTime: null,
4536 maxSize: null,
4537 Promise: Promise
4538 };
4539 return Batcher;
4540 }.call(void 0);
4541
4542 var Batcher_1 = Batcher;
4543
4544 function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
4545
4546 function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
4547
4548 function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); }
4549
4550 function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
4551
4552 function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
4553
4554 function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
4555
4556 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4557
4558 function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
4559
4560 var Bottleneck,
4561 DEFAULT_PRIORITY,
4562 Events,
4563 Job,
4564 LocalDatastore,
4565 NUM_PRIORITIES,
4566 Queues,
4567 RedisDatastore,
4568 States,
4569 Sync,
4570 parser,
4571 splice = [].splice;
4572 NUM_PRIORITIES = 10;
4573 DEFAULT_PRIORITY = 5;
4574 parser = parser$8;
4575 Queues = Queues_1;
4576 Job = Job_1;
4577 LocalDatastore = LocalDatastore_1;
4578 RedisDatastore = RedisDatastore_1;
4579 Events = Events_1;
4580 States = States_1;
4581 Sync = Sync_1;
4582
4583 Bottleneck = function () {
4584 class Bottleneck {
4585 constructor(options = {}, ...invalid) {
4586 var storeInstanceOptions, storeOptions;
4587 this._addToQueue = this._addToQueue.bind(this);
4588
4589 this._validateOptions(options, invalid);
4590
4591 parser.load(options, this.instanceDefaults, this);
4592 this._queues = new Queues(NUM_PRIORITIES);
4593 this._scheduled = {};
4594 this._states = new States(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : []));
4595 this._limiter = null;
4596 this.Events = new Events(this);
4597 this._submitLock = new Sync("submit", this.Promise);
4598 this._registerLock = new Sync("register", this.Promise);
4599 storeOptions = parser.load(options, this.storeDefaults, {});
4600
4601 this._store = function () {
4602 if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) {
4603 storeInstanceOptions = parser.load(options, this.redisStoreDefaults, {});
4604 return new RedisDatastore(this, storeOptions, storeInstanceOptions);
4605 } else if (this.datastore === "local") {
4606 storeInstanceOptions = parser.load(options, this.localStoreDefaults, {});
4607 return new LocalDatastore(this, storeOptions, storeInstanceOptions);
4608 } else {
4609 throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`);
4610 }
4611 }.call(this);
4612
4613 this._queues.on("leftzero", () => {
4614 var ref;
4615 return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0;
4616 });
4617
4618 this._queues.on("zero", () => {
4619 var ref;
4620 return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0;
4621 });
4622 }
4623
4624 _validateOptions(options, invalid) {
4625 if (!(options != null && typeof options === "object" && invalid.length === 0)) {
4626 throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.");
4627 }
4628 }
4629
4630 ready() {
4631 return this._store.ready;
4632 }
4633
4634 clients() {
4635 return this._store.clients;
4636 }
4637
4638 channel() {
4639 return `b_${this.id}`;
4640 }
4641
4642 channel_client() {
4643 return `b_${this.id}_${this._store.clientId}`;
4644 }
4645
4646 publish(message) {
4647 return this._store.__publish__(message);
4648 }
4649
4650 disconnect(flush = true) {
4651 return this._store.__disconnect__(flush);
4652 }
4653
4654 chain(_limiter) {
4655 this._limiter = _limiter;
4656 return this;
4657 }
4658
4659 queued(priority) {
4660 return this._queues.queued(priority);
4661 }
4662
4663 clusterQueued() {
4664 return this._store.__queued__();
4665 }
4666
4667 empty() {
4668 return this.queued() === 0 && this._submitLock.isEmpty();
4669 }
4670
4671 running() {
4672 return this._store.__running__();
4673 }
4674
4675 done() {
4676 return this._store.__done__();
4677 }
4678
4679 jobStatus(id) {
4680 return this._states.jobStatus(id);
4681 }
4682
4683 jobs(status) {
4684 return this._states.statusJobs(status);
4685 }
4686
4687 counts() {
4688 return this._states.statusCounts();
4689 }
4690
4691 _randomIndex() {
4692 return Math.random().toString(36).slice(2);
4693 }
4694
4695 check(weight = 1) {
4696 return this._store.__check__(weight);
4697 }
4698
4699 _clearGlobalState(index) {
4700 if (this._scheduled[index] != null) {
4701 clearTimeout(this._scheduled[index].expiration);
4702 delete this._scheduled[index];
4703 return true;
4704 } else {
4705 return false;
4706 }
4707 }
4708
4709 _free(index, job, options, eventInfo) {
4710 var _this = this;
4711
4712 return _asyncToGenerator(function* () {
4713 var e, running;
4714
4715 try {
4716 var _ref = yield _this._store.__free__(index, options.weight);
4717
4718 running = _ref.running;
4719
4720 _this.Events.trigger("debug", `Freed ${options.id}`, eventInfo);
4721
4722 if (running === 0 && _this.empty()) {
4723 return _this.Events.trigger("idle");
4724 }
4725 } catch (error1) {
4726 e = error1;
4727 return _this.Events.trigger("error", e);
4728 }
4729 })();
4730 }
4731
4732 _run(index, job, wait) {
4733 var clearGlobalState, free, run;
4734 job.doRun();
4735 clearGlobalState = this._clearGlobalState.bind(this, index);
4736 run = this._run.bind(this, index, job);
4737 free = this._free.bind(this, index, job);
4738 return this._scheduled[index] = {
4739 timeout: setTimeout(() => {
4740 return job.doExecute(this._limiter, clearGlobalState, run, free);
4741 }, wait),
4742 expiration: job.options.expiration != null ? setTimeout(function () {
4743 return job.doExpire(clearGlobalState, run, free);
4744 }, wait + job.options.expiration) : void 0,
4745 job: job
4746 };
4747 }
4748
4749 _drainOne(capacity) {
4750 return this._registerLock.schedule(() => {
4751 var args, index, next, options, queue;
4752
4753 if (this.queued() === 0) {
4754 return this.Promise.resolve(null);
4755 }
4756
4757 queue = this._queues.getFirst();
4758
4759 var _next2 = next = queue.first();
4760
4761 options = _next2.options;
4762 args = _next2.args;
4763
4764 if (capacity != null && options.weight > capacity) {
4765 return this.Promise.resolve(null);
4766 }
4767
4768 this.Events.trigger("debug", `Draining ${options.id}`, {
4769 args,
4770 options
4771 });
4772 index = this._randomIndex();
4773 return this._store.__register__(index, options.weight, options.expiration).then(({
4774 success,
4775 wait,
4776 reservoir
4777 }) => {
4778 var empty;
4779 this.Events.trigger("debug", `Drained ${options.id}`, {
4780 success,
4781 args,
4782 options
4783 });
4784
4785 if (success) {
4786 queue.shift();
4787 empty = this.empty();
4788
4789 if (empty) {
4790 this.Events.trigger("empty");
4791 }
4792
4793 if (reservoir === 0) {
4794 this.Events.trigger("depleted", empty);
4795 }
4796
4797 this._run(index, next, wait);
4798
4799 return this.Promise.resolve(options.weight);
4800 } else {
4801 return this.Promise.resolve(null);
4802 }
4803 });
4804 });
4805 }
4806
4807 _drainAll(capacity, total = 0) {
4808 return this._drainOne(capacity).then(drained => {
4809 var newCapacity;
4810
4811 if (drained != null) {
4812 newCapacity = capacity != null ? capacity - drained : capacity;
4813 return this._drainAll(newCapacity, total + drained);
4814 } else {
4815 return this.Promise.resolve(total);
4816 }
4817 }).catch(e => {
4818 return this.Events.trigger("error", e);
4819 });
4820 }
4821
4822 _dropAllQueued(message) {
4823 return this._queues.shiftAll(function (job) {
4824 return job.doDrop({
4825 message
4826 });
4827 });
4828 }
4829
4830 stop(options = {}) {
4831 var done, waitForExecuting;
4832 options = parser.load(options, this.stopDefaults);
4833
4834 waitForExecuting = at => {
4835 var finished;
4836
4837 finished = () => {
4838 var counts;
4839 counts = this._states.counts;
4840 return counts[0] + counts[1] + counts[2] + counts[3] === at;
4841 };
4842
4843 return new this.Promise((resolve, reject) => {
4844 if (finished()) {
4845 return resolve();
4846 } else {
4847 return this.on("done", () => {
4848 if (finished()) {
4849 this.removeAllListeners("done");
4850 return resolve();
4851 }
4852 });
4853 }
4854 });
4855 };
4856
4857 done = options.dropWaitingJobs ? (this._run = function (index, next) {
4858 return next.doDrop({
4859 message: options.dropErrorMessage
4860 });
4861 }, this._drainOne = () => {
4862 return this.Promise.resolve(null);
4863 }, this._registerLock.schedule(() => {
4864 return this._submitLock.schedule(() => {
4865 var k, ref, v;
4866 ref = this._scheduled;
4867
4868 for (k in ref) {
4869 v = ref[k];
4870
4871 if (this.jobStatus(v.job.options.id) === "RUNNING") {
4872 clearTimeout(v.timeout);
4873 clearTimeout(v.expiration);
4874 v.job.doDrop({
4875 message: options.dropErrorMessage
4876 });
4877 }
4878 }
4879
4880 this._dropAllQueued(options.dropErrorMessage);
4881
4882 return waitForExecuting(0);
4883 });
4884 })) : this.schedule({
4885 priority: NUM_PRIORITIES - 1,
4886 weight: 0
4887 }, () => {
4888 return waitForExecuting(1);
4889 });
4890
4891 this._receive = function (job) {
4892 return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage));
4893 };
4894
4895 this.stop = () => {
4896 return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called"));
4897 };
4898
4899 return done;
4900 }
4901
4902 _addToQueue(job) {
4903 var _this2 = this;
4904
4905 return _asyncToGenerator(function* () {
4906 var args, blocked, error, options, reachedHWM, shifted, strategy;
4907 args = job.args;
4908 options = job.options;
4909
4910 try {
4911 var _ref2 = yield _this2._store.__submit__(_this2.queued(), options.weight);
4912
4913 reachedHWM = _ref2.reachedHWM;
4914 blocked = _ref2.blocked;
4915 strategy = _ref2.strategy;
4916 } catch (error1) {
4917 error = error1;
4918
4919 _this2.Events.trigger("debug", `Could not queue ${options.id}`, {
4920 args,
4921 options,
4922 error
4923 });
4924
4925 job.doDrop({
4926 error
4927 });
4928 return false;
4929 }
4930
4931 if (blocked) {
4932 job.doDrop();
4933 return true;
4934 } else if (reachedHWM) {
4935 shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this2._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this2._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0;
4936
4937 if (shifted != null) {
4938 shifted.doDrop();
4939 }
4940
4941 if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) {
4942 if (shifted == null) {
4943 job.doDrop();
4944 }
4945
4946 return reachedHWM;
4947 }
4948 }
4949
4950 job.doQueue(reachedHWM, blocked);
4951
4952 _this2._queues.push(job);
4953
4954 yield _this2._drainAll();
4955 return reachedHWM;
4956 })();
4957 }
4958
4959 _receive(job) {
4960 if (this._states.jobStatus(job.options.id) != null) {
4961 job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`));
4962
4963 return false;
4964 } else {
4965 job.doReceive();
4966 return this._submitLock.schedule(this._addToQueue, job);
4967 }
4968 }
4969
4970 submit(...args) {
4971 var cb, fn, job, options, ref, ref1, task;
4972
4973 if (typeof args[0] === "function") {
4974 var _ref3, _ref4, _splice$call, _splice$call2;
4975
4976 ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), fn = _ref4[0], args = _ref4.slice(1), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call);
4977 options = parser.load({}, this.jobDefaults);
4978 } else {
4979 var _ref5, _ref6, _splice$call3, _splice$call4;
4980
4981 ref1 = args, (_ref5 = ref1, _ref6 = _toArray(_ref5), options = _ref6[0], fn = _ref6[1], args = _ref6.slice(2), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3);
4982 options = parser.load(options, this.jobDefaults);
4983 }
4984
4985 task = (...args) => {
4986 return new this.Promise(function (resolve, reject) {
4987 return fn(...args, function (...args) {
4988 return (args[0] != null ? reject : resolve)(args);
4989 });
4990 });
4991 };
4992
4993 job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);
4994 job.promise.then(function (args) {
4995 return typeof cb === "function" ? cb(...args) : void 0;
4996 }).catch(function (args) {
4997 if (Array.isArray(args)) {
4998 return typeof cb === "function" ? cb(...args) : void 0;
4999 } else {
5000 return typeof cb === "function" ? cb(args) : void 0;
5001 }
5002 });
5003 return this._receive(job);
5004 }
5005
5006 schedule(...args) {
5007 var job, options, task;
5008
5009 if (typeof args[0] === "function") {
5010 var _args = args;
5011
5012 var _args2 = _toArray(_args);
5013
5014 task = _args2[0];
5015 args = _args2.slice(1);
5016 options = {};
5017 } else {
5018 var _args3 = args;
5019
5020 var _args4 = _toArray(_args3);
5021
5022 options = _args4[0];
5023 task = _args4[1];
5024 args = _args4.slice(2);
5025 }
5026
5027 job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);
5028
5029 this._receive(job);
5030
5031 return job.promise;
5032 }
5033
5034 wrap(fn) {
5035 var schedule, wrapped;
5036 schedule = this.schedule.bind(this);
5037
5038 wrapped = function wrapped(...args) {
5039 return schedule(fn.bind(this), ...args);
5040 };
5041
5042 wrapped.withOptions = function (options, ...args) {
5043 return schedule(options, fn, ...args);
5044 };
5045
5046 return wrapped;
5047 }
5048
5049 updateSettings(options = {}) {
5050 var _this3 = this;
5051
5052 return _asyncToGenerator(function* () {
5053 yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults));
5054 parser.overwrite(options, _this3.instanceDefaults, _this3);
5055 return _this3;
5056 })();
5057 }
5058
5059 currentReservoir() {
5060 return this._store.__currentReservoir__();
5061 }
5062
5063 incrementReservoir(incr = 0) {
5064 return this._store.__incrementReservoir__(incr);
5065 }
5066
5067 }
5068 Bottleneck.default = Bottleneck;
5069 Bottleneck.Events = Events;
5070 Bottleneck.version = Bottleneck.prototype.version = require$$8.version;
5071 Bottleneck.strategy = Bottleneck.prototype.strategy = {
5072 LEAK: 1,
5073 OVERFLOW: 2,
5074 OVERFLOW_PRIORITY: 4,
5075 BLOCK: 3
5076 };
5077 Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1;
5078 Bottleneck.Group = Bottleneck.prototype.Group = Group_1;
5079 Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = RedisConnection_1;
5080 Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = IORedisConnection_1;
5081 Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1;
5082 Bottleneck.prototype.jobDefaults = {
5083 priority: DEFAULT_PRIORITY,
5084 weight: 1,
5085 expiration: null,
5086 id: "<no-id>"
5087 };
5088 Bottleneck.prototype.storeDefaults = {
5089 maxConcurrent: null,
5090 minTime: 0,
5091 highWater: null,
5092 strategy: Bottleneck.prototype.strategy.LEAK,
5093 penalty: null,
5094 reservoir: null,
5095 reservoirRefreshInterval: null,
5096 reservoirRefreshAmount: null,
5097 reservoirIncreaseInterval: null,
5098 reservoirIncreaseAmount: null,
5099 reservoirIncreaseMaximum: null
5100 };
5101 Bottleneck.prototype.localStoreDefaults = {
5102 Promise: Promise,
5103 timeout: null,
5104 heartbeatInterval: 250
5105 };
5106 Bottleneck.prototype.redisStoreDefaults = {
5107 Promise: Promise,
5108 timeout: null,
5109 heartbeatInterval: 5000,
5110 clientTimeout: 10000,
5111 Redis: null,
5112 clientOptions: {},
5113 clusterNodes: null,
5114 clearDatastore: false,
5115 connection: null
5116 };
5117 Bottleneck.prototype.instanceDefaults = {
5118 datastore: "local",
5119 connection: null,
5120 id: "<no-id>",
5121 rejectOnDrop: true,
5122 trackDoneStatus: false,
5123 Promise: Promise
5124 };
5125 Bottleneck.prototype.stopDefaults = {
5126 enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.",
5127 dropWaitingJobs: true,
5128 dropErrorMessage: "This limiter has been stopped."
5129 };
5130 return Bottleneck;
5131 }.call(void 0);
5132
5133 var Bottleneck_1 = Bottleneck;
5134
5135 var lib = require$$0;
5136
5137 const unifetch = typeof fetch !== 'undefined' ? fetch : browser$1;
5138 class AlpacaClient {
5139 params;
5140 baseURLs = endpoints;
5141 limiter = new lib({
5142 reservoir: 200,
5143 reservoirRefreshAmount: 200,
5144 reservoirRefreshInterval: 60 * 1000,
5145 maxConcurrent: 1,
5146 minTime: 200,
5147 });
5148 constructor(params) {
5149 this.params = params;
5150 if ('endpoints' in params) {
5151 this.baseURLs = Object.assign(endpoints, params.endpoints);
5152 }
5153 if (!('paper' in params.credentials) &&
5154 !('key' in params.credentials && params.credentials.key.startsWith('A'))) {
5155 params.credentials['paper'] = true;
5156 }
5157 if ('access_token' in params.credentials &&
5158 ('key' in params.credentials || 'secret' in params.credentials)) {
5159 throw new Error("can't create client with both default and oauth credentials");
5160 }
5161 }
5162 async isAuthenticated() {
5163 try {
5164 await this.getAccount();
5165 return true;
5166 }
5167 catch {
5168 return false;
5169 }
5170 }
5171 async getAccount() {
5172 return parse.account(await this.request({
5173 method: 'GET',
5174 url: `${this.baseURLs.rest.account}/account`,
5175 }));
5176 }
5177 async getOrder(params) {
5178 return parse.order(await this.request({
5179 method: 'GET',
5180 url: `${this.baseURLs.rest.account}/orders/${params.order_id || params.client_order_id}`,
5181 data: { nested: params.nested },
5182 }));
5183 }
5184 async getOrders(params = {}) {
5185 return parse.orders(await this.request({
5186 method: 'GET',
5187 url: `${this.baseURLs.rest.account}/orders`,
5188 data: {
5189 ...params,
5190 symbols: params.symbols ? params.symbols.join(',') : undefined,
5191 },
5192 }));
5193 }
5194 async placeOrder(params) {
5195 return parse.order(await this.request({
5196 method: 'POST',
5197 url: `${this.baseURLs.rest.account}/orders`,
5198 data: params,
5199 }));
5200 }
5201 async replaceOrder(params) {
5202 return parse.order(await this.request({
5203 method: 'PATCH',
5204 url: `${this.baseURLs.rest.account}/orders/${params.order_id}`,
5205 data: params,
5206 }));
5207 }
5208 cancelOrder(params) {
5209 return this.request({
5210 method: 'DELETE',
5211 url: `${this.baseURLs.rest.account}/orders/${params.order_id}`,
5212 isJSON: false,
5213 });
5214 }
5215 async cancelOrders() {
5216 return parse.canceled_orders(await this.request({
5217 method: 'DELETE',
5218 url: `${this.baseURLs.rest.account}/orders`,
5219 }));
5220 }
5221 async getPosition(params) {
5222 return parse.position(await this.request({
5223 method: 'GET',
5224 url: `${this.baseURLs.rest.account}/positions/${params.symbol}`,
5225 }));
5226 }
5227 async getPositions() {
5228 return parse.positions(await this.request({
5229 method: 'GET',
5230 url: `${this.baseURLs.rest.account}/positions`,
5231 }));
5232 }
5233 async closePosition(params) {
5234 return parse.order(await this.request({
5235 method: 'DELETE',
5236 url: `${this.baseURLs.rest.account}/positions/${params.symbol}`,
5237 data: params,
5238 }));
5239 }
5240 async closePositions(params) {
5241 return parse.orders(await this.request({
5242 method: 'DELETE',
5243 url: `${this.baseURLs.rest.account}/positions?cancel_orders=${JSON.stringify(params.cancel_orders ?? false)}`,
5244 }));
5245 }
5246 getAsset(params) {
5247 return this.request({
5248 method: 'GET',
5249 url: `${this.baseURLs.rest.account}/assets/${params.asset_id_or_symbol}`,
5250 });
5251 }
5252 getAssets(params) {
5253 return this.request({
5254 method: 'GET',
5255 url: `${this.baseURLs.rest.account}/assets`,
5256 data: params,
5257 });
5258 }
5259 getWatchlist(params) {
5260 return this.request({
5261 method: 'GET',
5262 url: `${this.baseURLs.rest.account}/watchlists/${params.uuid}`,
5263 });
5264 }
5265 getWatchlists() {
5266 return this.request({
5267 method: 'GET',
5268 url: `${this.baseURLs.rest.account}/watchlists`,
5269 });
5270 }
5271 createWatchlist(params) {
5272 return this.request({
5273 method: 'POST',
5274 url: `${this.baseURLs.rest.account}/watchlists`,
5275 data: params,
5276 });
5277 }
5278 updateWatchlist(params) {
5279 return this.request({
5280 method: 'PUT',
5281 url: `${this.baseURLs.rest.account}/watchlists/${params.uuid}`,
5282 data: params,
5283 });
5284 }
5285 addToWatchlist(params) {
5286 return this.request({
5287 method: 'POST',
5288 url: `${this.baseURLs.rest.account}/watchlists/${params.uuid}`,
5289 data: params,
5290 });
5291 }
5292 removeFromWatchlist(params) {
5293 return this.request({
5294 method: 'DELETE',
5295 url: `${this.baseURLs.rest.account}/watchlists/${params.uuid}/${params.symbol}`,
5296 });
5297 }
5298 deleteWatchlist(params) {
5299 return this.request({
5300 method: 'DELETE',
5301 url: `${this.baseURLs.rest.account}/watchlists/${params.uuid}`,
5302 });
5303 }
5304 getCalendar(params) {
5305 return this.request({
5306 method: 'GET',
5307 url: `${this.baseURLs.rest.account}/calendar`,
5308 data: params,
5309 });
5310 }
5311 getNews(params) {
5312 if ('symbols' in params && Array.isArray(params.symbols)) {
5313 params.symbols = params.symbols.join(',');
5314 }
5315 return this.request({
5316 method: 'GET',
5317 url: `${this.baseURLs.rest.beta}/news`,
5318 data: params,
5319 });
5320 }
5321 async getClock() {
5322 return parse.clock(await this.request({
5323 method: 'GET',
5324 url: `${this.baseURLs.rest.account}/clock`,
5325 }));
5326 }
5327 getAccountConfigurations() {
5328 return this.request({
5329 method: 'GET',
5330 url: `${this.baseURLs.rest.account}/account/configurations`,
5331 });
5332 }
5333 updateAccountConfigurations(params) {
5334 return this.request({
5335 method: 'PATCH',
5336 url: `${this.baseURLs.rest.account}/account/configurations`,
5337 data: params,
5338 });
5339 }
5340 async getAccountActivities(params) {
5341 if (params.activity_types && Array.isArray(params.activity_types)) {
5342 params.activity_types = params.activity_types.join(',');
5343 }
5344 return parse.activities(await this.request({
5345 method: 'GET',
5346 url: `${this.baseURLs.rest.account}/account/activities${params.activity_type ? '/'.concat(params.activity_type) : ''}`,
5347 data: { ...params, activity_type: undefined },
5348 }));
5349 }
5350 getPortfolioHistory(params) {
5351 return this.request({
5352 method: 'GET',
5353 url: `${this.baseURLs.rest.account}/account/portfolio/history`,
5354 data: params,
5355 });
5356 }
5357 async getBars_v1(params) {
5358 const transformed = {
5359 ...params,
5360 symbols: params.symbols.join(','),
5361 };
5362 return await this.request({
5363 method: 'GET',
5364 url: `${this.baseURLs.rest.market_data_v1}/bars/${params.timeframe}`,
5365 data: transformed,
5366 });
5367 }
5368 async getLastTrade_v1(params) {
5369 return await this.request({
5370 method: 'GET',
5371 url: `${this.baseURLs.rest.market_data_v1}/last/stocks/${params.symbol}`,
5372 });
5373 }
5374 async getLastQuote_v1(params) {
5375 return await this.request({
5376 method: 'GET',
5377 url: `${this.baseURLs.rest.market_data_v1}/last_quote/stocks/${params.symbol}`,
5378 });
5379 }
5380 async getTrades(params) {
5381 return parse.pageOfTrades(await this.request({
5382 method: 'GET',
5383 url: `${this.baseURLs.rest.market_data_v2}/stocks/${params.symbol}/trades`,
5384 data: { ...params, symbol: undefined },
5385 }));
5386 }
5387 async getQuotes(params) {
5388 return parse.pageOfQuotes(await this.request({
5389 method: 'GET',
5390 url: `${this.baseURLs.rest.market_data_v2}/stocks/${params.symbol}/quotes`,
5391 data: { ...params, symbol: undefined },
5392 }));
5393 }
5394 async getBars(params) {
5395 return parse.pageOfBars(await this.request({
5396 method: 'GET',
5397 url: `${this.baseURLs.rest.market_data_v2}/stocks/${params.symbol}/bars`,
5398 data: { ...params, symbol: undefined },
5399 }));
5400 }
5401 async getLatestTrade({ symbol, feed, limit, }) {
5402 let query = '';
5403 if (feed || limit) {
5404 query = '?'.concat(lib$1.stringify({ feed, limit }));
5405 }
5406 return parse.latestTrade(await this.request({
5407 method: 'GET',
5408 url: `${this.baseURLs.rest.market_data_v2}/stocks/${symbol}/trades/latest`.concat(query),
5409 }));
5410 }
5411 async getSnapshot(params) {
5412 return parse.snapshot(await this.request({
5413 method: 'GET',
5414 url: `${this.baseURLs.rest.market_data_v2}/stocks/${params.symbol}/snapshot`,
5415 }));
5416 }
5417 async getSnapshots(params) {
5418 return parse.snapshots(await this.request({
5419 method: 'GET',
5420 url: `${this.baseURLs.rest.market_data_v2}/stocks/snapshots?symbols=${params.symbols.join(',')}`,
5421 }));
5422 }
5423 async request(params) {
5424 let headers = {};
5425 if ('access_token' in this.params.credentials) {
5426 headers['Authorization'] = `Bearer ${this.params.credentials.access_token}`;
5427 }
5428 else {
5429 headers['APCA-API-KEY-ID'] = this.params.credentials.key;
5430 headers['APCA-API-SECRET-KEY'] = this.params.credentials.secret;
5431 }
5432 if (this.params.credentials.paper) {
5433 params.url = params.url.replace('api.', 'paper-api.');
5434 }
5435 let query = '';
5436 if (params.data) {
5437 for (let [key, value] of Object.entries(params.data)) {
5438 if (value instanceof Date) {
5439 params.data[key] = value.toISOString();
5440 }
5441 }
5442 if (!['POST', 'PATCH', 'PUT'].includes(params.method)) {
5443 query = '?'.concat(lib$1.stringify(params.data));
5444 params.data = undefined;
5445 }
5446 }
5447 const makeCall = () => unifetch(params.url.concat(query), {
5448 method: params.method,
5449 headers,
5450 body: JSON.stringify(params.data),
5451 }), func = this.params.rate_limit
5452 ? () => this.limiter.schedule(makeCall)
5453 : makeCall;
5454 let resp, result = {};
5455 try {
5456 resp = await func();
5457 if (!(params.isJSON == undefined ? true : params.isJSON)) {
5458 return resp.ok;
5459 }
5460 result = await resp.json();
5461 }
5462 catch (e) {
5463 console.error(e);
5464 throw result;
5465 }
5466 if ('code' in result || 'message' in result) {
5467 throw result;
5468 }
5469 return result;
5470 }
5471 }
5472
5473 var isBlob = value => {
5474 if (typeof Blob === 'undefined') {
5475 return false;
5476 }
5477
5478 return value instanceof Blob || Object.prototype.toString.call(value) === '[object Blob]';
5479 };
5480
5481 // https://github.com/maxogden/websocket-stream/blob/48dc3ddf943e5ada668c31ccd94e9186f02fafbd/ws-fallback.js
5482
5483 var ws = null;
5484
5485 if (typeof WebSocket !== 'undefined') {
5486 ws = WebSocket;
5487 } else if (typeof MozWebSocket !== 'undefined') {
5488 ws = MozWebSocket;
5489 } else if (typeof commonjsGlobal !== 'undefined') {
5490 ws = commonjsGlobal.WebSocket || commonjsGlobal.MozWebSocket;
5491 } else if (typeof window !== 'undefined') {
5492 ws = window.WebSocket || window.MozWebSocket;
5493 } else if (typeof self !== 'undefined') {
5494 ws = self.WebSocket || self.MozWebSocket;
5495 }
5496
5497 var browser = ws;
5498
5499 var eventemitter3 = createCommonjsModule(function (module) {
5500
5501 var has = Object.prototype.hasOwnProperty
5502 , prefix = '~';
5503
5504 /**
5505 * Constructor to create a storage for our `EE` objects.
5506 * An `Events` instance is a plain object whose properties are event names.
5507 *
5508 * @constructor
5509 * @private
5510 */
5511 function Events() {}
5512
5513 //
5514 // We try to not inherit from `Object.prototype`. In some engines creating an
5515 // instance in this way is faster than calling `Object.create(null)` directly.
5516 // If `Object.create(null)` is not supported we prefix the event names with a
5517 // character to make sure that the built-in object properties are not
5518 // overridden or used as an attack vector.
5519 //
5520 if (Object.create) {
5521 Events.prototype = Object.create(null);
5522
5523 //
5524 // This hack is needed because the `__proto__` property is still inherited in
5525 // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
5526 //
5527 if (!new Events().__proto__) prefix = false;
5528 }
5529
5530 /**
5531 * Representation of a single event listener.
5532 *
5533 * @param {Function} fn The listener function.
5534 * @param {*} context The context to invoke the listener with.
5535 * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
5536 * @constructor
5537 * @private
5538 */
5539 function EE(fn, context, once) {
5540 this.fn = fn;
5541 this.context = context;
5542 this.once = once || false;
5543 }
5544
5545 /**
5546 * Add a listener for a given event.
5547 *
5548 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
5549 * @param {(String|Symbol)} event The event name.
5550 * @param {Function} fn The listener function.
5551 * @param {*} context The context to invoke the listener with.
5552 * @param {Boolean} once Specify if the listener is a one-time listener.
5553 * @returns {EventEmitter}
5554 * @private
5555 */
5556 function addListener(emitter, event, fn, context, once) {
5557 if (typeof fn !== 'function') {
5558 throw new TypeError('The listener must be a function');
5559 }
5560
5561 var listener = new EE(fn, context || emitter, once)
5562 , evt = prefix ? prefix + event : event;
5563
5564 if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
5565 else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
5566 else emitter._events[evt] = [emitter._events[evt], listener];
5567
5568 return emitter;
5569 }
5570
5571 /**
5572 * Clear event by name.
5573 *
5574 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
5575 * @param {(String|Symbol)} evt The Event name.
5576 * @private
5577 */
5578 function clearEvent(emitter, evt) {
5579 if (--emitter._eventsCount === 0) emitter._events = new Events();
5580 else delete emitter._events[evt];
5581 }
5582
5583 /**
5584 * Minimal `EventEmitter` interface that is molded against the Node.js
5585 * `EventEmitter` interface.
5586 *
5587 * @constructor
5588 * @public
5589 */
5590 function EventEmitter() {
5591 this._events = new Events();
5592 this._eventsCount = 0;
5593 }
5594
5595 /**
5596 * Return an array listing the events for which the emitter has registered
5597 * listeners.
5598 *
5599 * @returns {Array}
5600 * @public
5601 */
5602 EventEmitter.prototype.eventNames = function eventNames() {
5603 var names = []
5604 , events
5605 , name;
5606
5607 if (this._eventsCount === 0) return names;
5608
5609 for (name in (events = this._events)) {
5610 if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
5611 }
5612
5613 if (Object.getOwnPropertySymbols) {
5614 return names.concat(Object.getOwnPropertySymbols(events));
5615 }
5616
5617 return names;
5618 };
5619
5620 /**
5621 * Return the listeners registered for a given event.
5622 *
5623 * @param {(String|Symbol)} event The event name.
5624 * @returns {Array} The registered listeners.
5625 * @public
5626 */
5627 EventEmitter.prototype.listeners = function listeners(event) {
5628 var evt = prefix ? prefix + event : event
5629 , handlers = this._events[evt];
5630
5631 if (!handlers) return [];
5632 if (handlers.fn) return [handlers.fn];
5633
5634 for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
5635 ee[i] = handlers[i].fn;
5636 }
5637
5638 return ee;
5639 };
5640
5641 /**
5642 * Return the number of listeners listening to a given event.
5643 *
5644 * @param {(String|Symbol)} event The event name.
5645 * @returns {Number} The number of listeners.
5646 * @public
5647 */
5648 EventEmitter.prototype.listenerCount = function listenerCount(event) {
5649 var evt = prefix ? prefix + event : event
5650 , listeners = this._events[evt];
5651
5652 if (!listeners) return 0;
5653 if (listeners.fn) return 1;
5654 return listeners.length;
5655 };
5656
5657 /**
5658 * Calls each of the listeners registered for a given event.
5659 *
5660 * @param {(String|Symbol)} event The event name.
5661 * @returns {Boolean} `true` if the event had listeners, else `false`.
5662 * @public
5663 */
5664 EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
5665 var evt = prefix ? prefix + event : event;
5666
5667 if (!this._events[evt]) return false;
5668
5669 var listeners = this._events[evt]
5670 , len = arguments.length
5671 , args
5672 , i;
5673
5674 if (listeners.fn) {
5675 if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
5676
5677 switch (len) {
5678 case 1: return listeners.fn.call(listeners.context), true;
5679 case 2: return listeners.fn.call(listeners.context, a1), true;
5680 case 3: return listeners.fn.call(listeners.context, a1, a2), true;
5681 case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
5682 case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
5683 case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
5684 }
5685
5686 for (i = 1, args = new Array(len -1); i < len; i++) {
5687 args[i - 1] = arguments[i];
5688 }
5689
5690 listeners.fn.apply(listeners.context, args);
5691 } else {
5692 var length = listeners.length
5693 , j;
5694
5695 for (i = 0; i < length; i++) {
5696 if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
5697
5698 switch (len) {
5699 case 1: listeners[i].fn.call(listeners[i].context); break;
5700 case 2: listeners[i].fn.call(listeners[i].context, a1); break;
5701 case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
5702 case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
5703 default:
5704 if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
5705 args[j - 1] = arguments[j];
5706 }
5707
5708 listeners[i].fn.apply(listeners[i].context, args);
5709 }
5710 }
5711 }
5712
5713 return true;
5714 };
5715
5716 /**
5717 * Add a listener for a given event.
5718 *
5719 * @param {(String|Symbol)} event The event name.
5720 * @param {Function} fn The listener function.
5721 * @param {*} [context=this] The context to invoke the listener with.
5722 * @returns {EventEmitter} `this`.
5723 * @public
5724 */
5725 EventEmitter.prototype.on = function on(event, fn, context) {
5726 return addListener(this, event, fn, context, false);
5727 };
5728
5729 /**
5730 * Add a one-time listener for a given event.
5731 *
5732 * @param {(String|Symbol)} event The event name.
5733 * @param {Function} fn The listener function.
5734 * @param {*} [context=this] The context to invoke the listener with.
5735 * @returns {EventEmitter} `this`.
5736 * @public
5737 */
5738 EventEmitter.prototype.once = function once(event, fn, context) {
5739 return addListener(this, event, fn, context, true);
5740 };
5741
5742 /**
5743 * Remove the listeners of a given event.
5744 *
5745 * @param {(String|Symbol)} event The event name.
5746 * @param {Function} fn Only remove the listeners that match this function.
5747 * @param {*} context Only remove the listeners that have this context.
5748 * @param {Boolean} once Only remove one-time listeners.
5749 * @returns {EventEmitter} `this`.
5750 * @public
5751 */
5752 EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
5753 var evt = prefix ? prefix + event : event;
5754
5755 if (!this._events[evt]) return this;
5756 if (!fn) {
5757 clearEvent(this, evt);
5758 return this;
5759 }
5760
5761 var listeners = this._events[evt];
5762
5763 if (listeners.fn) {
5764 if (
5765 listeners.fn === fn &&
5766 (!once || listeners.once) &&
5767 (!context || listeners.context === context)
5768 ) {
5769 clearEvent(this, evt);
5770 }
5771 } else {
5772 for (var i = 0, events = [], length = listeners.length; i < length; i++) {
5773 if (
5774 listeners[i].fn !== fn ||
5775 (once && !listeners[i].once) ||
5776 (context && listeners[i].context !== context)
5777 ) {
5778 events.push(listeners[i]);
5779 }
5780 }
5781
5782 //
5783 // Reset the array, or remove it completely if we have no more listeners.
5784 //
5785 if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
5786 else clearEvent(this, evt);
5787 }
5788
5789 return this;
5790 };
5791
5792 /**
5793 * Remove all listeners, or those of the specified event.
5794 *
5795 * @param {(String|Symbol)} [event] The event name.
5796 * @returns {EventEmitter} `this`.
5797 * @public
5798 */
5799 EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
5800 var evt;
5801
5802 if (event) {
5803 evt = prefix ? prefix + event : event;
5804 if (this._events[evt]) clearEvent(this, evt);
5805 } else {
5806 this._events = new Events();
5807 this._eventsCount = 0;
5808 }
5809
5810 return this;
5811 };
5812
5813 //
5814 // Alias methods names because people roll like that.
5815 //
5816 EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
5817 EventEmitter.prototype.addListener = EventEmitter.prototype.on;
5818
5819 //
5820 // Expose the prefix.
5821 //
5822 EventEmitter.prefixed = prefix;
5823
5824 //
5825 // Allow `EventEmitter` to be imported as module namespace.
5826 //
5827 EventEmitter.EventEmitter = EventEmitter;
5828
5829 //
5830 // Expose the module.
5831 //
5832 {
5833 module.exports = EventEmitter;
5834 }
5835 });
5836
5837 class AlpacaStream extends eventemitter3 {
5838 params;
5839 host;
5840 connection;
5841 authenticated;
5842 baseURLs = endpoints;
5843 constructor(params) {
5844 super();
5845 this.params = params;
5846 if ('endpoints' in params) {
5847 this.baseURLs = Object.assign(endpoints, params.endpoints);
5848 }
5849 if (!('paper' in params.credentials) &&
5850 !('key' in params.credentials && params.credentials.key.startsWith('A'))) {
5851 params.credentials['paper'] = true;
5852 }
5853 switch (params.type) {
5854 case 'account':
5855 this.host = params.credentials.paper
5856 ? this.baseURLs.websocket.account.replace('api.', 'paper-api.')
5857 : this.baseURLs.websocket.account;
5858 break;
5859 case 'market_data':
5860 this.host = this.baseURLs.websocket.market_data(this.params.source);
5861 break;
5862 default:
5863 this.host = 'unknown';
5864 }
5865 this.connection = new browser(this.host);
5866 this.connection.onopen = () => {
5867 let message = {};
5868 switch (this.params.type) {
5869 case 'account':
5870 message = {
5871 action: 'authenticate',
5872 data: {
5873 key_id: params.credentials.key,
5874 secret_key: params.credentials.secret,
5875 },
5876 };
5877 break;
5878 case 'market_data':
5879 message = { action: 'auth', ...params.credentials };
5880 break;
5881 }
5882 this.connection.send(JSON.stringify(message));
5883 this.emit('open', this);
5884 };
5885 this.connection.onclose = () => this.emit('close', this);
5886 this.connection.onmessage = async (event) => {
5887 let data = event.data;
5888 if (isBlob(data)) {
5889 data = await event.data.text();
5890 }
5891 else if (data instanceof ArrayBuffer) {
5892 data = String.fromCharCode(...new Uint8Array(event.data));
5893 }
5894 let parsed = JSON.parse(data), messages = this.params.type == 'account' ? [parsed] : parsed;
5895 messages.forEach((message) => {
5896 this.emit('message', message);
5897 if ('T' in message && message.msg == 'authenticated') {
5898 this.authenticated = true;
5899 this.emit('authenticated', this);
5900 }
5901 else if ('stream' in message && message.stream == 'authorization') {
5902 if (message.data.status == 'authorized') {
5903 this.authenticated = true;
5904 this.emit('authenticated', this);
5905 }
5906 }
5907 if ('stream' in message && message.stream == 'trade_updates') {
5908 this.emit('trade_updates', parse.trade_update(message.data));
5909 }
5910 const x = {
5911 success: 'success',
5912 subscription: 'subscription',
5913 error: 'error',
5914 t: 'trade',
5915 q: 'quote',
5916 b: 'bar',
5917 };
5918 if ('T' in message) {
5919 this.emit(x[message.T.split('.')[0]], message);
5920 }
5921 });
5922 };
5923 this.connection.onerror = (err) => {
5924 this.emit('error', err);
5925 };
5926 }
5927 getConnection() {
5928 return this.connection;
5929 }
5930 subscribe(channel, symbols = []) {
5931 switch (this.params.type) {
5932 case 'account':
5933 this.send(JSON.stringify({ action: 'listen', data: { streams: [channel] } }));
5934 break;
5935 case 'market_data':
5936 let message = { action: 'subscribe' };
5937 message[channel] = symbols;
5938 this.send(JSON.stringify(message));
5939 break;
5940 }
5941 return this;
5942 }
5943 unsubscribe(channel, symbols = []) {
5944 switch (this.params.type) {
5945 case 'account':
5946 this.send(JSON.stringify({ action: 'unlisten', data: { streams: [channel] } }));
5947 break;
5948 case 'market_data':
5949 let message = { action: 'unsubscribe' };
5950 message[channel] = symbols;
5951 this.send(JSON.stringify(message));
5952 break;
5953 }
5954 return this;
5955 }
5956 send(message) {
5957 if (!this.authenticated) {
5958 throw new Error('not authenticated');
5959 }
5960 if (typeof message == 'object') {
5961 message = JSON.stringify(message);
5962 }
5963 this.connection.send(message);
5964 return this;
5965 }
5966 }
5967
5968 var index = {
5969 AlpacaClient: AlpacaClient,
5970 AlpacaStream: AlpacaStream,
5971 };
5972
5973 exports.AlpacaClient = AlpacaClient;
5974 exports.AlpacaStream = AlpacaStream;
5975 exports['default'] = index;
5976
5977 Object.defineProperty(exports, '__esModule', { value: true });
5978
5979})));
5980//# sourceMappingURL=alpaca.browser.js.map