UNPKG

163 kBJavaScriptView Raw
1/**
2 * This file contains the full Bottleneck library (MIT) compiled to ES5.
3 * https://github.com/SGrondin/bottleneck
4 * It also contains the regenerator-runtime (MIT), necessary for Babel-generated ES5 code to execute promise and async/await code.
5 * See the following link for Copyright and License information:
6 * https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js
7 */
8(function (global, factory) {
9 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
10 typeof define === 'function' && define.amd ? define(factory) :
11 (global.Bottleneck = factory());
12}(this, (function () { 'use strict';
13
14 var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
15
16 function createCommonjsModule(fn, module) {
17 return module = { exports: {} }, fn(module, module.exports), module.exports;
18 }
19
20 function getCjsExportFromNamespace (n) {
21 return n && n.default || n;
22 }
23
24 var runtime = createCommonjsModule(function (module) {
25 /**
26 * Copyright (c) 2014-present, Facebook, Inc.
27 *
28 * This source code is licensed under the MIT license found in the
29 * LICENSE file in the root directory of this source tree.
30 */
31
32 !(function(global) {
33
34 var Op = Object.prototype;
35 var hasOwn = Op.hasOwnProperty;
36 var undefined; // More compressible than void 0.
37 var $Symbol = typeof Symbol === "function" ? Symbol : {};
38 var iteratorSymbol = $Symbol.iterator || "@@iterator";
39 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
40 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
41 var runtime = global.regeneratorRuntime;
42 if (runtime) {
43 {
44 // If regeneratorRuntime is defined globally and we're in a module,
45 // make the exports object identical to regeneratorRuntime.
46 module.exports = runtime;
47 }
48 // Don't bother evaluating the rest of this file if the runtime was
49 // already defined globally.
50 return;
51 }
52
53 // Define the runtime globally (as expected by generated code) as either
54 // module.exports (if we're in a module) or a new, empty object.
55 runtime = global.regeneratorRuntime = module.exports;
56
57 function wrap(innerFn, outerFn, self, tryLocsList) {
58 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
59 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
60 var generator = Object.create(protoGenerator.prototype);
61 var context = new Context(tryLocsList || []);
62
63 // The ._invoke method unifies the implementations of the .next,
64 // .throw, and .return methods.
65 generator._invoke = makeInvokeMethod(innerFn, self, context);
66
67 return generator;
68 }
69 runtime.wrap = wrap;
70
71 // Try/catch helper to minimize deoptimizations. Returns a completion
72 // record like context.tryEntries[i].completion. This interface could
73 // have been (and was previously) designed to take a closure to be
74 // invoked without arguments, but in all the cases we care about we
75 // already have an existing method we want to call, so there's no need
76 // to create a new function object. We can even get away with assuming
77 // the method takes exactly one argument, since that happens to be true
78 // in every case, so we don't have to touch the arguments object. The
79 // only additional allocation required is the completion record, which
80 // has a stable shape and so hopefully should be cheap to allocate.
81 function tryCatch(fn, obj, arg) {
82 try {
83 return { type: "normal", arg: fn.call(obj, arg) };
84 } catch (err) {
85 return { type: "throw", arg: err };
86 }
87 }
88
89 var GenStateSuspendedStart = "suspendedStart";
90 var GenStateSuspendedYield = "suspendedYield";
91 var GenStateExecuting = "executing";
92 var GenStateCompleted = "completed";
93
94 // Returning this object from the innerFn has the same effect as
95 // breaking out of the dispatch switch statement.
96 var ContinueSentinel = {};
97
98 // Dummy constructor functions that we use as the .constructor and
99 // .constructor.prototype properties for functions that return Generator
100 // objects. For full spec compliance, you may wish to configure your
101 // minifier not to mangle the names of these two functions.
102 function Generator() {}
103 function GeneratorFunction() {}
104 function GeneratorFunctionPrototype() {}
105
106 // This is a polyfill for %IteratorPrototype% for environments that
107 // don't natively support it.
108 var IteratorPrototype = {};
109 IteratorPrototype[iteratorSymbol] = function () {
110 return this;
111 };
112
113 var getProto = Object.getPrototypeOf;
114 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
115 if (NativeIteratorPrototype &&
116 NativeIteratorPrototype !== Op &&
117 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
118 // This environment has a native %IteratorPrototype%; use it instead
119 // of the polyfill.
120 IteratorPrototype = NativeIteratorPrototype;
121 }
122
123 var Gp = GeneratorFunctionPrototype.prototype =
124 Generator.prototype = Object.create(IteratorPrototype);
125 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
126 GeneratorFunctionPrototype.constructor = GeneratorFunction;
127 GeneratorFunctionPrototype[toStringTagSymbol] =
128 GeneratorFunction.displayName = "GeneratorFunction";
129
130 // Helper for defining the .next, .throw, and .return methods of the
131 // Iterator interface in terms of a single ._invoke method.
132 function defineIteratorMethods(prototype) {
133 ["next", "throw", "return"].forEach(function(method) {
134 prototype[method] = function(arg) {
135 return this._invoke(method, arg);
136 };
137 });
138 }
139
140 runtime.isGeneratorFunction = function(genFun) {
141 var ctor = typeof genFun === "function" && genFun.constructor;
142 return ctor
143 ? ctor === GeneratorFunction ||
144 // For the native GeneratorFunction constructor, the best we can
145 // do is to check its .name property.
146 (ctor.displayName || ctor.name) === "GeneratorFunction"
147 : false;
148 };
149
150 runtime.mark = function(genFun) {
151 if (Object.setPrototypeOf) {
152 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
153 } else {
154 genFun.__proto__ = GeneratorFunctionPrototype;
155 if (!(toStringTagSymbol in genFun)) {
156 genFun[toStringTagSymbol] = "GeneratorFunction";
157 }
158 }
159 genFun.prototype = Object.create(Gp);
160 return genFun;
161 };
162
163 // Within the body of any async function, `await x` is transformed to
164 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
165 // `hasOwn.call(value, "__await")` to determine if the yielded value is
166 // meant to be awaited.
167 runtime.awrap = function(arg) {
168 return { __await: arg };
169 };
170
171 function AsyncIterator(generator) {
172 function invoke(method, arg, resolve, reject) {
173 var record = tryCatch(generator[method], generator, arg);
174 if (record.type === "throw") {
175 reject(record.arg);
176 } else {
177 var result = record.arg;
178 var value = result.value;
179 if (value &&
180 typeof value === "object" &&
181 hasOwn.call(value, "__await")) {
182 return Promise.resolve(value.__await).then(function(value) {
183 invoke("next", value, resolve, reject);
184 }, function(err) {
185 invoke("throw", err, resolve, reject);
186 });
187 }
188
189 return Promise.resolve(value).then(function(unwrapped) {
190 // When a yielded Promise is resolved, its final value becomes
191 // the .value of the Promise<{value,done}> result for the
192 // current iteration.
193 result.value = unwrapped;
194 resolve(result);
195 }, function(error) {
196 // If a rejected Promise was yielded, throw the rejection back
197 // into the async generator function so it can be handled there.
198 return invoke("throw", error, resolve, reject);
199 });
200 }
201 }
202
203 var previousPromise;
204
205 function enqueue(method, arg) {
206 function callInvokeWithMethodAndArg() {
207 return new Promise(function(resolve, reject) {
208 invoke(method, arg, resolve, reject);
209 });
210 }
211
212 return previousPromise =
213 // If enqueue has been called before, then we want to wait until
214 // all previous Promises have been resolved before calling invoke,
215 // so that results are always delivered in the correct order. If
216 // enqueue has not been called before, then it is important to
217 // call invoke immediately, without waiting on a callback to fire,
218 // so that the async generator function has the opportunity to do
219 // any necessary setup in a predictable way. This predictability
220 // is why the Promise constructor synchronously invokes its
221 // executor callback, and why async functions synchronously
222 // execute code before the first await. Since we implement simple
223 // async functions in terms of async generators, it is especially
224 // important to get this right, even though it requires care.
225 previousPromise ? previousPromise.then(
226 callInvokeWithMethodAndArg,
227 // Avoid propagating failures to Promises returned by later
228 // invocations of the iterator.
229 callInvokeWithMethodAndArg
230 ) : callInvokeWithMethodAndArg();
231 }
232
233 // Define the unified helper method that is used to implement .next,
234 // .throw, and .return (see defineIteratorMethods).
235 this._invoke = enqueue;
236 }
237
238 defineIteratorMethods(AsyncIterator.prototype);
239 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
240 return this;
241 };
242 runtime.AsyncIterator = AsyncIterator;
243
244 // Note that simple async functions are implemented on top of
245 // AsyncIterator objects; they just return a Promise for the value of
246 // the final result produced by the iterator.
247 runtime.async = function(innerFn, outerFn, self, tryLocsList) {
248 var iter = new AsyncIterator(
249 wrap(innerFn, outerFn, self, tryLocsList)
250 );
251
252 return runtime.isGeneratorFunction(outerFn)
253 ? iter // If outerFn is a generator, return the full iterator.
254 : iter.next().then(function(result) {
255 return result.done ? result.value : iter.next();
256 });
257 };
258
259 function makeInvokeMethod(innerFn, self, context) {
260 var state = GenStateSuspendedStart;
261
262 return function invoke(method, arg) {
263 if (state === GenStateExecuting) {
264 throw new Error("Generator is already running");
265 }
266
267 if (state === GenStateCompleted) {
268 if (method === "throw") {
269 throw arg;
270 }
271
272 // Be forgiving, per 25.3.3.3.3 of the spec:
273 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
274 return doneResult();
275 }
276
277 context.method = method;
278 context.arg = arg;
279
280 while (true) {
281 var delegate = context.delegate;
282 if (delegate) {
283 var delegateResult = maybeInvokeDelegate(delegate, context);
284 if (delegateResult) {
285 if (delegateResult === ContinueSentinel) continue;
286 return delegateResult;
287 }
288 }
289
290 if (context.method === "next") {
291 // Setting context._sent for legacy support of Babel's
292 // function.sent implementation.
293 context.sent = context._sent = context.arg;
294
295 } else if (context.method === "throw") {
296 if (state === GenStateSuspendedStart) {
297 state = GenStateCompleted;
298 throw context.arg;
299 }
300
301 context.dispatchException(context.arg);
302
303 } else if (context.method === "return") {
304 context.abrupt("return", context.arg);
305 }
306
307 state = GenStateExecuting;
308
309 var record = tryCatch(innerFn, self, context);
310 if (record.type === "normal") {
311 // If an exception is thrown from innerFn, we leave state ===
312 // GenStateExecuting and loop back for another invocation.
313 state = context.done
314 ? GenStateCompleted
315 : GenStateSuspendedYield;
316
317 if (record.arg === ContinueSentinel) {
318 continue;
319 }
320
321 return {
322 value: record.arg,
323 done: context.done
324 };
325
326 } else if (record.type === "throw") {
327 state = GenStateCompleted;
328 // Dispatch the exception by looping back around to the
329 // context.dispatchException(context.arg) call above.
330 context.method = "throw";
331 context.arg = record.arg;
332 }
333 }
334 };
335 }
336
337 // Call delegate.iterator[context.method](context.arg) and handle the
338 // result, either by returning a { value, done } result from the
339 // delegate iterator, or by modifying context.method and context.arg,
340 // setting context.delegate to null, and returning the ContinueSentinel.
341 function maybeInvokeDelegate(delegate, context) {
342 var method = delegate.iterator[context.method];
343 if (method === undefined) {
344 // A .throw or .return when the delegate iterator has no .throw
345 // method always terminates the yield* loop.
346 context.delegate = null;
347
348 if (context.method === "throw") {
349 if (delegate.iterator.return) {
350 // If the delegate iterator has a return method, give it a
351 // chance to clean up.
352 context.method = "return";
353 context.arg = undefined;
354 maybeInvokeDelegate(delegate, context);
355
356 if (context.method === "throw") {
357 // If maybeInvokeDelegate(context) changed context.method from
358 // "return" to "throw", let that override the TypeError below.
359 return ContinueSentinel;
360 }
361 }
362
363 context.method = "throw";
364 context.arg = new TypeError(
365 "The iterator does not provide a 'throw' method");
366 }
367
368 return ContinueSentinel;
369 }
370
371 var record = tryCatch(method, delegate.iterator, context.arg);
372
373 if (record.type === "throw") {
374 context.method = "throw";
375 context.arg = record.arg;
376 context.delegate = null;
377 return ContinueSentinel;
378 }
379
380 var info = record.arg;
381
382 if (! info) {
383 context.method = "throw";
384 context.arg = new TypeError("iterator result is not an object");
385 context.delegate = null;
386 return ContinueSentinel;
387 }
388
389 if (info.done) {
390 // Assign the result of the finished delegate to the temporary
391 // variable specified by delegate.resultName (see delegateYield).
392 context[delegate.resultName] = info.value;
393
394 // Resume execution at the desired location (see delegateYield).
395 context.next = delegate.nextLoc;
396
397 // If context.method was "throw" but the delegate handled the
398 // exception, let the outer generator proceed normally. If
399 // context.method was "next", forget context.arg since it has been
400 // "consumed" by the delegate iterator. If context.method was
401 // "return", allow the original .return call to continue in the
402 // outer generator.
403 if (context.method !== "return") {
404 context.method = "next";
405 context.arg = undefined;
406 }
407
408 } else {
409 // Re-yield the result returned by the delegate method.
410 return info;
411 }
412
413 // The delegate iterator is finished, so forget it and continue with
414 // the outer generator.
415 context.delegate = null;
416 return ContinueSentinel;
417 }
418
419 // Define Generator.prototype.{next,throw,return} in terms of the
420 // unified ._invoke helper method.
421 defineIteratorMethods(Gp);
422
423 Gp[toStringTagSymbol] = "Generator";
424
425 // A Generator should always return itself as the iterator object when the
426 // @@iterator function is called on it. Some browsers' implementations of the
427 // iterator prototype chain incorrectly implement this, causing the Generator
428 // object to not be returned from this call. This ensures that doesn't happen.
429 // See https://github.com/facebook/regenerator/issues/274 for more details.
430 Gp[iteratorSymbol] = function() {
431 return this;
432 };
433
434 Gp.toString = function() {
435 return "[object Generator]";
436 };
437
438 function pushTryEntry(locs) {
439 var entry = { tryLoc: locs[0] };
440
441 if (1 in locs) {
442 entry.catchLoc = locs[1];
443 }
444
445 if (2 in locs) {
446 entry.finallyLoc = locs[2];
447 entry.afterLoc = locs[3];
448 }
449
450 this.tryEntries.push(entry);
451 }
452
453 function resetTryEntry(entry) {
454 var record = entry.completion || {};
455 record.type = "normal";
456 delete record.arg;
457 entry.completion = record;
458 }
459
460 function Context(tryLocsList) {
461 // The root entry object (effectively a try statement without a catch
462 // or a finally block) gives us a place to store values thrown from
463 // locations where there is no enclosing try statement.
464 this.tryEntries = [{ tryLoc: "root" }];
465 tryLocsList.forEach(pushTryEntry, this);
466 this.reset(true);
467 }
468
469 runtime.keys = function(object) {
470 var keys = [];
471 for (var key in object) {
472 keys.push(key);
473 }
474 keys.reverse();
475
476 // Rather than returning an object with a next method, we keep
477 // things simple and return the next function itself.
478 return function next() {
479 while (keys.length) {
480 var key = keys.pop();
481 if (key in object) {
482 next.value = key;
483 next.done = false;
484 return next;
485 }
486 }
487
488 // To avoid creating an additional object, we just hang the .value
489 // and .done properties off the next function object itself. This
490 // also ensures that the minifier will not anonymize the function.
491 next.done = true;
492 return next;
493 };
494 };
495
496 function values(iterable) {
497 if (iterable) {
498 var iteratorMethod = iterable[iteratorSymbol];
499 if (iteratorMethod) {
500 return iteratorMethod.call(iterable);
501 }
502
503 if (typeof iterable.next === "function") {
504 return iterable;
505 }
506
507 if (!isNaN(iterable.length)) {
508 var i = -1, next = function next() {
509 while (++i < iterable.length) {
510 if (hasOwn.call(iterable, i)) {
511 next.value = iterable[i];
512 next.done = false;
513 return next;
514 }
515 }
516
517 next.value = undefined;
518 next.done = true;
519
520 return next;
521 };
522
523 return next.next = next;
524 }
525 }
526
527 // Return an iterator with no values.
528 return { next: doneResult };
529 }
530 runtime.values = values;
531
532 function doneResult() {
533 return { value: undefined, done: true };
534 }
535
536 Context.prototype = {
537 constructor: Context,
538
539 reset: function(skipTempReset) {
540 this.prev = 0;
541 this.next = 0;
542 // Resetting context._sent for legacy support of Babel's
543 // function.sent implementation.
544 this.sent = this._sent = undefined;
545 this.done = false;
546 this.delegate = null;
547
548 this.method = "next";
549 this.arg = undefined;
550
551 this.tryEntries.forEach(resetTryEntry);
552
553 if (!skipTempReset) {
554 for (var name in this) {
555 // Not sure about the optimal order of these conditions:
556 if (name.charAt(0) === "t" &&
557 hasOwn.call(this, name) &&
558 !isNaN(+name.slice(1))) {
559 this[name] = undefined;
560 }
561 }
562 }
563 },
564
565 stop: function() {
566 this.done = true;
567
568 var rootEntry = this.tryEntries[0];
569 var rootRecord = rootEntry.completion;
570 if (rootRecord.type === "throw") {
571 throw rootRecord.arg;
572 }
573
574 return this.rval;
575 },
576
577 dispatchException: function(exception) {
578 if (this.done) {
579 throw exception;
580 }
581
582 var context = this;
583 function handle(loc, caught) {
584 record.type = "throw";
585 record.arg = exception;
586 context.next = loc;
587
588 if (caught) {
589 // If the dispatched exception was caught by a catch block,
590 // then let that catch block handle the exception normally.
591 context.method = "next";
592 context.arg = undefined;
593 }
594
595 return !! caught;
596 }
597
598 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
599 var entry = this.tryEntries[i];
600 var record = entry.completion;
601
602 if (entry.tryLoc === "root") {
603 // Exception thrown outside of any try block that could handle
604 // it, so set the completion value of the entire function to
605 // throw the exception.
606 return handle("end");
607 }
608
609 if (entry.tryLoc <= this.prev) {
610 var hasCatch = hasOwn.call(entry, "catchLoc");
611 var hasFinally = hasOwn.call(entry, "finallyLoc");
612
613 if (hasCatch && hasFinally) {
614 if (this.prev < entry.catchLoc) {
615 return handle(entry.catchLoc, true);
616 } else if (this.prev < entry.finallyLoc) {
617 return handle(entry.finallyLoc);
618 }
619
620 } else if (hasCatch) {
621 if (this.prev < entry.catchLoc) {
622 return handle(entry.catchLoc, true);
623 }
624
625 } else if (hasFinally) {
626 if (this.prev < entry.finallyLoc) {
627 return handle(entry.finallyLoc);
628 }
629
630 } else {
631 throw new Error("try statement without catch or finally");
632 }
633 }
634 }
635 },
636
637 abrupt: function(type, arg) {
638 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
639 var entry = this.tryEntries[i];
640 if (entry.tryLoc <= this.prev &&
641 hasOwn.call(entry, "finallyLoc") &&
642 this.prev < entry.finallyLoc) {
643 var finallyEntry = entry;
644 break;
645 }
646 }
647
648 if (finallyEntry &&
649 (type === "break" ||
650 type === "continue") &&
651 finallyEntry.tryLoc <= arg &&
652 arg <= finallyEntry.finallyLoc) {
653 // Ignore the finally entry if control is not jumping to a
654 // location outside the try/catch block.
655 finallyEntry = null;
656 }
657
658 var record = finallyEntry ? finallyEntry.completion : {};
659 record.type = type;
660 record.arg = arg;
661
662 if (finallyEntry) {
663 this.method = "next";
664 this.next = finallyEntry.finallyLoc;
665 return ContinueSentinel;
666 }
667
668 return this.complete(record);
669 },
670
671 complete: function(record, afterLoc) {
672 if (record.type === "throw") {
673 throw record.arg;
674 }
675
676 if (record.type === "break" ||
677 record.type === "continue") {
678 this.next = record.arg;
679 } else if (record.type === "return") {
680 this.rval = this.arg = record.arg;
681 this.method = "return";
682 this.next = "end";
683 } else if (record.type === "normal" && afterLoc) {
684 this.next = afterLoc;
685 }
686
687 return ContinueSentinel;
688 },
689
690 finish: function(finallyLoc) {
691 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
692 var entry = this.tryEntries[i];
693 if (entry.finallyLoc === finallyLoc) {
694 this.complete(entry.completion, entry.afterLoc);
695 resetTryEntry(entry);
696 return ContinueSentinel;
697 }
698 }
699 },
700
701 "catch": function(tryLoc) {
702 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
703 var entry = this.tryEntries[i];
704 if (entry.tryLoc === tryLoc) {
705 var record = entry.completion;
706 if (record.type === "throw") {
707 var thrown = record.arg;
708 resetTryEntry(entry);
709 }
710 return thrown;
711 }
712 }
713
714 // The context.catch method must only be called with a location
715 // argument that corresponds to a known catch block.
716 throw new Error("illegal catch attempt");
717 },
718
719 delegateYield: function(iterable, resultName, nextLoc) {
720 this.delegate = {
721 iterator: values(iterable),
722 resultName: resultName,
723 nextLoc: nextLoc
724 };
725
726 if (this.method === "next") {
727 // Deliberately forget the last sent value so that we don't
728 // accidentally pass it on to the delegate.
729 this.arg = undefined;
730 }
731
732 return ContinueSentinel;
733 }
734 };
735 })(
736 // In sloppy mode, unbound `this` refers to the global object, fallback to
737 // Function constructor if we're in global strict mode. That is sadly a form
738 // of indirect eval which violates Content Security Policy.
739 (function() {
740 return this || (typeof self === "object" && self);
741 })() || Function("return this")()
742 );
743 });
744
745 function _typeof(obj) {
746 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
747 _typeof = function (obj) {
748 return typeof obj;
749 };
750 } else {
751 _typeof = function (obj) {
752 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
753 };
754 }
755
756 return _typeof(obj);
757 }
758
759 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
760 try {
761 var info = gen[key](arg);
762 var value = info.value;
763 } catch (error) {
764 reject(error);
765 return;
766 }
767
768 if (info.done) {
769 resolve(value);
770 } else {
771 Promise.resolve(value).then(_next, _throw);
772 }
773 }
774
775 function _asyncToGenerator(fn) {
776 return function () {
777 var self = this,
778 args = arguments;
779 return new Promise(function (resolve, reject) {
780 var gen = fn.apply(self, args);
781
782 function _next(value) {
783 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
784 }
785
786 function _throw(err) {
787 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
788 }
789
790 _next(undefined);
791 });
792 };
793 }
794
795 function _classCallCheck(instance, Constructor) {
796 if (!(instance instanceof Constructor)) {
797 throw new TypeError("Cannot call a class as a function");
798 }
799 }
800
801 function _defineProperties(target, props) {
802 for (var i = 0; i < props.length; i++) {
803 var descriptor = props[i];
804 descriptor.enumerable = descriptor.enumerable || false;
805 descriptor.configurable = true;
806 if ("value" in descriptor) descriptor.writable = true;
807 Object.defineProperty(target, descriptor.key, descriptor);
808 }
809 }
810
811 function _createClass(Constructor, protoProps, staticProps) {
812 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
813 if (staticProps) _defineProperties(Constructor, staticProps);
814 return Constructor;
815 }
816
817 function _inherits(subClass, superClass) {
818 if (typeof superClass !== "function" && superClass !== null) {
819 throw new TypeError("Super expression must either be null or a function");
820 }
821
822 subClass.prototype = Object.create(superClass && superClass.prototype, {
823 constructor: {
824 value: subClass,
825 writable: true,
826 configurable: true
827 }
828 });
829 if (superClass) _setPrototypeOf(subClass, superClass);
830 }
831
832 function _getPrototypeOf(o) {
833 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
834 return o.__proto__ || Object.getPrototypeOf(o);
835 };
836 return _getPrototypeOf(o);
837 }
838
839 function _setPrototypeOf(o, p) {
840 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
841 o.__proto__ = p;
842 return o;
843 };
844
845 return _setPrototypeOf(o, p);
846 }
847
848 function isNativeReflectConstruct() {
849 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
850 if (Reflect.construct.sham) return false;
851 if (typeof Proxy === "function") return true;
852
853 try {
854 Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
855 return true;
856 } catch (e) {
857 return false;
858 }
859 }
860
861 function _construct(Parent, args, Class) {
862 if (isNativeReflectConstruct()) {
863 _construct = Reflect.construct;
864 } else {
865 _construct = function _construct(Parent, args, Class) {
866 var a = [null];
867 a.push.apply(a, args);
868 var Constructor = Function.bind.apply(Parent, a);
869 var instance = new Constructor();
870 if (Class) _setPrototypeOf(instance, Class.prototype);
871 return instance;
872 };
873 }
874
875 return _construct.apply(null, arguments);
876 }
877
878 function _isNativeFunction(fn) {
879 return Function.toString.call(fn).indexOf("[native code]") !== -1;
880 }
881
882 function _wrapNativeSuper(Class) {
883 var _cache = typeof Map === "function" ? new Map() : undefined;
884
885 _wrapNativeSuper = function _wrapNativeSuper(Class) {
886 if (Class === null || !_isNativeFunction(Class)) return Class;
887
888 if (typeof Class !== "function") {
889 throw new TypeError("Super expression must either be null or a function");
890 }
891
892 if (typeof _cache !== "undefined") {
893 if (_cache.has(Class)) return _cache.get(Class);
894
895 _cache.set(Class, Wrapper);
896 }
897
898 function Wrapper() {
899 return _construct(Class, arguments, _getPrototypeOf(this).constructor);
900 }
901
902 Wrapper.prototype = Object.create(Class.prototype, {
903 constructor: {
904 value: Wrapper,
905 enumerable: false,
906 writable: true,
907 configurable: true
908 }
909 });
910 return _setPrototypeOf(Wrapper, Class);
911 };
912
913 return _wrapNativeSuper(Class);
914 }
915
916 function _assertThisInitialized(self) {
917 if (self === void 0) {
918 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
919 }
920
921 return self;
922 }
923
924 function _possibleConstructorReturn(self, call) {
925 if (call && (typeof call === "object" || typeof call === "function")) {
926 return call;
927 }
928
929 return _assertThisInitialized(self);
930 }
931
932 function _slicedToArray(arr, i) {
933 return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
934 }
935
936 function _toArray(arr) {
937 return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
938 }
939
940 function _toConsumableArray(arr) {
941 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
942 }
943
944 function _arrayWithoutHoles(arr) {
945 if (Array.isArray(arr)) {
946 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
947
948 return arr2;
949 }
950 }
951
952 function _arrayWithHoles(arr) {
953 if (Array.isArray(arr)) return arr;
954 }
955
956 function _iterableToArray(iter) {
957 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
958 }
959
960 function _iterableToArrayLimit(arr, i) {
961 var _arr = [];
962 var _n = true;
963 var _d = false;
964 var _e = undefined;
965
966 try {
967 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
968 _arr.push(_s.value);
969
970 if (i && _arr.length === i) break;
971 }
972 } catch (err) {
973 _d = true;
974 _e = err;
975 } finally {
976 try {
977 if (!_n && _i["return"] != null) _i["return"]();
978 } finally {
979 if (_d) throw _e;
980 }
981 }
982
983 return _arr;
984 }
985
986 function _nonIterableSpread() {
987 throw new TypeError("Invalid attempt to spread non-iterable instance");
988 }
989
990 function _nonIterableRest() {
991 throw new TypeError("Invalid attempt to destructure non-iterable instance");
992 }
993
994 var load = function load(received, defaults) {
995 var onto = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
996 var k, ref, v;
997
998 for (k in defaults) {
999 v = defaults[k];
1000 onto[k] = (ref = received[k]) != null ? ref : v;
1001 }
1002
1003 return onto;
1004 };
1005
1006 var overwrite = function overwrite(received, defaults) {
1007 var onto = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1008 var k, v;
1009
1010 for (k in received) {
1011 v = received[k];
1012
1013 if (defaults[k] !== void 0) {
1014 onto[k] = v;
1015 }
1016 }
1017
1018 return onto;
1019 };
1020
1021 var parser = {
1022 load: load,
1023 overwrite: overwrite
1024 };
1025
1026 var DLList;
1027
1028 DLList =
1029 /*#__PURE__*/
1030 function () {
1031 function DLList(_queues) {
1032 _classCallCheck(this, DLList);
1033
1034 this._queues = _queues;
1035 this._first = null;
1036 this._last = null;
1037 this.length = 0;
1038 }
1039
1040 _createClass(DLList, [{
1041 key: "push",
1042 value: function push(value) {
1043 var node, ref1;
1044 this.length++;
1045
1046 if ((ref1 = this._queues) != null) {
1047 ref1.incr();
1048 }
1049
1050 node = {
1051 value: value,
1052 next: null
1053 };
1054
1055 if (this._last != null) {
1056 this._last.next = node;
1057 this._last = node;
1058 } else {
1059 this._first = this._last = node;
1060 }
1061
1062 return void 0;
1063 }
1064 }, {
1065 key: "shift",
1066 value: function shift() {
1067 var ref1, ref2, value;
1068
1069 if (this._first == null) {
1070 return void 0;
1071 } else {
1072 this.length--;
1073
1074 if ((ref1 = this._queues) != null) {
1075 ref1.decr();
1076 }
1077 }
1078
1079 value = this._first.value;
1080 this._first = (ref2 = this._first.next) != null ? ref2 : this._last = null;
1081 return value;
1082 }
1083 }, {
1084 key: "first",
1085 value: function first() {
1086 if (this._first != null) {
1087 return this._first.value;
1088 }
1089 }
1090 }, {
1091 key: "getArray",
1092 value: function getArray() {
1093 var node, ref, results;
1094 node = this._first;
1095 results = [];
1096
1097 while (node != null) {
1098 results.push((ref = node, node = node.next, ref.value));
1099 }
1100
1101 return results;
1102 }
1103 }, {
1104 key: "forEachShift",
1105 value: function forEachShift(cb) {
1106 var node;
1107 node = this.shift();
1108
1109 while (node != null) {
1110 cb(node), node = this.shift();
1111 }
1112
1113 return void 0;
1114 }
1115 }]);
1116
1117 return DLList;
1118 }();
1119
1120 var DLList_1 = DLList;
1121
1122 var Events;
1123
1124 Events =
1125 /*#__PURE__*/
1126 function () {
1127 function Events(instance) {
1128 var _this = this;
1129
1130 _classCallCheck(this, Events);
1131
1132 this.instance = instance;
1133 this._events = {};
1134
1135 if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) {
1136 throw new Error("An Emitter already exists for this object");
1137 }
1138
1139 this.instance.on = function (name, cb) {
1140 return _this._addListener(name, "many", cb);
1141 };
1142
1143 this.instance.once = function (name, cb) {
1144 return _this._addListener(name, "once", cb);
1145 };
1146
1147 this.instance.removeAllListeners = function () {
1148 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
1149
1150 if (name != null) {
1151 return delete _this._events[name];
1152 } else {
1153 return _this._events = {};
1154 }
1155 };
1156 }
1157
1158 _createClass(Events, [{
1159 key: "_addListener",
1160 value: function _addListener(name, status, cb) {
1161 var base;
1162
1163 if ((base = this._events)[name] == null) {
1164 base[name] = [];
1165 }
1166
1167 this._events[name].push({
1168 cb: cb,
1169 status: status
1170 });
1171
1172 return this.instance;
1173 }
1174 }, {
1175 key: "listenerCount",
1176 value: function listenerCount(name) {
1177 if (this._events[name] != null) {
1178 return this._events[name].length;
1179 } else {
1180 return 0;
1181 }
1182 }
1183 }, {
1184 key: "trigger",
1185 value: function () {
1186 var _trigger = _asyncToGenerator(
1187 /*#__PURE__*/
1188 regeneratorRuntime.mark(function _callee2(name) {
1189 var _this2 = this;
1190
1191 var _len,
1192 args,
1193 _key,
1194 e,
1195 promises,
1196 _args2 = arguments;
1197
1198 return regeneratorRuntime.wrap(function _callee2$(_context2) {
1199 while (1) {
1200 switch (_context2.prev = _context2.next) {
1201 case 0:
1202 for (_len = _args2.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1203 args[_key - 1] = _args2[_key];
1204 }
1205
1206 _context2.prev = 1;
1207
1208 if (name !== "debug") {
1209 this.trigger("debug", "Event triggered: ".concat(name), args);
1210 }
1211
1212 if (!(this._events[name] == null)) {
1213 _context2.next = 5;
1214 break;
1215 }
1216
1217 return _context2.abrupt("return");
1218
1219 case 5:
1220 this._events[name] = this._events[name].filter(function (listener) {
1221 return listener.status !== "none";
1222 });
1223 promises = this._events[name].map(
1224 /*#__PURE__*/
1225 function () {
1226 var _ref = _asyncToGenerator(
1227 /*#__PURE__*/
1228 regeneratorRuntime.mark(function _callee(listener) {
1229 var e, returned;
1230 return regeneratorRuntime.wrap(function _callee$(_context) {
1231 while (1) {
1232 switch (_context.prev = _context.next) {
1233 case 0:
1234 if (!(listener.status === "none")) {
1235 _context.next = 2;
1236 break;
1237 }
1238
1239 return _context.abrupt("return");
1240
1241 case 2:
1242 if (listener.status === "once") {
1243 listener.status = "none";
1244 }
1245
1246 _context.prev = 3;
1247 returned = typeof listener.cb === "function" ? listener.cb.apply(listener, args) : void 0;
1248
1249 if (!(typeof (returned != null ? returned.then : void 0) === "function")) {
1250 _context.next = 11;
1251 break;
1252 }
1253
1254 _context.next = 8;
1255 return returned;
1256
1257 case 8:
1258 return _context.abrupt("return", _context.sent);
1259
1260 case 11:
1261 return _context.abrupt("return", returned);
1262
1263 case 12:
1264 _context.next = 19;
1265 break;
1266
1267 case 14:
1268 _context.prev = 14;
1269 _context.t0 = _context["catch"](3);
1270 e = _context.t0;
1271
1272 {
1273 _this2.trigger("error", e);
1274 }
1275
1276 return _context.abrupt("return", null);
1277
1278 case 19:
1279 case "end":
1280 return _context.stop();
1281 }
1282 }
1283 }, _callee, this, [[3, 14]]);
1284 }));
1285
1286 return function (_x2) {
1287 return _ref.apply(this, arguments);
1288 };
1289 }());
1290 _context2.next = 9;
1291 return Promise.all(promises);
1292
1293 case 9:
1294 _context2.t0 = function (x) {
1295 return x != null;
1296 };
1297
1298 return _context2.abrupt("return", _context2.sent.find(_context2.t0));
1299
1300 case 13:
1301 _context2.prev = 13;
1302 _context2.t1 = _context2["catch"](1);
1303 e = _context2.t1;
1304
1305 {
1306 this.trigger("error", e);
1307 }
1308
1309 return _context2.abrupt("return", null);
1310
1311 case 18:
1312 case "end":
1313 return _context2.stop();
1314 }
1315 }
1316 }, _callee2, this, [[1, 13]]);
1317 }));
1318
1319 return function trigger(_x) {
1320 return _trigger.apply(this, arguments);
1321 };
1322 }()
1323 }]);
1324
1325 return Events;
1326 }();
1327
1328 var Events_1 = Events;
1329
1330 var DLList$1, Events$1, Queues;
1331 DLList$1 = DLList_1;
1332 Events$1 = Events_1;
1333
1334 Queues =
1335 /*#__PURE__*/
1336 function () {
1337 function Queues(num_priorities) {
1338 _classCallCheck(this, Queues);
1339
1340 var i;
1341 this.Events = new Events$1(this);
1342 this._length = 0;
1343
1344 this._lists = function () {
1345 var j, ref, results;
1346 results = [];
1347
1348 for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) {
1349 results.push(new DLList$1(this));
1350 }
1351
1352 return results;
1353 }.call(this);
1354 }
1355
1356 _createClass(Queues, [{
1357 key: "incr",
1358 value: function incr() {
1359 if (this._length++ === 0) {
1360 return this.Events.trigger("leftzero");
1361 }
1362 }
1363 }, {
1364 key: "decr",
1365 value: function decr() {
1366 if (--this._length === 0) {
1367 return this.Events.trigger("zero");
1368 }
1369 }
1370 }, {
1371 key: "push",
1372 value: function push(priority, job) {
1373 return this._lists[priority].push(job);
1374 }
1375 }, {
1376 key: "queued",
1377 value: function queued(priority) {
1378 if (priority != null) {
1379 return this._lists[priority].length;
1380 } else {
1381 return this._length;
1382 }
1383 }
1384 }, {
1385 key: "shiftAll",
1386 value: function shiftAll(fn) {
1387 return this._lists.forEach(function (list) {
1388 return list.forEachShift(fn);
1389 });
1390 }
1391 }, {
1392 key: "getFirst",
1393 value: function getFirst() {
1394 var arr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._lists;
1395 var j, len, list;
1396
1397 for (j = 0, len = arr.length; j < len; j++) {
1398 list = arr[j];
1399
1400 if (list.length > 0) {
1401 return list;
1402 }
1403 }
1404
1405 return [];
1406 }
1407 }, {
1408 key: "shiftLastFrom",
1409 value: function shiftLastFrom(priority) {
1410 return this.getFirst(this._lists.slice(priority).reverse()).shift();
1411 }
1412 }]);
1413
1414 return Queues;
1415 }();
1416
1417 var Queues_1 = Queues;
1418
1419 var BottleneckError;
1420
1421 BottleneckError =
1422 /*#__PURE__*/
1423 function (_Error) {
1424 _inherits(BottleneckError, _Error);
1425
1426 function BottleneckError() {
1427 _classCallCheck(this, BottleneckError);
1428
1429 return _possibleConstructorReturn(this, _getPrototypeOf(BottleneckError).apply(this, arguments));
1430 }
1431
1432 return BottleneckError;
1433 }(_wrapNativeSuper(Error));
1434
1435 var BottleneckError_1 = BottleneckError;
1436
1437 var BottleneckError$1, LocalDatastore, parser$1;
1438 parser$1 = parser;
1439 BottleneckError$1 = BottleneckError_1;
1440
1441 LocalDatastore =
1442 /*#__PURE__*/
1443 function () {
1444 function LocalDatastore(instance, storeOptions, storeInstanceOptions) {
1445 _classCallCheck(this, LocalDatastore);
1446
1447 this.instance = instance;
1448 this.storeOptions = storeOptions;
1449 this.clientId = this.instance._randomIndex();
1450 parser$1.load(storeInstanceOptions, storeInstanceOptions, this);
1451 this._nextRequest = this._lastReservoirRefresh = Date.now();
1452 this._running = 0;
1453 this._done = 0;
1454 this._unblockTime = 0;
1455 this.ready = this.Promise.resolve();
1456 this.clients = {};
1457
1458 this._startHeartbeat();
1459 }
1460
1461 _createClass(LocalDatastore, [{
1462 key: "_startHeartbeat",
1463 value: function _startHeartbeat() {
1464 var _this = this;
1465
1466 var base;
1467
1468 if (this.heartbeat == null && this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null) {
1469 return typeof (base = this.heartbeat = setInterval(function () {
1470 var now;
1471 now = Date.now();
1472
1473 if (now >= _this._lastReservoirRefresh + _this.storeOptions.reservoirRefreshInterval) {
1474 _this.storeOptions.reservoir = _this.storeOptions.reservoirRefreshAmount;
1475 _this._lastReservoirRefresh = now;
1476 return _this.instance._drainAll(_this.computeCapacity());
1477 }
1478 }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0;
1479 } else {
1480 return clearInterval(this.heartbeat);
1481 }
1482 }
1483 }, {
1484 key: "__publish__",
1485 value: function () {
1486 var _publish__ = _asyncToGenerator(
1487 /*#__PURE__*/
1488 regeneratorRuntime.mark(function _callee(message) {
1489 return regeneratorRuntime.wrap(function _callee$(_context) {
1490 while (1) {
1491 switch (_context.prev = _context.next) {
1492 case 0:
1493 _context.next = 2;
1494 return this.yieldLoop();
1495
1496 case 2:
1497 return _context.abrupt("return", this.instance.Events.trigger("message", message.toString()));
1498
1499 case 3:
1500 case "end":
1501 return _context.stop();
1502 }
1503 }
1504 }, _callee, this);
1505 }));
1506
1507 return function __publish__(_x) {
1508 return _publish__.apply(this, arguments);
1509 };
1510 }()
1511 }, {
1512 key: "__disconnect__",
1513 value: function () {
1514 var _disconnect__ = _asyncToGenerator(
1515 /*#__PURE__*/
1516 regeneratorRuntime.mark(function _callee2(flush) {
1517 return regeneratorRuntime.wrap(function _callee2$(_context2) {
1518 while (1) {
1519 switch (_context2.prev = _context2.next) {
1520 case 0:
1521 _context2.next = 2;
1522 return this.yieldLoop();
1523
1524 case 2:
1525 clearInterval(this.heartbeat);
1526 return _context2.abrupt("return", this.Promise.resolve());
1527
1528 case 4:
1529 case "end":
1530 return _context2.stop();
1531 }
1532 }
1533 }, _callee2, this);
1534 }));
1535
1536 return function __disconnect__(_x2) {
1537 return _disconnect__.apply(this, arguments);
1538 };
1539 }()
1540 }, {
1541 key: "yieldLoop",
1542 value: function yieldLoop() {
1543 var t = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
1544 return new this.Promise(function (resolve, reject) {
1545 return setTimeout(resolve, t);
1546 });
1547 }
1548 }, {
1549 key: "computePenalty",
1550 value: function computePenalty() {
1551 var ref;
1552 return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000;
1553 }
1554 }, {
1555 key: "__updateSettings__",
1556 value: function () {
1557 var _updateSettings__ = _asyncToGenerator(
1558 /*#__PURE__*/
1559 regeneratorRuntime.mark(function _callee3(options) {
1560 return regeneratorRuntime.wrap(function _callee3$(_context3) {
1561 while (1) {
1562 switch (_context3.prev = _context3.next) {
1563 case 0:
1564 _context3.next = 2;
1565 return this.yieldLoop();
1566
1567 case 2:
1568 parser$1.overwrite(options, options, this.storeOptions);
1569
1570 this._startHeartbeat();
1571
1572 this.instance._drainAll(this.computeCapacity());
1573
1574 return _context3.abrupt("return", true);
1575
1576 case 6:
1577 case "end":
1578 return _context3.stop();
1579 }
1580 }
1581 }, _callee3, this);
1582 }));
1583
1584 return function __updateSettings__(_x3) {
1585 return _updateSettings__.apply(this, arguments);
1586 };
1587 }()
1588 }, {
1589 key: "__running__",
1590 value: function () {
1591 var _running__ = _asyncToGenerator(
1592 /*#__PURE__*/
1593 regeneratorRuntime.mark(function _callee4() {
1594 return regeneratorRuntime.wrap(function _callee4$(_context4) {
1595 while (1) {
1596 switch (_context4.prev = _context4.next) {
1597 case 0:
1598 _context4.next = 2;
1599 return this.yieldLoop();
1600
1601 case 2:
1602 return _context4.abrupt("return", this._running);
1603
1604 case 3:
1605 case "end":
1606 return _context4.stop();
1607 }
1608 }
1609 }, _callee4, this);
1610 }));
1611
1612 return function __running__() {
1613 return _running__.apply(this, arguments);
1614 };
1615 }()
1616 }, {
1617 key: "__queued__",
1618 value: function () {
1619 var _queued__ = _asyncToGenerator(
1620 /*#__PURE__*/
1621 regeneratorRuntime.mark(function _callee5() {
1622 return regeneratorRuntime.wrap(function _callee5$(_context5) {
1623 while (1) {
1624 switch (_context5.prev = _context5.next) {
1625 case 0:
1626 _context5.next = 2;
1627 return this.yieldLoop();
1628
1629 case 2:
1630 return _context5.abrupt("return", this.instance.queued());
1631
1632 case 3:
1633 case "end":
1634 return _context5.stop();
1635 }
1636 }
1637 }, _callee5, this);
1638 }));
1639
1640 return function __queued__() {
1641 return _queued__.apply(this, arguments);
1642 };
1643 }()
1644 }, {
1645 key: "__done__",
1646 value: function () {
1647 var _done__ = _asyncToGenerator(
1648 /*#__PURE__*/
1649 regeneratorRuntime.mark(function _callee6() {
1650 return regeneratorRuntime.wrap(function _callee6$(_context6) {
1651 while (1) {
1652 switch (_context6.prev = _context6.next) {
1653 case 0:
1654 _context6.next = 2;
1655 return this.yieldLoop();
1656
1657 case 2:
1658 return _context6.abrupt("return", this._done);
1659
1660 case 3:
1661 case "end":
1662 return _context6.stop();
1663 }
1664 }
1665 }, _callee6, this);
1666 }));
1667
1668 return function __done__() {
1669 return _done__.apply(this, arguments);
1670 };
1671 }()
1672 }, {
1673 key: "__groupCheck__",
1674 value: function () {
1675 var _groupCheck__ = _asyncToGenerator(
1676 /*#__PURE__*/
1677 regeneratorRuntime.mark(function _callee7(time) {
1678 return regeneratorRuntime.wrap(function _callee7$(_context7) {
1679 while (1) {
1680 switch (_context7.prev = _context7.next) {
1681 case 0:
1682 _context7.next = 2;
1683 return this.yieldLoop();
1684
1685 case 2:
1686 return _context7.abrupt("return", this._nextRequest + this.timeout < time);
1687
1688 case 3:
1689 case "end":
1690 return _context7.stop();
1691 }
1692 }
1693 }, _callee7, this);
1694 }));
1695
1696 return function __groupCheck__(_x4) {
1697 return _groupCheck__.apply(this, arguments);
1698 };
1699 }()
1700 }, {
1701 key: "computeCapacity",
1702 value: function computeCapacity() {
1703 var maxConcurrent, reservoir;
1704 var _this$storeOptions = this.storeOptions;
1705 maxConcurrent = _this$storeOptions.maxConcurrent;
1706 reservoir = _this$storeOptions.reservoir;
1707
1708 if (maxConcurrent != null && reservoir != null) {
1709 return Math.min(maxConcurrent - this._running, reservoir);
1710 } else if (maxConcurrent != null) {
1711 return maxConcurrent - this._running;
1712 } else if (reservoir != null) {
1713 return reservoir;
1714 } else {
1715 return null;
1716 }
1717 }
1718 }, {
1719 key: "conditionsCheck",
1720 value: function conditionsCheck(weight) {
1721 var capacity;
1722 capacity = this.computeCapacity();
1723 return capacity == null || weight <= capacity;
1724 }
1725 }, {
1726 key: "__incrementReservoir__",
1727 value: function () {
1728 var _incrementReservoir__ = _asyncToGenerator(
1729 /*#__PURE__*/
1730 regeneratorRuntime.mark(function _callee8(incr) {
1731 var reservoir;
1732 return regeneratorRuntime.wrap(function _callee8$(_context8) {
1733 while (1) {
1734 switch (_context8.prev = _context8.next) {
1735 case 0:
1736 _context8.next = 2;
1737 return this.yieldLoop();
1738
1739 case 2:
1740 reservoir = this.storeOptions.reservoir += incr;
1741
1742 this.instance._drainAll(this.computeCapacity());
1743
1744 return _context8.abrupt("return", reservoir);
1745
1746 case 5:
1747 case "end":
1748 return _context8.stop();
1749 }
1750 }
1751 }, _callee8, this);
1752 }));
1753
1754 return function __incrementReservoir__(_x5) {
1755 return _incrementReservoir__.apply(this, arguments);
1756 };
1757 }()
1758 }, {
1759 key: "__currentReservoir__",
1760 value: function () {
1761 var _currentReservoir__ = _asyncToGenerator(
1762 /*#__PURE__*/
1763 regeneratorRuntime.mark(function _callee9() {
1764 return regeneratorRuntime.wrap(function _callee9$(_context9) {
1765 while (1) {
1766 switch (_context9.prev = _context9.next) {
1767 case 0:
1768 _context9.next = 2;
1769 return this.yieldLoop();
1770
1771 case 2:
1772 return _context9.abrupt("return", this.storeOptions.reservoir);
1773
1774 case 3:
1775 case "end":
1776 return _context9.stop();
1777 }
1778 }
1779 }, _callee9, this);
1780 }));
1781
1782 return function __currentReservoir__() {
1783 return _currentReservoir__.apply(this, arguments);
1784 };
1785 }()
1786 }, {
1787 key: "isBlocked",
1788 value: function isBlocked(now) {
1789 return this._unblockTime >= now;
1790 }
1791 }, {
1792 key: "check",
1793 value: function check(weight, now) {
1794 return this.conditionsCheck(weight) && this._nextRequest - now <= 0;
1795 }
1796 }, {
1797 key: "__check__",
1798 value: function () {
1799 var _check__ = _asyncToGenerator(
1800 /*#__PURE__*/
1801 regeneratorRuntime.mark(function _callee10(weight) {
1802 var now;
1803 return regeneratorRuntime.wrap(function _callee10$(_context10) {
1804 while (1) {
1805 switch (_context10.prev = _context10.next) {
1806 case 0:
1807 _context10.next = 2;
1808 return this.yieldLoop();
1809
1810 case 2:
1811 now = Date.now();
1812 return _context10.abrupt("return", this.check(weight, now));
1813
1814 case 4:
1815 case "end":
1816 return _context10.stop();
1817 }
1818 }
1819 }, _callee10, this);
1820 }));
1821
1822 return function __check__(_x6) {
1823 return _check__.apply(this, arguments);
1824 };
1825 }()
1826 }, {
1827 key: "__register__",
1828 value: function () {
1829 var _register__ = _asyncToGenerator(
1830 /*#__PURE__*/
1831 regeneratorRuntime.mark(function _callee11(index, weight, expiration) {
1832 var now, wait;
1833 return regeneratorRuntime.wrap(function _callee11$(_context11) {
1834 while (1) {
1835 switch (_context11.prev = _context11.next) {
1836 case 0:
1837 _context11.next = 2;
1838 return this.yieldLoop();
1839
1840 case 2:
1841 now = Date.now();
1842
1843 if (!this.conditionsCheck(weight)) {
1844 _context11.next = 11;
1845 break;
1846 }
1847
1848 this._running += weight;
1849
1850 if (this.storeOptions.reservoir != null) {
1851 this.storeOptions.reservoir -= weight;
1852 }
1853
1854 wait = Math.max(this._nextRequest - now, 0);
1855 this._nextRequest = now + wait + this.storeOptions.minTime;
1856 return _context11.abrupt("return", {
1857 success: true,
1858 wait: wait,
1859 reservoir: this.storeOptions.reservoir
1860 });
1861
1862 case 11:
1863 return _context11.abrupt("return", {
1864 success: false
1865 });
1866
1867 case 12:
1868 case "end":
1869 return _context11.stop();
1870 }
1871 }
1872 }, _callee11, this);
1873 }));
1874
1875 return function __register__(_x7, _x8, _x9) {
1876 return _register__.apply(this, arguments);
1877 };
1878 }()
1879 }, {
1880 key: "strategyIsBlock",
1881 value: function strategyIsBlock() {
1882 return this.storeOptions.strategy === 3;
1883 }
1884 }, {
1885 key: "__submit__",
1886 value: function () {
1887 var _submit__ = _asyncToGenerator(
1888 /*#__PURE__*/
1889 regeneratorRuntime.mark(function _callee12(queueLength, weight) {
1890 var blocked, now, reachedHWM;
1891 return regeneratorRuntime.wrap(function _callee12$(_context12) {
1892 while (1) {
1893 switch (_context12.prev = _context12.next) {
1894 case 0:
1895 _context12.next = 2;
1896 return this.yieldLoop();
1897
1898 case 2:
1899 if (!(this.storeOptions.maxConcurrent != null && weight > this.storeOptions.maxConcurrent)) {
1900 _context12.next = 4;
1901 break;
1902 }
1903
1904 throw new BottleneckError$1("Impossible to add a job having a weight of ".concat(weight, " to a limiter having a maxConcurrent setting of ").concat(this.storeOptions.maxConcurrent));
1905
1906 case 4:
1907 now = Date.now();
1908 reachedHWM = this.storeOptions.highWater != null && queueLength === this.storeOptions.highWater && !this.check(weight, now);
1909 blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now));
1910
1911 if (blocked) {
1912 this._unblockTime = now + this.computePenalty();
1913 this._nextRequest = this._unblockTime + this.storeOptions.minTime;
1914
1915 this.instance._dropAllQueued();
1916 }
1917
1918 return _context12.abrupt("return", {
1919 reachedHWM: reachedHWM,
1920 blocked: blocked,
1921 strategy: this.storeOptions.strategy
1922 });
1923
1924 case 9:
1925 case "end":
1926 return _context12.stop();
1927 }
1928 }
1929 }, _callee12, this);
1930 }));
1931
1932 return function __submit__(_x10, _x11) {
1933 return _submit__.apply(this, arguments);
1934 };
1935 }()
1936 }, {
1937 key: "__free__",
1938 value: function () {
1939 var _free__ = _asyncToGenerator(
1940 /*#__PURE__*/
1941 regeneratorRuntime.mark(function _callee13(index, weight) {
1942 return regeneratorRuntime.wrap(function _callee13$(_context13) {
1943 while (1) {
1944 switch (_context13.prev = _context13.next) {
1945 case 0:
1946 _context13.next = 2;
1947 return this.yieldLoop();
1948
1949 case 2:
1950 this._running -= weight;
1951 this._done += weight;
1952
1953 this.instance._drainAll(this.computeCapacity());
1954
1955 return _context13.abrupt("return", {
1956 running: this._running
1957 });
1958
1959 case 6:
1960 case "end":
1961 return _context13.stop();
1962 }
1963 }
1964 }, _callee13, this);
1965 }));
1966
1967 return function __free__(_x12, _x13) {
1968 return _free__.apply(this, arguments);
1969 };
1970 }()
1971 }]);
1972
1973 return LocalDatastore;
1974 }();
1975
1976 var LocalDatastore_1 = LocalDatastore;
1977
1978 var lua = {
1979 "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",
1980 "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",
1981 "conditions_check.lua": "local conditions_check = function (capacity, weight)\n return capacity == nil or weight <= capacity\nend\n",
1982 "current_reservoir.lua": "return process_tick(now, false)['reservoir']\n",
1983 "done.lua": "process_tick(now, false)\n\nreturn tonumber(redis.call('hget', settings_key, 'done'))\n",
1984 "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",
1985 "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",
1986 "group_check.lua": "return not (redis.call('exists', settings_key) == 1)\n",
1987 "heartbeat.lua": "process_tick(now, true)\n",
1988 "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",
1989 "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 '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 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",
1990 "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 '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 capacityPriorityCounter = tonumber(settings[8])\n local clientTimeout = tonumber(settings[9])\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 --\n -- Clear unresponsive clients\n --\n local unresponsive = redis.call('zrangebyscore', client_last_seen_key, '-inf', (now - clientTimeout))\n if #unresponsive > 0 then\n local terminated_clients = {}\n for i = 1, #unresponsive do\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 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 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",
1991 "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",
1992 "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",
1993 "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",
1994 "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",
1995 "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",
1996 "running.lua": "return process_tick(now, false)['running']\n",
1997 "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",
1998 "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",
1999 "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",
2000 "validate_keys.lua": "if not (redis.call('exists', settings_key) == 1) then\n return redis.error_reply('SETTINGS_KEY_NOT_FOUND')\nend\n"
2001 };
2002
2003 var lua$1 = /*#__PURE__*/Object.freeze({
2004 default: lua
2005 });
2006
2007 var require$$0 = getCjsExportFromNamespace(lua$1);
2008
2009 var Scripts = createCommonjsModule(function (module, exports) {
2010 var headers, lua, templates;
2011 lua = require$$0;
2012 headers = {
2013 refs: lua["refs.lua"],
2014 validate_keys: lua["validate_keys.lua"],
2015 validate_client: lua["validate_client.lua"],
2016 refresh_expiration: lua["refresh_expiration.lua"],
2017 process_tick: lua["process_tick.lua"],
2018 conditions_check: lua["conditions_check.lua"],
2019 get_time: lua["get_time.lua"]
2020 };
2021
2022 exports.allKeys = function (id) {
2023 return [
2024 /*
2025 HASH
2026 */
2027 "b_".concat(id, "_settings"),
2028 /*
2029 HASH
2030 job index -> weight
2031 */
2032 "b_".concat(id, "_job_weights"),
2033 /*
2034 ZSET
2035 job index -> expiration
2036 */
2037 "b_".concat(id, "_job_expirations"),
2038 /*
2039 HASH
2040 job index -> client
2041 */
2042 "b_".concat(id, "_job_clients"),
2043 /*
2044 ZSET
2045 client -> sum running
2046 */
2047 "b_".concat(id, "_client_running"),
2048 /*
2049 HASH
2050 client -> num queued
2051 */
2052 "b_".concat(id, "_client_num_queued"),
2053 /*
2054 ZSET
2055 client -> last job registered
2056 */
2057 "b_".concat(id, "_client_last_registered"),
2058 /*
2059 ZSET
2060 client -> last seen
2061 */
2062 "b_".concat(id, "_client_last_seen")];
2063 };
2064
2065 templates = {
2066 init: {
2067 keys: exports.allKeys,
2068 headers: ["process_tick"],
2069 refresh_expiration: true,
2070 code: lua["init.lua"]
2071 },
2072 group_check: {
2073 keys: exports.allKeys,
2074 headers: [],
2075 refresh_expiration: false,
2076 code: lua["group_check.lua"]
2077 },
2078 register_client: {
2079 keys: exports.allKeys,
2080 headers: ["validate_keys"],
2081 refresh_expiration: false,
2082 code: lua["register_client.lua"]
2083 },
2084 blacklist_client: {
2085 keys: exports.allKeys,
2086 headers: ["validate_keys", "validate_client"],
2087 refresh_expiration: false,
2088 code: lua["blacklist_client.lua"]
2089 },
2090 heartbeat: {
2091 keys: exports.allKeys,
2092 headers: ["validate_keys", "validate_client", "process_tick"],
2093 refresh_expiration: false,
2094 code: lua["heartbeat.lua"]
2095 },
2096 update_settings: {
2097 keys: exports.allKeys,
2098 headers: ["validate_keys", "validate_client", "process_tick"],
2099 refresh_expiration: true,
2100 code: lua["update_settings.lua"]
2101 },
2102 running: {
2103 keys: exports.allKeys,
2104 headers: ["validate_keys", "validate_client", "process_tick"],
2105 refresh_expiration: false,
2106 code: lua["running.lua"]
2107 },
2108 queued: {
2109 keys: exports.allKeys,
2110 headers: ["validate_keys", "validate_client"],
2111 refresh_expiration: false,
2112 code: lua["queued.lua"]
2113 },
2114 done: {
2115 keys: exports.allKeys,
2116 headers: ["validate_keys", "validate_client", "process_tick"],
2117 refresh_expiration: false,
2118 code: lua["done.lua"]
2119 },
2120 check: {
2121 keys: exports.allKeys,
2122 headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"],
2123 refresh_expiration: false,
2124 code: lua["check.lua"]
2125 },
2126 submit: {
2127 keys: exports.allKeys,
2128 headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"],
2129 refresh_expiration: true,
2130 code: lua["submit.lua"]
2131 },
2132 register: {
2133 keys: exports.allKeys,
2134 headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"],
2135 refresh_expiration: true,
2136 code: lua["register.lua"]
2137 },
2138 free: {
2139 keys: exports.allKeys,
2140 headers: ["validate_keys", "validate_client", "process_tick"],
2141 refresh_expiration: true,
2142 code: lua["free.lua"]
2143 },
2144 current_reservoir: {
2145 keys: exports.allKeys,
2146 headers: ["validate_keys", "validate_client", "process_tick"],
2147 refresh_expiration: false,
2148 code: lua["current_reservoir.lua"]
2149 },
2150 increment_reservoir: {
2151 keys: exports.allKeys,
2152 headers: ["validate_keys", "validate_client", "process_tick"],
2153 refresh_expiration: true,
2154 code: lua["increment_reservoir.lua"]
2155 }
2156 };
2157 exports.names = Object.keys(templates);
2158
2159 exports.keys = function (name, id) {
2160 return templates[name].keys(id);
2161 };
2162
2163 exports.payload = function (name) {
2164 var template;
2165 template = templates[name];
2166 return Array.prototype.concat(headers.refs, template.headers.map(function (h) {
2167 return headers[h];
2168 }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join("\n");
2169 };
2170 });
2171 var Scripts_1 = Scripts.allKeys;
2172 var Scripts_2 = Scripts.names;
2173 var Scripts_3 = Scripts.keys;
2174 var Scripts_4 = Scripts.payload;
2175
2176 var Events$2, RedisConnection, Scripts$1, parser$2;
2177 parser$2 = parser;
2178 Events$2 = Events_1;
2179 Scripts$1 = Scripts;
2180
2181 RedisConnection = function () {
2182 var RedisConnection =
2183 /*#__PURE__*/
2184 function () {
2185 function RedisConnection() {
2186 var _this = this;
2187
2188 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2189
2190 _classCallCheck(this, RedisConnection);
2191
2192 var Redis;
2193 Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module
2194
2195 parser$2.load(options, this.defaults, this);
2196
2197 if (this.Events == null) {
2198 this.Events = new Events$2(this);
2199 }
2200
2201 this.terminated = false;
2202
2203 if (this.client == null) {
2204 this.client = Redis.createClient(this.clientOptions);
2205 }
2206
2207 this.subscriber = this.client.duplicate();
2208 this.limiters = {};
2209 this.shas = {};
2210 this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(function () {
2211 return _this._loadScripts();
2212 }).then(function () {
2213 return {
2214 client: _this.client,
2215 subscriber: _this.subscriber
2216 };
2217 });
2218 }
2219
2220 _createClass(RedisConnection, [{
2221 key: "_setup",
2222 value: function _setup(client, sub) {
2223 var _this2 = this;
2224
2225 client.setMaxListeners(0);
2226 return new this.Promise(function (resolve, reject) {
2227 client.on("error", function (e) {
2228 return _this2.Events.trigger("error", e);
2229 });
2230
2231 if (sub) {
2232 client.on("message", function (channel, message) {
2233 var ref;
2234 return (ref = _this2.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
2235 });
2236 }
2237
2238 if (client.ready) {
2239 return resolve();
2240 } else {
2241 return client.once("ready", resolve);
2242 }
2243 });
2244 }
2245 }, {
2246 key: "_loadScript",
2247 value: function _loadScript(name) {
2248 var _this3 = this;
2249
2250 return new this.Promise(function (resolve, reject) {
2251 var payload;
2252 payload = Scripts$1.payload(name);
2253 return _this3.client.multi([["script", "load", payload]]).exec(function (err, replies) {
2254 if (err != null) {
2255 return reject(err);
2256 }
2257
2258 _this3.shas[name] = replies[0];
2259 return resolve(replies[0]);
2260 });
2261 });
2262 }
2263 }, {
2264 key: "_loadScripts",
2265 value: function _loadScripts() {
2266 var _this4 = this;
2267
2268 return this.Promise.all(Scripts$1.names.map(function (k) {
2269 return _this4._loadScript(k);
2270 }));
2271 }
2272 }, {
2273 key: "__runCommand__",
2274 value: function () {
2275 var _runCommand__ = _asyncToGenerator(
2276 /*#__PURE__*/
2277 regeneratorRuntime.mark(function _callee(cmd) {
2278 var _this5 = this;
2279
2280 return regeneratorRuntime.wrap(function _callee$(_context) {
2281 while (1) {
2282 switch (_context.prev = _context.next) {
2283 case 0:
2284 _context.next = 2;
2285 return this.ready;
2286
2287 case 2:
2288 return _context.abrupt("return", new this.Promise(function (resolve, reject) {
2289 return _this5.client.multi([cmd]).exec_atomic(function (err, replies) {
2290 if (err != null) {
2291 return reject(err);
2292 } else {
2293 return resolve(replies[0]);
2294 }
2295 });
2296 }));
2297
2298 case 3:
2299 case "end":
2300 return _context.stop();
2301 }
2302 }
2303 }, _callee, this);
2304 }));
2305
2306 return function __runCommand__(_x) {
2307 return _runCommand__.apply(this, arguments);
2308 };
2309 }()
2310 }, {
2311 key: "__addLimiter__",
2312 value: function __addLimiter__(instance) {
2313 var _this6 = this;
2314
2315 return this.Promise.all([instance.channel(), instance.channel_client()].map(function (channel) {
2316 return new _this6.Promise(function (resolve, reject) {
2317 var _handler;
2318
2319 _handler = function handler(chan) {
2320 if (chan === channel) {
2321 _this6.subscriber.removeListener("subscribe", _handler);
2322
2323 _this6.limiters[channel] = instance;
2324 return resolve();
2325 }
2326 };
2327
2328 _this6.subscriber.on("subscribe", _handler);
2329
2330 return _this6.subscriber.subscribe(channel);
2331 });
2332 }));
2333 }
2334 }, {
2335 key: "__removeLimiter__",
2336 value: function __removeLimiter__(instance) {
2337 var _this7 = this;
2338
2339 return this.Promise.all([instance.channel(), instance.channel_client()].map(
2340 /*#__PURE__*/
2341 function () {
2342 var _ref = _asyncToGenerator(
2343 /*#__PURE__*/
2344 regeneratorRuntime.mark(function _callee2(channel) {
2345 return regeneratorRuntime.wrap(function _callee2$(_context2) {
2346 while (1) {
2347 switch (_context2.prev = _context2.next) {
2348 case 0:
2349 if (_this7.terminated) {
2350 _context2.next = 3;
2351 break;
2352 }
2353
2354 _context2.next = 3;
2355 return new _this7.Promise(function (resolve, reject) {
2356 return _this7.subscriber.unsubscribe(channel, function (err, chan) {
2357 if (err != null) {
2358 return reject(err);
2359 }
2360
2361 if (chan === channel) {
2362 return resolve();
2363 }
2364 });
2365 });
2366
2367 case 3:
2368 return _context2.abrupt("return", delete _this7.limiters[channel]);
2369
2370 case 4:
2371 case "end":
2372 return _context2.stop();
2373 }
2374 }
2375 }, _callee2, this);
2376 }));
2377
2378 return function (_x2) {
2379 return _ref.apply(this, arguments);
2380 };
2381 }()));
2382 }
2383 }, {
2384 key: "__scriptArgs__",
2385 value: function __scriptArgs__(name, id, args, cb) {
2386 var keys;
2387 keys = Scripts$1.keys(name, id);
2388 return [this.shas[name], keys.length].concat(keys, args, cb);
2389 }
2390 }, {
2391 key: "__scriptFn__",
2392 value: function __scriptFn__(name) {
2393 return this.client.evalsha.bind(this.client);
2394 }
2395 }, {
2396 key: "disconnect",
2397 value: function disconnect() {
2398 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
2399 var i, k, len, ref;
2400 ref = Object.keys(this.limiters);
2401
2402 for (i = 0, len = ref.length; i < len; i++) {
2403 k = ref[i];
2404 clearInterval(this.limiters[k]._store.heartbeat);
2405 }
2406
2407 this.limiters = {};
2408 this.terminated = true;
2409 this.client.end(flush);
2410 this.subscriber.end(flush);
2411 return this.Promise.resolve();
2412 }
2413 }]);
2414
2415 return RedisConnection;
2416 }();
2417 RedisConnection.prototype.datastore = "redis";
2418 RedisConnection.prototype.defaults = {
2419 clientOptions: {},
2420 client: null,
2421 Promise: Promise,
2422 Events: null
2423 };
2424 return RedisConnection;
2425 }.call(commonjsGlobal);
2426
2427 var RedisConnection_1 = RedisConnection;
2428
2429 var Events$3, IORedisConnection, Scripts$2, parser$3;
2430 parser$3 = parser;
2431 Events$3 = Events_1;
2432 Scripts$2 = Scripts;
2433
2434 IORedisConnection = function () {
2435 var IORedisConnection =
2436 /*#__PURE__*/
2437 function () {
2438 function IORedisConnection() {
2439 var _this = this;
2440
2441 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2442
2443 _classCallCheck(this, IORedisConnection);
2444
2445 var Redis;
2446 Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module
2447
2448 parser$3.load(options, this.defaults, this);
2449
2450 if (this.Events == null) {
2451 this.Events = new Events$3(this);
2452 }
2453
2454 this.terminated = false;
2455
2456 if (this.clusterNodes != null) {
2457 this.client = new Redis.Cluster(this.clusterNodes, this.clientOptions);
2458 this.subscriber = new Redis.Cluster(this.clusterNodes, this.clientOptions);
2459 } else {
2460 if (this.client == null) {
2461 this.client = new Redis(this.clientOptions);
2462 }
2463
2464 this.subscriber = this.client.duplicate();
2465 }
2466
2467 this.limiters = {};
2468 this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(function () {
2469 _this._loadScripts();
2470
2471 return {
2472 client: _this.client,
2473 subscriber: _this.subscriber
2474 };
2475 });
2476 }
2477
2478 _createClass(IORedisConnection, [{
2479 key: "_setup",
2480 value: function _setup(client, sub) {
2481 var _this2 = this;
2482
2483 client.setMaxListeners(0);
2484 return new this.Promise(function (resolve, reject) {
2485 client.on("error", function (e) {
2486 return _this2.Events.trigger("error", e);
2487 });
2488
2489 if (sub) {
2490 client.on("message", function (channel, message) {
2491 var ref;
2492 return (ref = _this2.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
2493 });
2494 }
2495
2496 if (client.status === "ready") {
2497 return resolve();
2498 } else {
2499 return client.once("ready", resolve);
2500 }
2501 });
2502 }
2503 }, {
2504 key: "_loadScripts",
2505 value: function _loadScripts() {
2506 var _this3 = this;
2507
2508 return Scripts$2.names.forEach(function (name) {
2509 return _this3.client.defineCommand(name, {
2510 lua: Scripts$2.payload(name)
2511 });
2512 });
2513 }
2514 }, {
2515 key: "__runCommand__",
2516 value: function () {
2517 var _runCommand__ = _asyncToGenerator(
2518 /*#__PURE__*/
2519 regeneratorRuntime.mark(function _callee(cmd) {
2520 var _, deleted, _ref, _ref2, _ref2$;
2521
2522 return regeneratorRuntime.wrap(function _callee$(_context) {
2523 while (1) {
2524 switch (_context.prev = _context.next) {
2525 case 0:
2526 _context.next = 2;
2527 return this.ready;
2528
2529 case 2:
2530 _context.next = 4;
2531 return this.client.pipeline([cmd]).exec();
2532
2533 case 4:
2534 _ref = _context.sent;
2535 _ref2 = _slicedToArray(_ref, 1);
2536 _ref2$ = _slicedToArray(_ref2[0], 2);
2537 _ = _ref2$[0];
2538 deleted = _ref2$[1];
2539 return _context.abrupt("return", deleted);
2540
2541 case 10:
2542 case "end":
2543 return _context.stop();
2544 }
2545 }
2546 }, _callee, this);
2547 }));
2548
2549 return function __runCommand__(_x) {
2550 return _runCommand__.apply(this, arguments);
2551 };
2552 }()
2553 }, {
2554 key: "__addLimiter__",
2555 value: function __addLimiter__(instance) {
2556 var _this4 = this;
2557
2558 return this.Promise.all([instance.channel(), instance.channel_client()].map(function (channel) {
2559 return new _this4.Promise(function (resolve, reject) {
2560 return _this4.subscriber.subscribe(channel, function () {
2561 _this4.limiters[channel] = instance;
2562 return resolve();
2563 });
2564 });
2565 }));
2566 }
2567 }, {
2568 key: "__removeLimiter__",
2569 value: function __removeLimiter__(instance) {
2570 var _this5 = this;
2571
2572 return [instance.channel(), instance.channel_client()].forEach(
2573 /*#__PURE__*/
2574 function () {
2575 var _ref3 = _asyncToGenerator(
2576 /*#__PURE__*/
2577 regeneratorRuntime.mark(function _callee2(channel) {
2578 return regeneratorRuntime.wrap(function _callee2$(_context2) {
2579 while (1) {
2580 switch (_context2.prev = _context2.next) {
2581 case 0:
2582 if (_this5.terminated) {
2583 _context2.next = 3;
2584 break;
2585 }
2586
2587 _context2.next = 3;
2588 return _this5.subscriber.unsubscribe(channel);
2589
2590 case 3:
2591 return _context2.abrupt("return", delete _this5.limiters[channel]);
2592
2593 case 4:
2594 case "end":
2595 return _context2.stop();
2596 }
2597 }
2598 }, _callee2, this);
2599 }));
2600
2601 return function (_x2) {
2602 return _ref3.apply(this, arguments);
2603 };
2604 }());
2605 }
2606 }, {
2607 key: "__scriptArgs__",
2608 value: function __scriptArgs__(name, id, args, cb) {
2609 var keys;
2610 keys = Scripts$2.keys(name, id);
2611 return [keys.length].concat(keys, args, cb);
2612 }
2613 }, {
2614 key: "__scriptFn__",
2615 value: function __scriptFn__(name) {
2616 return this.client[name].bind(this.client);
2617 }
2618 }, {
2619 key: "disconnect",
2620 value: function disconnect() {
2621 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
2622 var i, k, len, ref;
2623 ref = Object.keys(this.limiters);
2624
2625 for (i = 0, len = ref.length; i < len; i++) {
2626 k = ref[i];
2627 clearInterval(this.limiters[k]._store.heartbeat);
2628 }
2629
2630 this.limiters = {};
2631 this.terminated = true;
2632
2633 if (flush) {
2634 return this.Promise.all([this.client.quit(), this.subscriber.quit()]);
2635 } else {
2636 this.client.disconnect();
2637 this.subscriber.disconnect();
2638 return this.Promise.resolve();
2639 }
2640 }
2641 }]);
2642
2643 return IORedisConnection;
2644 }();
2645 IORedisConnection.prototype.datastore = "ioredis";
2646 IORedisConnection.prototype.defaults = {
2647 clientOptions: {},
2648 clusterNodes: null,
2649 client: null,
2650 Promise: Promise,
2651 Events: null
2652 };
2653 return IORedisConnection;
2654 }.call(commonjsGlobal);
2655
2656 var IORedisConnection_1 = IORedisConnection;
2657
2658 var BottleneckError$2, IORedisConnection$1, RedisConnection$1, RedisDatastore, parser$4;
2659 parser$4 = parser;
2660 BottleneckError$2 = BottleneckError_1;
2661 RedisConnection$1 = RedisConnection_1;
2662 IORedisConnection$1 = IORedisConnection_1;
2663
2664 RedisDatastore =
2665 /*#__PURE__*/
2666 function () {
2667 function RedisDatastore(instance, storeOptions, storeInstanceOptions) {
2668 var _this = this;
2669
2670 _classCallCheck(this, RedisDatastore);
2671
2672 this.instance = instance;
2673 this.storeOptions = storeOptions;
2674 this.originalId = this.instance.id;
2675 this.clientId = this.instance._randomIndex();
2676 parser$4.load(storeInstanceOptions, storeInstanceOptions, this);
2677 this.clients = {};
2678 this.capacityPriorityCounters = {};
2679 this.sharedConnection = this.connection != null;
2680
2681 if (this.connection == null) {
2682 this.connection = this.instance.datastore === "redis" ? new RedisConnection$1({
2683 clientOptions: this.clientOptions,
2684 Promise: this.Promise,
2685 Events: this.instance.Events
2686 }) : this.instance.datastore === "ioredis" ? new IORedisConnection$1({
2687 clientOptions: this.clientOptions,
2688 clusterNodes: this.clusterNodes,
2689 Promise: this.Promise,
2690 Events: this.instance.Events
2691 }) : void 0;
2692 }
2693
2694 this.instance.connection = this.connection;
2695 this.instance.datastore = this.connection.datastore;
2696 this.ready = this.connection.ready.then(function (clients) {
2697 _this.clients = clients;
2698 return _this.runScript("init", _this.prepareInitSettings(_this.clearDatastore));
2699 }).then(function () {
2700 return _this.connection.__addLimiter__(_this.instance);
2701 }).then(function () {
2702 return _this.runScript("register_client", [_this.instance.queued()]);
2703 }).then(function () {
2704 var base;
2705
2706 if (typeof (base = _this.heartbeat = setInterval(function () {
2707 return _this.runScript("heartbeat", []).catch(function (e) {
2708 return _this.instance.Events.trigger("error", e);
2709 });
2710 }, _this.heartbeatInterval)).unref === "function") {
2711 base.unref();
2712 }
2713
2714 return _this.clients;
2715 });
2716 }
2717
2718 _createClass(RedisDatastore, [{
2719 key: "__publish__",
2720 value: function () {
2721 var _publish__ = _asyncToGenerator(
2722 /*#__PURE__*/
2723 regeneratorRuntime.mark(function _callee(message) {
2724 var client, _ref;
2725
2726 return regeneratorRuntime.wrap(function _callee$(_context) {
2727 while (1) {
2728 switch (_context.prev = _context.next) {
2729 case 0:
2730 _context.next = 2;
2731 return this.ready;
2732
2733 case 2:
2734 _ref = _context.sent;
2735 client = _ref.client;
2736 return _context.abrupt("return", client.publish(this.instance.channel(), "message:".concat(message.toString())));
2737
2738 case 5:
2739 case "end":
2740 return _context.stop();
2741 }
2742 }
2743 }, _callee, this);
2744 }));
2745
2746 return function __publish__(_x) {
2747 return _publish__.apply(this, arguments);
2748 };
2749 }()
2750 }, {
2751 key: "onMessage",
2752 value: function () {
2753 var _onMessage = _asyncToGenerator(
2754 /*#__PURE__*/
2755 regeneratorRuntime.mark(function _callee3(channel, message) {
2756 var _this2 = this;
2757
2758 var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type, _ref2, _data$split, _data$split2;
2759
2760 return regeneratorRuntime.wrap(function _callee3$(_context3) {
2761 while (1) {
2762 switch (_context3.prev = _context3.next) {
2763 case 0:
2764 _context3.prev = 0;
2765 pos = message.indexOf(":");
2766 _ref2 = [message.slice(0, pos), message.slice(pos + 1)];
2767 type = _ref2[0];
2768 data = _ref2[1];
2769
2770 if (!(type === "capacity")) {
2771 _context3.next = 11;
2772 break;
2773 }
2774
2775 _context3.next = 8;
2776 return this.instance._drainAll(data.length > 0 ? ~~data : void 0);
2777
2778 case 8:
2779 return _context3.abrupt("return", _context3.sent);
2780
2781 case 11:
2782 if (!(type === "capacity-priority")) {
2783 _context3.next = 37;
2784 break;
2785 }
2786
2787 _data$split = data.split(":");
2788 _data$split2 = _slicedToArray(_data$split, 3);
2789 rawCapacity = _data$split2[0];
2790 priorityClient = _data$split2[1];
2791 counter = _data$split2[2];
2792 capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0;
2793
2794 if (!(priorityClient === this.clientId)) {
2795 _context3.next = 28;
2796 break;
2797 }
2798
2799 _context3.next = 21;
2800 return this.instance._drainAll(capacity);
2801
2802 case 21:
2803 drained = _context3.sent;
2804 newCapacity = capacity != null ? capacity - (drained || 0) : "";
2805 _context3.next = 25;
2806 return this.clients.client.publish(this.instance.channel(), "capacity-priority:".concat(newCapacity, "::").concat(counter));
2807
2808 case 25:
2809 return _context3.abrupt("return", _context3.sent);
2810
2811 case 28:
2812 if (!(priorityClient === "")) {
2813 _context3.next = 34;
2814 break;
2815 }
2816
2817 clearTimeout(this.capacityPriorityCounters[counter]);
2818 delete this.capacityPriorityCounters[counter];
2819 return _context3.abrupt("return", this.instance._drainAll(capacity));
2820
2821 case 34:
2822 return _context3.abrupt("return", this.capacityPriorityCounters[counter] = setTimeout(
2823 /*#__PURE__*/
2824 _asyncToGenerator(
2825 /*#__PURE__*/
2826 regeneratorRuntime.mark(function _callee2() {
2827 var e;
2828 return regeneratorRuntime.wrap(function _callee2$(_context2) {
2829 while (1) {
2830 switch (_context2.prev = _context2.next) {
2831 case 0:
2832 _context2.prev = 0;
2833 delete _this2.capacityPriorityCounters[counter];
2834 _context2.next = 4;
2835 return _this2.runScript("blacklist_client", [priorityClient]);
2836
2837 case 4:
2838 _context2.next = 6;
2839 return _this2.instance._drainAll(capacity);
2840
2841 case 6:
2842 return _context2.abrupt("return", _context2.sent);
2843
2844 case 9:
2845 _context2.prev = 9;
2846 _context2.t0 = _context2["catch"](0);
2847 e = _context2.t0;
2848 return _context2.abrupt("return", _this2.instance.Events.trigger("error", e));
2849
2850 case 13:
2851 case "end":
2852 return _context2.stop();
2853 }
2854 }
2855 }, _callee2, this, [[0, 9]]);
2856 })), 1000));
2857
2858 case 35:
2859 _context3.next = 45;
2860 break;
2861
2862 case 37:
2863 if (!(type === "message")) {
2864 _context3.next = 41;
2865 break;
2866 }
2867
2868 return _context3.abrupt("return", this.instance.Events.trigger("message", data));
2869
2870 case 41:
2871 if (!(type === "blocked")) {
2872 _context3.next = 45;
2873 break;
2874 }
2875
2876 _context3.next = 44;
2877 return this.instance._dropAllQueued();
2878
2879 case 44:
2880 return _context3.abrupt("return", _context3.sent);
2881
2882 case 45:
2883 _context3.next = 51;
2884 break;
2885
2886 case 47:
2887 _context3.prev = 47;
2888 _context3.t0 = _context3["catch"](0);
2889 e = _context3.t0;
2890 return _context3.abrupt("return", this.instance.Events.trigger("error", e));
2891
2892 case 51:
2893 case "end":
2894 return _context3.stop();
2895 }
2896 }
2897 }, _callee3, this, [[0, 47]]);
2898 }));
2899
2900 return function onMessage(_x2, _x3) {
2901 return _onMessage.apply(this, arguments);
2902 };
2903 }()
2904 }, {
2905 key: "__disconnect__",
2906 value: function __disconnect__(flush) {
2907 clearInterval(this.heartbeat);
2908
2909 if (this.sharedConnection) {
2910 return this.connection.__removeLimiter__(this.instance);
2911 } else {
2912 return this.connection.disconnect(flush);
2913 }
2914 }
2915 }, {
2916 key: "runScript",
2917 value: function () {
2918 var _runScript = _asyncToGenerator(
2919 /*#__PURE__*/
2920 regeneratorRuntime.mark(function _callee4(name, args) {
2921 var _this3 = this;
2922
2923 return regeneratorRuntime.wrap(function _callee4$(_context4) {
2924 while (1) {
2925 switch (_context4.prev = _context4.next) {
2926 case 0:
2927 if (name === "init" || name === "register_client") {
2928 _context4.next = 3;
2929 break;
2930 }
2931
2932 _context4.next = 3;
2933 return this.ready;
2934
2935 case 3:
2936 return _context4.abrupt("return", new this.Promise(function (resolve, reject) {
2937 var all_args, arr;
2938 all_args = [Date.now(), _this3.clientId].concat(args);
2939
2940 _this3.instance.Events.trigger("debug", "Calling Redis script: ".concat(name, ".lua"), all_args);
2941
2942 arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) {
2943 if (err != null) {
2944 return reject(err);
2945 }
2946
2947 return resolve(replies);
2948 });
2949 return _this3.connection.__scriptFn__(name).apply(void 0, _toConsumableArray(arr));
2950 }).catch(function (e) {
2951 if (e.message === "SETTINGS_KEY_NOT_FOUND") {
2952 if (name === "heartbeat") {
2953 return _this3.Promise.resolve();
2954 } else {
2955 return _this3.runScript("init", _this3.prepareInitSettings(false)).then(function () {
2956 return _this3.runScript(name, args);
2957 });
2958 }
2959 } else if (e.message === "UNKNOWN_CLIENT") {
2960 return _this3.runScript("register_client", [_this3.instance.queued()]).then(function () {
2961 return _this3.runScript(name, args);
2962 });
2963 } else {
2964 return _this3.Promise.reject(e);
2965 }
2966 }));
2967
2968 case 4:
2969 case "end":
2970 return _context4.stop();
2971 }
2972 }
2973 }, _callee4, this);
2974 }));
2975
2976 return function runScript(_x4, _x5) {
2977 return _runScript.apply(this, arguments);
2978 };
2979 }()
2980 }, {
2981 key: "prepareArray",
2982 value: function prepareArray(arr) {
2983 var i, len, results, x;
2984 results = [];
2985
2986 for (i = 0, len = arr.length; i < len; i++) {
2987 x = arr[i];
2988 results.push(x != null ? x.toString() : "");
2989 }
2990
2991 return results;
2992 }
2993 }, {
2994 key: "prepareObject",
2995 value: function prepareObject(obj) {
2996 var arr, k, v;
2997 arr = [];
2998
2999 for (k in obj) {
3000 v = obj[k];
3001 arr.push(k, v != null ? v.toString() : "");
3002 }
3003
3004 return arr;
3005 }
3006 }, {
3007 key: "prepareInitSettings",
3008 value: function prepareInitSettings(clear) {
3009 var args;
3010 args = this.prepareObject(Object.assign({}, this.storeOptions, {
3011 id: this.originalId,
3012 version: this.instance.version,
3013 groupTimeout: this.timeout,
3014 clientTimeout: this.clientTimeout
3015 }));
3016 args.unshift(clear ? 1 : 0, this.instance.version);
3017 return args;
3018 }
3019 }, {
3020 key: "convertBool",
3021 value: function convertBool(b) {
3022 return !!b;
3023 }
3024 }, {
3025 key: "__updateSettings__",
3026 value: function () {
3027 var _updateSettings__ = _asyncToGenerator(
3028 /*#__PURE__*/
3029 regeneratorRuntime.mark(function _callee5(options) {
3030 return regeneratorRuntime.wrap(function _callee5$(_context5) {
3031 while (1) {
3032 switch (_context5.prev = _context5.next) {
3033 case 0:
3034 _context5.next = 2;
3035 return this.runScript("update_settings", this.prepareObject(options));
3036
3037 case 2:
3038 return _context5.abrupt("return", parser$4.overwrite(options, options, this.storeOptions));
3039
3040 case 3:
3041 case "end":
3042 return _context5.stop();
3043 }
3044 }
3045 }, _callee5, this);
3046 }));
3047
3048 return function __updateSettings__(_x6) {
3049 return _updateSettings__.apply(this, arguments);
3050 };
3051 }()
3052 }, {
3053 key: "__running__",
3054 value: function __running__() {
3055 return this.runScript("running", []);
3056 }
3057 }, {
3058 key: "__queued__",
3059 value: function __queued__() {
3060 return this.runScript("queued", []);
3061 }
3062 }, {
3063 key: "__done__",
3064 value: function __done__() {
3065 return this.runScript("done", []);
3066 }
3067 }, {
3068 key: "__groupCheck__",
3069 value: function () {
3070 var _groupCheck__ = _asyncToGenerator(
3071 /*#__PURE__*/
3072 regeneratorRuntime.mark(function _callee6() {
3073 return regeneratorRuntime.wrap(function _callee6$(_context6) {
3074 while (1) {
3075 switch (_context6.prev = _context6.next) {
3076 case 0:
3077 _context6.t0 = this;
3078 _context6.next = 3;
3079 return this.runScript("group_check", []);
3080
3081 case 3:
3082 _context6.t1 = _context6.sent;
3083 return _context6.abrupt("return", _context6.t0.convertBool.call(_context6.t0, _context6.t1));
3084
3085 case 5:
3086 case "end":
3087 return _context6.stop();
3088 }
3089 }
3090 }, _callee6, this);
3091 }));
3092
3093 return function __groupCheck__() {
3094 return _groupCheck__.apply(this, arguments);
3095 };
3096 }()
3097 }, {
3098 key: "__incrementReservoir__",
3099 value: function __incrementReservoir__(incr) {
3100 return this.runScript("increment_reservoir", [incr]);
3101 }
3102 }, {
3103 key: "__currentReservoir__",
3104 value: function __currentReservoir__() {
3105 return this.runScript("current_reservoir", []);
3106 }
3107 }, {
3108 key: "__check__",
3109 value: function () {
3110 var _check__ = _asyncToGenerator(
3111 /*#__PURE__*/
3112 regeneratorRuntime.mark(function _callee7(weight) {
3113 return regeneratorRuntime.wrap(function _callee7$(_context7) {
3114 while (1) {
3115 switch (_context7.prev = _context7.next) {
3116 case 0:
3117 _context7.t0 = this;
3118 _context7.next = 3;
3119 return this.runScript("check", this.prepareArray([weight]));
3120
3121 case 3:
3122 _context7.t1 = _context7.sent;
3123 return _context7.abrupt("return", _context7.t0.convertBool.call(_context7.t0, _context7.t1));
3124
3125 case 5:
3126 case "end":
3127 return _context7.stop();
3128 }
3129 }
3130 }, _callee7, this);
3131 }));
3132
3133 return function __check__(_x7) {
3134 return _check__.apply(this, arguments);
3135 };
3136 }()
3137 }, {
3138 key: "__register__",
3139 value: function () {
3140 var _register__ = _asyncToGenerator(
3141 /*#__PURE__*/
3142 regeneratorRuntime.mark(function _callee8(index, weight, expiration) {
3143 var reservoir, success, wait, _ref4, _ref5;
3144
3145 return regeneratorRuntime.wrap(function _callee8$(_context8) {
3146 while (1) {
3147 switch (_context8.prev = _context8.next) {
3148 case 0:
3149 _context8.next = 2;
3150 return this.runScript("register", this.prepareArray([index, weight, expiration]));
3151
3152 case 2:
3153 _ref4 = _context8.sent;
3154 _ref5 = _slicedToArray(_ref4, 3);
3155 success = _ref5[0];
3156 wait = _ref5[1];
3157 reservoir = _ref5[2];
3158 return _context8.abrupt("return", {
3159 success: this.convertBool(success),
3160 wait: wait,
3161 reservoir: reservoir
3162 });
3163
3164 case 8:
3165 case "end":
3166 return _context8.stop();
3167 }
3168 }
3169 }, _callee8, this);
3170 }));
3171
3172 return function __register__(_x8, _x9, _x10) {
3173 return _register__.apply(this, arguments);
3174 };
3175 }()
3176 }, {
3177 key: "__submit__",
3178 value: function () {
3179 var _submit__ = _asyncToGenerator(
3180 /*#__PURE__*/
3181 regeneratorRuntime.mark(function _callee9(queueLength, weight) {
3182 var blocked, e, maxConcurrent, overweight, reachedHWM, strategy, _ref6, _ref7, _e$message$split, _e$message$split2;
3183
3184 return regeneratorRuntime.wrap(function _callee9$(_context9) {
3185 while (1) {
3186 switch (_context9.prev = _context9.next) {
3187 case 0:
3188 _context9.prev = 0;
3189 _context9.next = 3;
3190 return this.runScript("submit", this.prepareArray([queueLength, weight]));
3191
3192 case 3:
3193 _ref6 = _context9.sent;
3194 _ref7 = _slicedToArray(_ref6, 3);
3195 reachedHWM = _ref7[0];
3196 blocked = _ref7[1];
3197 strategy = _ref7[2];
3198 return _context9.abrupt("return", {
3199 reachedHWM: this.convertBool(reachedHWM),
3200 blocked: this.convertBool(blocked),
3201 strategy: strategy
3202 });
3203
3204 case 11:
3205 _context9.prev = 11;
3206 _context9.t0 = _context9["catch"](0);
3207 e = _context9.t0;
3208
3209 if (!(e.message.indexOf("OVERWEIGHT") === 0)) {
3210 _context9.next = 23;
3211 break;
3212 }
3213
3214 _e$message$split = e.message.split(":");
3215 _e$message$split2 = _slicedToArray(_e$message$split, 3);
3216 overweight = _e$message$split2[0];
3217 weight = _e$message$split2[1];
3218 maxConcurrent = _e$message$split2[2];
3219 throw new BottleneckError$2("Impossible to add a job having a weight of ".concat(weight, " to a limiter having a maxConcurrent setting of ").concat(maxConcurrent));
3220
3221 case 23:
3222 throw e;
3223
3224 case 24:
3225 case "end":
3226 return _context9.stop();
3227 }
3228 }
3229 }, _callee9, this, [[0, 11]]);
3230 }));
3231
3232 return function __submit__(_x11, _x12) {
3233 return _submit__.apply(this, arguments);
3234 };
3235 }()
3236 }, {
3237 key: "__free__",
3238 value: function () {
3239 var _free__ = _asyncToGenerator(
3240 /*#__PURE__*/
3241 regeneratorRuntime.mark(function _callee10(index, weight) {
3242 var running;
3243 return regeneratorRuntime.wrap(function _callee10$(_context10) {
3244 while (1) {
3245 switch (_context10.prev = _context10.next) {
3246 case 0:
3247 _context10.next = 2;
3248 return this.runScript("free", this.prepareArray([index]));
3249
3250 case 2:
3251 running = _context10.sent;
3252 return _context10.abrupt("return", {
3253 running: running
3254 });
3255
3256 case 4:
3257 case "end":
3258 return _context10.stop();
3259 }
3260 }
3261 }, _callee10, this);
3262 }));
3263
3264 return function __free__(_x13, _x14) {
3265 return _free__.apply(this, arguments);
3266 };
3267 }()
3268 }]);
3269
3270 return RedisDatastore;
3271 }();
3272
3273 var RedisDatastore_1 = RedisDatastore;
3274
3275 var BottleneckError$3, States;
3276 BottleneckError$3 = BottleneckError_1;
3277
3278 States =
3279 /*#__PURE__*/
3280 function () {
3281 function States(status1) {
3282 _classCallCheck(this, States);
3283
3284 this.status = status1;
3285 this.jobs = {};
3286 this.counts = this.status.map(function () {
3287 return 0;
3288 });
3289 }
3290
3291 _createClass(States, [{
3292 key: "next",
3293 value: function next(id) {
3294 var current, next;
3295 current = this.jobs[id];
3296 next = current + 1;
3297
3298 if (current != null && next < this.status.length) {
3299 this.counts[current]--;
3300 this.counts[next]++;
3301 return this.jobs[id]++;
3302 } else if (current != null) {
3303 this.counts[current]--;
3304 return delete this.jobs[id];
3305 }
3306 }
3307 }, {
3308 key: "start",
3309 value: function start(id) {
3310 var initial;
3311 initial = 0;
3312 this.jobs[id] = initial;
3313 return this.counts[initial]++;
3314 }
3315 }, {
3316 key: "remove",
3317 value: function remove(id) {
3318 var current;
3319 current = this.jobs[id];
3320
3321 if (current != null) {
3322 this.counts[current]--;
3323 delete this.jobs[id];
3324 }
3325
3326 return current != null;
3327 }
3328 }, {
3329 key: "jobStatus",
3330 value: function jobStatus(id) {
3331 var ref;
3332 return (ref = this.status[this.jobs[id]]) != null ? ref : null;
3333 }
3334 }, {
3335 key: "statusJobs",
3336 value: function statusJobs(status) {
3337 var k, pos, ref, results, v;
3338
3339 if (status != null) {
3340 pos = this.status.indexOf(status);
3341
3342 if (pos < 0) {
3343 throw new BottleneckError$3("status must be one of ".concat(this.status.join(', ')));
3344 }
3345
3346 ref = this.jobs;
3347 results = [];
3348
3349 for (k in ref) {
3350 v = ref[k];
3351
3352 if (v === pos) {
3353 results.push(k);
3354 }
3355 }
3356
3357 return results;
3358 } else {
3359 return Object.keys(this.jobs);
3360 }
3361 }
3362 }, {
3363 key: "statusCounts",
3364 value: function statusCounts() {
3365 var _this = this;
3366
3367 return this.counts.reduce(function (acc, v, i) {
3368 acc[_this.status[i]] = v;
3369 return acc;
3370 }, {});
3371 }
3372 }]);
3373
3374 return States;
3375 }();
3376
3377 var States_1 = States;
3378
3379 var DLList$2,
3380 Sync,
3381 splice = [].splice;
3382 DLList$2 = DLList_1;
3383
3384 Sync =
3385 /*#__PURE__*/
3386 function () {
3387 function Sync(name, Promise) {
3388 _classCallCheck(this, Sync);
3389
3390 this.submit = this.submit.bind(this);
3391 this.name = name;
3392 this.Promise = Promise;
3393 this._running = 0;
3394 this._queue = new DLList$2();
3395 }
3396
3397 _createClass(Sync, [{
3398 key: "isEmpty",
3399 value: function isEmpty() {
3400 return this._queue.length === 0;
3401 }
3402 }, {
3403 key: "_tryToRun",
3404 value: function _tryToRun() {
3405 var _this = this;
3406
3407 var next;
3408
3409 if (this._running < 1 && this._queue.length > 0) {
3410 var _next;
3411
3412 this._running++;
3413 next = this._queue.shift();
3414 return (_next = next).task.apply(_next, _toConsumableArray(next.args).concat([function () {
3415 var _next2;
3416
3417 _this._running--;
3418
3419 _this._tryToRun();
3420
3421 return typeof next.cb === "function" ? (_next2 = next).cb.apply(_next2, arguments) : void 0;
3422 }]));
3423 }
3424 }
3425 }, {
3426 key: "submit",
3427 value: function submit(task) {
3428 var _ref, _ref2, _splice$call, _splice$call2;
3429
3430 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3431 args[_key - 1] = arguments[_key];
3432 }
3433
3434 var cb, ref;
3435 ref = args, (_ref = ref, _ref2 = _toArray(_ref), args = _ref2.slice(0), _ref), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call);
3436
3437 this._queue.push({
3438 task: task,
3439 args: args,
3440 cb: cb
3441 });
3442
3443 return this._tryToRun();
3444 }
3445 }, {
3446 key: "schedule",
3447 value: function schedule(task) {
3448 var _this2 = this;
3449
3450 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
3451 args[_key2 - 1] = arguments[_key2];
3452 }
3453
3454 var wrapped;
3455
3456 wrapped = function wrapped() {
3457 var _ref3, _ref4, _splice$call3, _splice$call4;
3458
3459 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
3460 args[_key3] = arguments[_key3];
3461 }
3462
3463 var cb, ref;
3464 ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), args = _ref4.slice(0), _ref3), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3);
3465 return task.apply(void 0, _toConsumableArray(args)).then(function () {
3466 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
3467 args[_key4] = arguments[_key4];
3468 }
3469
3470 return cb.apply(void 0, [null].concat(args));
3471 }).catch(function () {
3472 return cb.apply(void 0, arguments);
3473 });
3474 };
3475
3476 return new this.Promise(function (resolve, reject) {
3477 return _this2.submit.apply(_this2, [wrapped].concat(args, [function () {
3478 for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
3479 args[_key5] = arguments[_key5];
3480 }
3481
3482 return (args[0] != null ? reject : (args.shift(), resolve)).apply(void 0, args);
3483 }]));
3484 });
3485 }
3486 }]);
3487
3488 return Sync;
3489 }();
3490
3491 var Sync_1 = Sync;
3492
3493 var version = "2.17.0";
3494 var version$1 = {
3495 version: version
3496 };
3497
3498 var version$2 = /*#__PURE__*/Object.freeze({
3499 version: version,
3500 default: version$1
3501 });
3502
3503 var Events$4, Group, IORedisConnection$2, RedisConnection$2, Scripts$3, parser$5;
3504 parser$5 = parser;
3505 Events$4 = Events_1;
3506 RedisConnection$2 = RedisConnection_1;
3507 IORedisConnection$2 = IORedisConnection_1;
3508 Scripts$3 = Scripts;
3509
3510 Group = function () {
3511 var Group =
3512 /*#__PURE__*/
3513 function () {
3514 function Group() {
3515 var limiterOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3516
3517 _classCallCheck(this, Group);
3518
3519 this.deleteKey = this.deleteKey.bind(this);
3520 this.updateSettings = this.updateSettings.bind(this);
3521 this.limiterOptions = limiterOptions;
3522 parser$5.load(this.limiterOptions, this.defaults, this);
3523 this.Events = new Events$4(this);
3524 this.instances = {};
3525 this.Bottleneck = Bottleneck_1;
3526
3527 this._startAutoCleanup();
3528
3529 this.sharedConnection = this.connection != null;
3530
3531 if (this.connection == null) {
3532 if (this.limiterOptions.datastore === "redis") {
3533 this.connection = new RedisConnection$2(Object.assign({}, this.limiterOptions, {
3534 Events: this.Events
3535 }));
3536 } else if (this.limiterOptions.datastore === "ioredis") {
3537 this.connection = new IORedisConnection$2(Object.assign({}, this.limiterOptions, {
3538 Events: this.Events
3539 }));
3540 }
3541 }
3542 }
3543
3544 _createClass(Group, [{
3545 key: "key",
3546 value: function key() {
3547 var _this = this;
3548
3549 var _key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
3550
3551 var ref;
3552 return (ref = this.instances[_key]) != null ? ref : function () {
3553 var limiter;
3554 limiter = _this.instances[_key] = new _this.Bottleneck(Object.assign(_this.limiterOptions, {
3555 id: "".concat(_this.id, "-").concat(_key),
3556 timeout: _this.timeout,
3557 connection: _this.connection
3558 }));
3559
3560 _this.Events.trigger("created", limiter, _key);
3561
3562 return limiter;
3563 }();
3564 }
3565 }, {
3566 key: "deleteKey",
3567 value: function () {
3568 var _deleteKey = _asyncToGenerator(
3569 /*#__PURE__*/
3570 regeneratorRuntime.mark(function _callee() {
3571 var key,
3572 deleted,
3573 instance,
3574 _args = arguments;
3575 return regeneratorRuntime.wrap(function _callee$(_context) {
3576 while (1) {
3577 switch (_context.prev = _context.next) {
3578 case 0:
3579 key = _args.length > 0 && _args[0] !== undefined ? _args[0] : "";
3580 instance = this.instances[key];
3581
3582 if (!this.connection) {
3583 _context.next = 6;
3584 break;
3585 }
3586
3587 _context.next = 5;
3588 return this.connection.__runCommand__(['del'].concat(_toConsumableArray(Scripts$3.allKeys("".concat(this.id, "-").concat(key)))));
3589
3590 case 5:
3591 deleted = _context.sent;
3592
3593 case 6:
3594 if (!(instance != null)) {
3595 _context.next = 10;
3596 break;
3597 }
3598
3599 delete this.instances[key];
3600 _context.next = 10;
3601 return instance.disconnect();
3602
3603 case 10:
3604 return _context.abrupt("return", instance != null || deleted > 0);
3605
3606 case 11:
3607 case "end":
3608 return _context.stop();
3609 }
3610 }
3611 }, _callee, this);
3612 }));
3613
3614 return function deleteKey() {
3615 return _deleteKey.apply(this, arguments);
3616 };
3617 }()
3618 }, {
3619 key: "limiters",
3620 value: function limiters() {
3621 var k, ref, results, v;
3622 ref = this.instances;
3623 results = [];
3624
3625 for (k in ref) {
3626 v = ref[k];
3627 results.push({
3628 key: k,
3629 limiter: v
3630 });
3631 }
3632
3633 return results;
3634 }
3635 }, {
3636 key: "keys",
3637 value: function keys() {
3638 return Object.keys(this.instances);
3639 }
3640 }, {
3641 key: "clusterKeys",
3642 value: function () {
3643 var _clusterKeys = _asyncToGenerator(
3644 /*#__PURE__*/
3645 regeneratorRuntime.mark(function _callee2() {
3646 var cursor, end, found, i, k, keys, len, next, start, _ref, _ref2;
3647
3648 return regeneratorRuntime.wrap(function _callee2$(_context2) {
3649 while (1) {
3650 switch (_context2.prev = _context2.next) {
3651 case 0:
3652 if (!(this.connection == null)) {
3653 _context2.next = 2;
3654 break;
3655 }
3656
3657 return _context2.abrupt("return", this.Promise.resolve(this.keys()));
3658
3659 case 2:
3660 keys = [];
3661 cursor = null;
3662 start = "b_".concat(this.id, "-").length;
3663 end = "_settings".length;
3664
3665 case 6:
3666 if (!(cursor !== 0)) {
3667 _context2.next = 17;
3668 break;
3669 }
3670
3671 _context2.next = 9;
3672 return this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", "b_".concat(this.id, "-*_settings"), "count", 10000]);
3673
3674 case 9:
3675 _ref = _context2.sent;
3676 _ref2 = _slicedToArray(_ref, 2);
3677 next = _ref2[0];
3678 found = _ref2[1];
3679 cursor = ~~next;
3680
3681 for (i = 0, len = found.length; i < len; i++) {
3682 k = found[i];
3683 keys.push(k.slice(start, -end));
3684 }
3685
3686 _context2.next = 6;
3687 break;
3688
3689 case 17:
3690 return _context2.abrupt("return", keys);
3691
3692 case 18:
3693 case "end":
3694 return _context2.stop();
3695 }
3696 }
3697 }, _callee2, this);
3698 }));
3699
3700 return function clusterKeys() {
3701 return _clusterKeys.apply(this, arguments);
3702 };
3703 }()
3704 }, {
3705 key: "_startAutoCleanup",
3706 value: function _startAutoCleanup() {
3707 var _this2 = this;
3708
3709 var base;
3710 clearInterval(this.interval);
3711 return typeof (base = this.interval = setInterval(
3712 /*#__PURE__*/
3713 _asyncToGenerator(
3714 /*#__PURE__*/
3715 regeneratorRuntime.mark(function _callee3() {
3716 var e, k, ref, results, time, v;
3717 return regeneratorRuntime.wrap(function _callee3$(_context3) {
3718 while (1) {
3719 switch (_context3.prev = _context3.next) {
3720 case 0:
3721 time = Date.now();
3722 ref = _this2.instances;
3723 results = [];
3724 _context3.t0 = regeneratorRuntime.keys(ref);
3725
3726 case 4:
3727 if ((_context3.t1 = _context3.t0()).done) {
3728 _context3.next = 23;
3729 break;
3730 }
3731
3732 k = _context3.t1.value;
3733 v = ref[k];
3734 _context3.prev = 7;
3735 _context3.next = 10;
3736 return v._store.__groupCheck__(time);
3737
3738 case 10:
3739 if (!_context3.sent) {
3740 _context3.next = 14;
3741 break;
3742 }
3743
3744 results.push(_this2.deleteKey(k));
3745 _context3.next = 15;
3746 break;
3747
3748 case 14:
3749 results.push(void 0);
3750
3751 case 15:
3752 _context3.next = 21;
3753 break;
3754
3755 case 17:
3756 _context3.prev = 17;
3757 _context3.t2 = _context3["catch"](7);
3758 e = _context3.t2;
3759 results.push(v.Events.trigger("error", e));
3760
3761 case 21:
3762 _context3.next = 4;
3763 break;
3764
3765 case 23:
3766 return _context3.abrupt("return", results);
3767
3768 case 24:
3769 case "end":
3770 return _context3.stop();
3771 }
3772 }
3773 }, _callee3, this, [[7, 17]]);
3774 })), this.timeout / 2)).unref === "function" ? base.unref() : void 0;
3775 }
3776 }, {
3777 key: "updateSettings",
3778 value: function updateSettings() {
3779 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3780 parser$5.overwrite(options, this.defaults, this);
3781 parser$5.overwrite(options, options, this.limiterOptions);
3782
3783 if (options.timeout != null) {
3784 return this._startAutoCleanup();
3785 }
3786 }
3787 }, {
3788 key: "disconnect",
3789 value: function disconnect() {
3790 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
3791 var ref;
3792
3793 if (!this.sharedConnection) {
3794 return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;
3795 }
3796 }
3797 }]);
3798
3799 return Group;
3800 }();
3801 Group.prototype.defaults = {
3802 timeout: 1000 * 60 * 5,
3803 connection: null,
3804 Promise: Promise,
3805 id: "group-key"
3806 };
3807 return Group;
3808 }.call(commonjsGlobal);
3809
3810 var Group_1 = Group;
3811
3812 var Batcher, Events$5, parser$6;
3813 parser$6 = parser;
3814 Events$5 = Events_1;
3815
3816 Batcher = function () {
3817 var Batcher =
3818 /*#__PURE__*/
3819 function () {
3820 function Batcher() {
3821 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3822
3823 _classCallCheck(this, Batcher);
3824
3825 this.options = options;
3826 parser$6.load(this.options, this.defaults, this);
3827 this.Events = new Events$5(this);
3828 this._arr = [];
3829
3830 this._resetPromise();
3831
3832 this._lastFlush = Date.now();
3833 }
3834
3835 _createClass(Batcher, [{
3836 key: "_resetPromise",
3837 value: function _resetPromise() {
3838 var _this = this;
3839
3840 return this._promise = new this.Promise(function (res, rej) {
3841 return _this._resolve = res;
3842 });
3843 }
3844 }, {
3845 key: "_flush",
3846 value: function _flush() {
3847 clearTimeout(this._timeout);
3848 this._lastFlush = Date.now();
3849
3850 this._resolve();
3851
3852 this.Events.trigger("batch", this._arr);
3853 this._arr = [];
3854 return this._resetPromise();
3855 }
3856 }, {
3857 key: "add",
3858 value: function add(data) {
3859 var _this2 = this;
3860
3861 var ret;
3862
3863 this._arr.push(data);
3864
3865 ret = this._promise;
3866
3867 if (this._arr.length === this.maxSize) {
3868 this._flush();
3869 } else if (this.maxTime != null && this._arr.length === 1) {
3870 this._timeout = setTimeout(function () {
3871 return _this2._flush();
3872 }, this.maxTime);
3873 }
3874
3875 return ret;
3876 }
3877 }]);
3878
3879 return Batcher;
3880 }();
3881 Batcher.prototype.defaults = {
3882 maxTime: null,
3883 maxSize: null,
3884 Promise: Promise
3885 };
3886 return Batcher;
3887 }.call(commonjsGlobal);
3888
3889 var Batcher_1 = Batcher;
3890
3891 var require$$7 = getCjsExportFromNamespace(version$2);
3892
3893 var Bottleneck,
3894 DEFAULT_PRIORITY,
3895 Events$6,
3896 LocalDatastore$1,
3897 NUM_PRIORITIES,
3898 Queues$1,
3899 RedisDatastore$1,
3900 States$1,
3901 Sync$1,
3902 parser$7,
3903 splice$1 = [].splice;
3904 NUM_PRIORITIES = 10;
3905 DEFAULT_PRIORITY = 5;
3906 parser$7 = parser;
3907 Queues$1 = Queues_1;
3908 LocalDatastore$1 = LocalDatastore_1;
3909 RedisDatastore$1 = RedisDatastore_1;
3910 Events$6 = Events_1;
3911 States$1 = States_1;
3912 Sync$1 = Sync_1;
3913
3914 Bottleneck = function () {
3915 var Bottleneck =
3916 /*#__PURE__*/
3917 function () {
3918 function Bottleneck() {
3919 var _this = this;
3920
3921 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3922
3923 _classCallCheck(this, Bottleneck);
3924
3925 var storeInstanceOptions, storeOptions;
3926 this._drainOne = this._drainOne.bind(this);
3927 this.submit = this.submit.bind(this);
3928 this.schedule = this.schedule.bind(this);
3929 this.updateSettings = this.updateSettings.bind(this);
3930 this.incrementReservoir = this.incrementReservoir.bind(this);
3931
3932 for (var _len = arguments.length, invalid = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3933 invalid[_key - 1] = arguments[_key];
3934 }
3935
3936 this._validateOptions(options, invalid);
3937
3938 parser$7.load(options, this.instanceDefaults, this);
3939 this._queues = new Queues$1(NUM_PRIORITIES);
3940 this._scheduled = {};
3941 this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : []));
3942 this._limiter = null;
3943 this.Events = new Events$6(this);
3944 this._submitLock = new Sync$1("submit", this.Promise);
3945 this._registerLock = new Sync$1("register", this.Promise);
3946 storeOptions = parser$7.load(options, this.storeDefaults, {});
3947
3948 this._store = function () {
3949 if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) {
3950 storeInstanceOptions = parser$7.load(options, this.redisStoreDefaults, {});
3951 return new RedisDatastore$1(this, storeOptions, storeInstanceOptions);
3952 } else if (this.datastore === "local") {
3953 storeInstanceOptions = parser$7.load(options, this.localStoreDefaults, {});
3954 return new LocalDatastore$1(this, storeOptions, storeInstanceOptions);
3955 } else {
3956 throw new Bottleneck.prototype.BottleneckError("Invalid datastore type: ".concat(this.datastore));
3957 }
3958 }.call(this);
3959
3960 this._queues.on("leftzero", function () {
3961 var base;
3962 return typeof (base = _this._store.heartbeat).ref === "function" ? base.ref() : void 0;
3963 });
3964
3965 this._queues.on("zero", function () {
3966 var base;
3967 return typeof (base = _this._store.heartbeat).unref === "function" ? base.unref() : void 0;
3968 });
3969 }
3970
3971 _createClass(Bottleneck, [{
3972 key: "_validateOptions",
3973 value: function _validateOptions(options, invalid) {
3974 if (!(options != null && _typeof(options) === "object" && invalid.length === 0)) {
3975 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.");
3976 }
3977 }
3978 }, {
3979 key: "ready",
3980 value: function ready() {
3981 return this._store.ready;
3982 }
3983 }, {
3984 key: "clients",
3985 value: function clients() {
3986 return this._store.clients;
3987 }
3988 }, {
3989 key: "channel",
3990 value: function channel() {
3991 return "b_".concat(this.id);
3992 }
3993 }, {
3994 key: "channel_client",
3995 value: function channel_client() {
3996 return "b_".concat(this.id, "_").concat(this._store.clientId);
3997 }
3998 }, {
3999 key: "publish",
4000 value: function publish(message) {
4001 return this._store.__publish__(message);
4002 }
4003 }, {
4004 key: "disconnect",
4005 value: function disconnect() {
4006 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
4007 return this._store.__disconnect__(flush);
4008 }
4009 }, {
4010 key: "chain",
4011 value: function chain(_limiter) {
4012 this._limiter = _limiter;
4013 return this;
4014 }
4015 }, {
4016 key: "queued",
4017 value: function queued(priority) {
4018 return this._queues.queued(priority);
4019 }
4020 }, {
4021 key: "clusterQueued",
4022 value: function clusterQueued() {
4023 return this._store.__queued__();
4024 }
4025 }, {
4026 key: "empty",
4027 value: function empty() {
4028 return this.queued() === 0 && this._submitLock.isEmpty();
4029 }
4030 }, {
4031 key: "running",
4032 value: function running() {
4033 return this._store.__running__();
4034 }
4035 }, {
4036 key: "done",
4037 value: function done() {
4038 return this._store.__done__();
4039 }
4040 }, {
4041 key: "jobStatus",
4042 value: function jobStatus(id) {
4043 return this._states.jobStatus(id);
4044 }
4045 }, {
4046 key: "jobs",
4047 value: function jobs(status) {
4048 return this._states.statusJobs(status);
4049 }
4050 }, {
4051 key: "counts",
4052 value: function counts() {
4053 return this._states.statusCounts();
4054 }
4055 }, {
4056 key: "_sanitizePriority",
4057 value: function _sanitizePriority(priority) {
4058 var sProperty;
4059 sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority;
4060
4061 if (sProperty < 0) {
4062 return 0;
4063 } else if (sProperty > NUM_PRIORITIES - 1) {
4064 return NUM_PRIORITIES - 1;
4065 } else {
4066 return sProperty;
4067 }
4068 }
4069 }, {
4070 key: "_randomIndex",
4071 value: function _randomIndex() {
4072 return Math.random().toString(36).slice(2);
4073 }
4074 }, {
4075 key: "check",
4076 value: function check() {
4077 var weight = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
4078 return this._store.__check__(weight);
4079 }
4080 }, {
4081 key: "_run",
4082 value: function _run(next, wait, index, retryCount) {
4083 var _this2 = this;
4084
4085 var completed, done;
4086 this.Events.trigger("debug", "Scheduling ".concat(next.options.id), {
4087 args: next.args,
4088 options: next.options
4089 });
4090 done = false;
4091
4092 completed =
4093 /*#__PURE__*/
4094 function () {
4095 var _ref = _asyncToGenerator(
4096 /*#__PURE__*/
4097 regeneratorRuntime.mark(function _callee() {
4098 var e,
4099 error,
4100 eventInfo,
4101 retry,
4102 retryAfter,
4103 running,
4104 _ref2,
4105 _args = arguments;
4106
4107 return regeneratorRuntime.wrap(function _callee$(_context) {
4108 while (1) {
4109 switch (_context.prev = _context.next) {
4110 case 0:
4111 if (done) {
4112 _context.next = 30;
4113 break;
4114 }
4115
4116 _context.prev = 1;
4117 done = true;
4118 clearTimeout(_this2._scheduled[index].expiration);
4119 delete _this2._scheduled[index];
4120 eventInfo = {
4121 args: next.args,
4122 options: next.options,
4123 retryCount: retryCount
4124 };
4125
4126 if (!((error = _args.length <= 0 ? undefined : _args[0]) != null)) {
4127 _context.next = 14;
4128 break;
4129 }
4130
4131 _context.next = 9;
4132 return _this2.Events.trigger("failed", error, eventInfo);
4133
4134 case 9:
4135 retry = _context.sent;
4136
4137 if (!(retry != null)) {
4138 _context.next = 14;
4139 break;
4140 }
4141
4142 retryAfter = ~~retry;
4143
4144 _this2.Events.trigger("retry", "Retrying ".concat(next.options.id, " after ").concat(retryAfter, " ms"), eventInfo);
4145
4146 return _context.abrupt("return", _this2._run(next, retryAfter, index, retryCount + 1));
4147
4148 case 14:
4149 _this2._states.next(next.options.id); // DONE
4150
4151
4152 _this2.Events.trigger("debug", "Completed ".concat(next.options.id), eventInfo);
4153
4154 _this2.Events.trigger("done", "Completed ".concat(next.options.id), eventInfo);
4155
4156 _context.next = 19;
4157 return _this2._store.__free__(index, next.options.weight);
4158
4159 case 19:
4160 _ref2 = _context.sent;
4161 running = _ref2.running;
4162
4163 _this2.Events.trigger("debug", "Freed ".concat(next.options.id), eventInfo);
4164
4165 if (running === 0 && _this2.empty()) {
4166 _this2.Events.trigger("idle");
4167 }
4168
4169 return _context.abrupt("return", typeof next.cb === "function" ? next.cb.apply(next, _args) : void 0);
4170
4171 case 26:
4172 _context.prev = 26;
4173 _context.t0 = _context["catch"](1);
4174 e = _context.t0;
4175 return _context.abrupt("return", _this2.Events.trigger("error", e));
4176
4177 case 30:
4178 case "end":
4179 return _context.stop();
4180 }
4181 }
4182 }, _callee, this, [[1, 26]]);
4183 }));
4184
4185 return function completed() {
4186 return _ref.apply(this, arguments);
4187 };
4188 }();
4189
4190 if (retryCount === 0) {
4191 // RUNNING
4192 this._states.next(next.options.id);
4193 }
4194
4195 return this._scheduled[index] = {
4196 timeout: setTimeout(function () {
4197 _this2.Events.trigger("debug", "Executing ".concat(next.options.id), {
4198 args: next.args,
4199 options: next.options
4200 });
4201
4202 if (retryCount === 0) {
4203 // EXECUTING
4204 _this2._states.next(next.options.id);
4205 }
4206
4207 if (_this2._limiter != null) {
4208 var _this2$_limiter;
4209
4210 return (_this2$_limiter = _this2._limiter).submit.apply(_this2$_limiter, [next.options, next.task].concat(_toConsumableArray(next.args), [completed]));
4211 } else {
4212 return next.task.apply(next, _toConsumableArray(next.args).concat([completed]));
4213 }
4214 }, wait),
4215 expiration: next.options.expiration != null ? setTimeout(function () {
4216 return completed(new Bottleneck.prototype.BottleneckError("This job timed out after ".concat(next.options.expiration, " ms.")));
4217 }, wait + next.options.expiration) : void 0,
4218 job: next
4219 };
4220 }
4221 }, {
4222 key: "_drainOne",
4223 value: function _drainOne(capacity) {
4224 var _this3 = this;
4225
4226 return this._registerLock.schedule(function () {
4227 var args, index, next, options, queue;
4228
4229 if (_this3.queued() === 0) {
4230 return _this3.Promise.resolve(null);
4231 }
4232
4233 queue = _this3._queues.getFirst();
4234
4235 var _next = next = queue.first();
4236
4237 options = _next.options;
4238 args = _next.args;
4239
4240 if (capacity != null && options.weight > capacity) {
4241 return _this3.Promise.resolve(null);
4242 }
4243
4244 _this3.Events.trigger("debug", "Draining ".concat(options.id), {
4245 args: args,
4246 options: options
4247 });
4248
4249 index = _this3._randomIndex();
4250 return _this3._store.__register__(index, options.weight, options.expiration).then(function (_ref3) {
4251 var success = _ref3.success,
4252 wait = _ref3.wait,
4253 reservoir = _ref3.reservoir;
4254 var empty;
4255
4256 _this3.Events.trigger("debug", "Drained ".concat(options.id), {
4257 success: success,
4258 args: args,
4259 options: options
4260 });
4261
4262 if (success) {
4263 queue.shift();
4264 empty = _this3.empty();
4265
4266 if (empty) {
4267 _this3.Events.trigger("empty");
4268 }
4269
4270 if (reservoir === 0) {
4271 _this3.Events.trigger("depleted", empty);
4272 }
4273
4274 _this3._run(next, wait, index, 0);
4275
4276 return _this3.Promise.resolve(options.weight);
4277 } else {
4278 return _this3.Promise.resolve(null);
4279 }
4280 });
4281 });
4282 }
4283 }, {
4284 key: "_drainAll",
4285 value: function _drainAll(capacity) {
4286 var _this4 = this;
4287
4288 var total = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
4289 return this._drainOne(capacity).then(function (drained) {
4290 var newCapacity;
4291
4292 if (drained != null) {
4293 newCapacity = capacity != null ? capacity - drained : capacity;
4294 return _this4._drainAll(newCapacity, total + drained);
4295 } else {
4296 return _this4.Promise.resolve(total);
4297 }
4298 }).catch(function (e) {
4299 return _this4.Events.trigger("error", e);
4300 });
4301 }
4302 }, {
4303 key: "_drop",
4304 value: function _drop(job) {
4305 var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "This job has been dropped by Bottleneck";
4306
4307 if (this._states.remove(job.options.id)) {
4308 if (this.rejectOnDrop) {
4309 if (typeof job.cb === "function") {
4310 job.cb(new Bottleneck.prototype.BottleneckError(message));
4311 }
4312 }
4313
4314 return this.Events.trigger("dropped", job);
4315 }
4316 }
4317 }, {
4318 key: "_dropAllQueued",
4319 value: function _dropAllQueued(message) {
4320 var _this5 = this;
4321
4322 return this._queues.shiftAll(function (job) {
4323 return _this5._drop(job, message);
4324 });
4325 }
4326 }, {
4327 key: "stop",
4328 value: function stop() {
4329 var _this6 = this;
4330
4331 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4332 var done, waitForExecuting;
4333 options = parser$7.load(options, this.stopDefaults);
4334
4335 waitForExecuting = function waitForExecuting(at) {
4336 var finished;
4337
4338 finished = function finished() {
4339 var counts;
4340 counts = _this6._states.counts;
4341 return counts[0] + counts[1] + counts[2] + counts[3] === at;
4342 };
4343
4344 return new _this6.Promise(function (resolve, reject) {
4345 if (finished()) {
4346 return resolve();
4347 } else {
4348 return _this6.on("done", function () {
4349 if (finished()) {
4350 _this6.removeAllListeners("done");
4351
4352 return resolve();
4353 }
4354 });
4355 }
4356 });
4357 };
4358
4359 done = options.dropWaitingJobs ? (this._run = function (next) {
4360 return _this6._drop(next, options.dropErrorMessage);
4361 }, this._drainOne = function () {
4362 return _this6.Promise.resolve(null);
4363 }, this._registerLock.schedule(function () {
4364 return _this6._submitLock.schedule(function () {
4365 var k, ref, v;
4366 ref = _this6._scheduled;
4367
4368 for (k in ref) {
4369 v = ref[k];
4370
4371 if (_this6.jobStatus(v.job.options.id) === "RUNNING") {
4372 clearTimeout(v.timeout);
4373 clearTimeout(v.expiration);
4374
4375 _this6._drop(v.job, options.dropErrorMessage);
4376 }
4377 }
4378
4379 _this6._dropAllQueued(options.dropErrorMessage);
4380
4381 return waitForExecuting(0);
4382 });
4383 })) : this.schedule({
4384 priority: NUM_PRIORITIES - 1,
4385 weight: 0
4386 }, function () {
4387 return waitForExecuting(1);
4388 });
4389
4390 this.submit = function () {
4391 var _ref4, _ref5, _splice$call, _splice$call2;
4392
4393 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
4394 args[_key2] = arguments[_key2];
4395 }
4396
4397 var cb, ref;
4398 ref = args, (_ref4 = ref, _ref5 = _toArray(_ref4), args = _ref5.slice(0), _ref4), (_splice$call = splice$1.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call);
4399 return typeof cb === "function" ? cb(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)) : void 0;
4400 };
4401
4402 this.stop = function () {
4403 return _this6.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called"));
4404 };
4405
4406 return done;
4407 }
4408 }, {
4409 key: "submit",
4410 value: function submit() {
4411 var _this7 = this;
4412
4413 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
4414 args[_key3] = arguments[_key3];
4415 }
4416
4417 var cb, job, options, ref, ref1, task;
4418
4419 if (typeof args[0] === "function") {
4420 var _ref6, _ref7, _splice$call3, _splice$call4;
4421
4422 ref = args, (_ref6 = ref, _ref7 = _toArray(_ref6), task = _ref7[0], args = _ref7.slice(1), _ref6), (_splice$call3 = splice$1.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3);
4423 options = parser$7.load({}, this.jobDefaults, {});
4424 } else {
4425 var _ref8, _ref9, _splice$call5, _splice$call6;
4426
4427 ref1 = args, (_ref8 = ref1, _ref9 = _toArray(_ref8), options = _ref9[0], task = _ref9[1], args = _ref9.slice(2), _ref8), (_splice$call5 = splice$1.call(args, -1), _splice$call6 = _slicedToArray(_splice$call5, 1), cb = _splice$call6[0], _splice$call5);
4428 options = parser$7.load(options, this.jobDefaults);
4429 }
4430
4431 job = {
4432 options: options,
4433 task: task,
4434 args: args,
4435 cb: cb
4436 };
4437 options.priority = this._sanitizePriority(options.priority);
4438
4439 if (options.id === this.jobDefaults.id) {
4440 options.id = "".concat(options.id, "-").concat(this._randomIndex());
4441 }
4442
4443 if (this.jobStatus(options.id) != null) {
4444 if (typeof job.cb === "function") {
4445 job.cb(new Bottleneck.prototype.BottleneckError("A job with the same id already exists (id=".concat(options.id, ")")));
4446 }
4447
4448 return false;
4449 }
4450
4451 this._states.start(options.id); // RECEIVED
4452
4453
4454 this.Events.trigger("debug", "Queueing ".concat(options.id), {
4455 args: args,
4456 options: options
4457 });
4458 return this._submitLock.schedule(
4459 /*#__PURE__*/
4460 _asyncToGenerator(
4461 /*#__PURE__*/
4462 regeneratorRuntime.mark(function _callee2() {
4463 var blocked, e, reachedHWM, shifted, strategy, _ref11;
4464
4465 return regeneratorRuntime.wrap(function _callee2$(_context2) {
4466 while (1) {
4467 switch (_context2.prev = _context2.next) {
4468 case 0:
4469 _context2.prev = 0;
4470 _context2.next = 3;
4471 return _this7._store.__submit__(_this7.queued(), options.weight);
4472
4473 case 3:
4474 _ref11 = _context2.sent;
4475 reachedHWM = _ref11.reachedHWM;
4476 blocked = _ref11.blocked;
4477 strategy = _ref11.strategy;
4478
4479 _this7.Events.trigger("debug", "Queued ".concat(options.id), {
4480 args: args,
4481 options: options,
4482 reachedHWM: reachedHWM,
4483 blocked: blocked
4484 });
4485
4486 _context2.next = 17;
4487 break;
4488
4489 case 10:
4490 _context2.prev = 10;
4491 _context2.t0 = _context2["catch"](0);
4492 e = _context2.t0;
4493
4494 _this7._states.remove(options.id);
4495
4496 _this7.Events.trigger("debug", "Could not queue ".concat(options.id), {
4497 args: args,
4498 options: options,
4499 error: e
4500 });
4501
4502 if (typeof job.cb === "function") {
4503 job.cb(e);
4504 }
4505
4506 return _context2.abrupt("return", false);
4507
4508 case 17:
4509 if (!blocked) {
4510 _context2.next = 22;
4511 break;
4512 }
4513
4514 _this7._drop(job);
4515
4516 return _context2.abrupt("return", true);
4517
4518 case 22:
4519 if (!reachedHWM) {
4520 _context2.next = 28;
4521 break;
4522 }
4523
4524 shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this7._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this7._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0;
4525
4526 if (shifted != null) {
4527 _this7._drop(shifted);
4528 }
4529
4530 if (!(shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW)) {
4531 _context2.next = 28;
4532 break;
4533 }
4534
4535 if (shifted == null) {
4536 _this7._drop(job);
4537 }
4538
4539 return _context2.abrupt("return", reachedHWM);
4540
4541 case 28:
4542 _this7._states.next(job.options.id); // QUEUED
4543
4544
4545 _this7._queues.push(options.priority, job);
4546
4547 _context2.next = 32;
4548 return _this7._drainAll();
4549
4550 case 32:
4551 return _context2.abrupt("return", reachedHWM);
4552
4553 case 33:
4554 case "end":
4555 return _context2.stop();
4556 }
4557 }
4558 }, _callee2, this, [[0, 10]]);
4559 })));
4560 }
4561 }, {
4562 key: "schedule",
4563 value: function schedule() {
4564 var _this8 = this;
4565
4566 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
4567 args[_key4] = arguments[_key4];
4568 }
4569
4570 var options, task, wrapped;
4571
4572 if (typeof args[0] === "function") {
4573 var _args3 = args;
4574
4575 var _args4 = _toArray(_args3);
4576
4577 task = _args4[0];
4578 args = _args4.slice(1);
4579 options = parser$7.load({}, this.jobDefaults, {});
4580 } else {
4581 var _args5 = args;
4582
4583 var _args6 = _toArray(_args5);
4584
4585 options = _args6[0];
4586 task = _args6[1];
4587 args = _args6.slice(2);
4588 options = parser$7.load(options, this.jobDefaults);
4589 }
4590
4591 wrapped = function wrapped() {
4592 var _ref12, _ref13, _splice$call7, _splice$call8;
4593
4594 for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
4595 args[_key5] = arguments[_key5];
4596 }
4597
4598 var cb, e, ref, returned;
4599 ref = args, (_ref12 = ref, _ref13 = _toArray(_ref12), args = _ref13.slice(0), _ref12), (_splice$call7 = splice$1.call(args, -1), _splice$call8 = _slicedToArray(_splice$call7, 1), cb = _splice$call8[0], _splice$call7);
4600
4601 returned = function () {
4602 try {
4603 return task.apply(void 0, _toConsumableArray(args));
4604 } catch (error1) {
4605 e = error1;
4606 return this.Promise.reject(e);
4607 }
4608 }.call(_this8);
4609
4610 return (!((returned != null ? returned.then : void 0) != null && typeof returned.then === "function") ? _this8.Promise.resolve(returned) : returned).then(function () {
4611 for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
4612 args[_key6] = arguments[_key6];
4613 }
4614
4615 return cb.apply(void 0, [null].concat(args));
4616 }).catch(function () {
4617 return cb.apply(void 0, arguments);
4618 });
4619 };
4620
4621 return new this.Promise(function (resolve, reject) {
4622 return _this8.submit.apply(_this8, [options, wrapped].concat(_toConsumableArray(args), [function () {
4623 for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
4624 args[_key7] = arguments[_key7];
4625 }
4626
4627 return (args[0] != null ? reject : (args.shift(), resolve)).apply(void 0, args);
4628 }])).catch(function (e) {
4629 return _this8.Events.trigger("error", e);
4630 });
4631 });
4632 }
4633 }, {
4634 key: "wrap",
4635 value: function wrap(fn) {
4636 var schedule, wrapped;
4637 schedule = this.schedule;
4638
4639 wrapped = function wrapped() {
4640 for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
4641 args[_key8] = arguments[_key8];
4642 }
4643
4644 return schedule.apply(void 0, [fn.bind(this)].concat(args));
4645 };
4646
4647 wrapped.withOptions = function (options) {
4648 for (var _len9 = arguments.length, args = new Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) {
4649 args[_key9 - 1] = arguments[_key9];
4650 }
4651
4652 return schedule.apply(void 0, [options, fn].concat(args));
4653 };
4654
4655 return wrapped;
4656 }
4657 }, {
4658 key: "updateSettings",
4659 value: function () {
4660 var _updateSettings = _asyncToGenerator(
4661 /*#__PURE__*/
4662 regeneratorRuntime.mark(function _callee3() {
4663 var options,
4664 _args7 = arguments;
4665 return regeneratorRuntime.wrap(function _callee3$(_context3) {
4666 while (1) {
4667 switch (_context3.prev = _context3.next) {
4668 case 0:
4669 options = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {};
4670 _context3.next = 3;
4671 return this._store.__updateSettings__(parser$7.overwrite(options, this.storeDefaults));
4672
4673 case 3:
4674 parser$7.overwrite(options, this.instanceDefaults, this);
4675 return _context3.abrupt("return", this);
4676
4677 case 5:
4678 case "end":
4679 return _context3.stop();
4680 }
4681 }
4682 }, _callee3, this);
4683 }));
4684
4685 return function updateSettings() {
4686 return _updateSettings.apply(this, arguments);
4687 };
4688 }()
4689 }, {
4690 key: "currentReservoir",
4691 value: function currentReservoir() {
4692 return this._store.__currentReservoir__();
4693 }
4694 }, {
4695 key: "incrementReservoir",
4696 value: function incrementReservoir() {
4697 var incr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
4698 return this._store.__incrementReservoir__(incr);
4699 }
4700 }]);
4701
4702 return Bottleneck;
4703 }();
4704 Bottleneck.default = Bottleneck;
4705 Bottleneck.Events = Events$6;
4706 Bottleneck.version = Bottleneck.prototype.version = require$$7.version;
4707 Bottleneck.strategy = Bottleneck.prototype.strategy = {
4708 LEAK: 1,
4709 OVERFLOW: 2,
4710 OVERFLOW_PRIORITY: 4,
4711 BLOCK: 3
4712 };
4713 Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1;
4714 Bottleneck.Group = Bottleneck.prototype.Group = Group_1;
4715 Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = RedisConnection_1;
4716 Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = IORedisConnection_1;
4717 Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1;
4718 Bottleneck.prototype.jobDefaults = {
4719 priority: DEFAULT_PRIORITY,
4720 weight: 1,
4721 expiration: null,
4722 id: "<no-id>"
4723 };
4724 Bottleneck.prototype.storeDefaults = {
4725 maxConcurrent: null,
4726 minTime: 0,
4727 highWater: null,
4728 strategy: Bottleneck.prototype.strategy.LEAK,
4729 penalty: null,
4730 reservoir: null,
4731 reservoirRefreshInterval: null,
4732 reservoirRefreshAmount: null
4733 };
4734 Bottleneck.prototype.localStoreDefaults = {
4735 Promise: Promise,
4736 timeout: null,
4737 heartbeatInterval: 250
4738 };
4739 Bottleneck.prototype.redisStoreDefaults = {
4740 Promise: Promise,
4741 timeout: null,
4742 heartbeatInterval: 5000,
4743 clientTimeout: 10000,
4744 clientOptions: {},
4745 clusterNodes: null,
4746 clearDatastore: false,
4747 connection: null
4748 };
4749 Bottleneck.prototype.instanceDefaults = {
4750 datastore: "local",
4751 connection: null,
4752 id: "<no-id>",
4753 rejectOnDrop: true,
4754 trackDoneStatus: false,
4755 Promise: Promise
4756 };
4757 Bottleneck.prototype.stopDefaults = {
4758 enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.",
4759 dropWaitingJobs: true,
4760 dropErrorMessage: "This limiter has been stopped."
4761 };
4762 return Bottleneck;
4763 }.call(commonjsGlobal);
4764
4765 var Bottleneck_1 = Bottleneck;
4766
4767 var es5 = Bottleneck_1;
4768
4769 return es5;
4770
4771})));