miniflare 0.0.0-e7ea6005c → 0.0.0-e8aaa3930

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1971 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __commonJS = (cb, mod) => function() {
7
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from == "object" || typeof from == "function")
11
+ for (let key of __getOwnPropNames(from))
12
+ !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ return to;
14
+ };
15
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
16
+ // If the importer is in node compatibility mode or this is not an ESM
17
+ // file that has been converted to a CommonJS file using a Babel-
18
+ // compatible transform (i.e. "__esModule" has not been set), then set
19
+ // "default" to the CommonJS "module.exports" for node compatibility.
20
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
21
+ mod
22
+ ));
23
+
24
+ // ../../node_modules/.pnpm/heap-js@2.5.0/node_modules/heap-js/dist/heap-js.umd.js
25
+ var require_heap_js_umd = __commonJS({
26
+ "../../node_modules/.pnpm/heap-js@2.5.0/node_modules/heap-js/dist/heap-js.umd.js"(exports, module) {
27
+ (function(global, factory) {
28
+ typeof exports == "object" && typeof module < "u" ? factory(exports) : typeof define == "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis < "u" ? globalThis : global || self, factory(global.heap = {}));
29
+ })(exports, function(exports2) {
30
+ "use strict";
31
+ var __awaiter = function(thisArg, _arguments, P, generator) {
32
+ function adopt(value) {
33
+ return value instanceof P ? value : new P(function(resolve) {
34
+ resolve(value);
35
+ });
36
+ }
37
+ return new (P || (P = Promise))(function(resolve, reject) {
38
+ function fulfilled(value) {
39
+ try {
40
+ step(generator.next(value));
41
+ } catch (e) {
42
+ reject(e);
43
+ }
44
+ }
45
+ function rejected(value) {
46
+ try {
47
+ step(generator.throw(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ }
52
+ function step(result) {
53
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
54
+ }
55
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
56
+ });
57
+ }, __generator$1 = function(thisArg, body) {
58
+ var _ = { label: 0, sent: function() {
59
+ if (t[0] & 1)
60
+ throw t[1];
61
+ return t[1];
62
+ }, trys: [], ops: [] }, f, y, t, g;
63
+ return g = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol == "function" && (g[Symbol.iterator] = function() {
64
+ return this;
65
+ }), g;
66
+ function verb(n2) {
67
+ return function(v) {
68
+ return step([n2, v]);
69
+ };
70
+ }
71
+ function step(op) {
72
+ if (f)
73
+ throw new TypeError("Generator is already executing.");
74
+ for (; g && (g = 0, op[0] && (_ = 0)), _; )
75
+ try {
76
+ if (f = 1, y && (t = op[0] & 2 ? y.return : op[0] ? y.throw || ((t = y.return) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
77
+ return t;
78
+ switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
79
+ case 0:
80
+ case 1:
81
+ t = op;
82
+ break;
83
+ case 4:
84
+ return _.label++, { value: op[1], done: !1 };
85
+ case 5:
86
+ _.label++, y = op[1], op = [0];
87
+ continue;
88
+ case 7:
89
+ op = _.ops.pop(), _.trys.pop();
90
+ continue;
91
+ default:
92
+ if (t = _.trys, !(t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
93
+ _ = 0;
94
+ continue;
95
+ }
96
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
97
+ _.label = op[1];
98
+ break;
99
+ }
100
+ if (op[0] === 6 && _.label < t[1]) {
101
+ _.label = t[1], t = op;
102
+ break;
103
+ }
104
+ if (t && _.label < t[2]) {
105
+ _.label = t[2], _.ops.push(op);
106
+ break;
107
+ }
108
+ t[2] && _.ops.pop(), _.trys.pop();
109
+ continue;
110
+ }
111
+ op = body.call(thisArg, _);
112
+ } catch (e) {
113
+ op = [6, e], y = 0;
114
+ } finally {
115
+ f = t = 0;
116
+ }
117
+ if (op[0] & 5)
118
+ throw op[1];
119
+ return { value: op[0] ? op[1] : void 0, done: !0 };
120
+ }
121
+ }, __read$1 = function(o, n2) {
122
+ var m = typeof Symbol == "function" && o[Symbol.iterator];
123
+ if (!m)
124
+ return o;
125
+ var i = m.call(o), r2, ar = [], e;
126
+ try {
127
+ for (; (n2 === void 0 || n2-- > 0) && !(r2 = i.next()).done; )
128
+ ar.push(r2.value);
129
+ } catch (error) {
130
+ e = { error };
131
+ } finally {
132
+ try {
133
+ r2 && !r2.done && (m = i.return) && m.call(i);
134
+ } finally {
135
+ if (e)
136
+ throw e.error;
137
+ }
138
+ }
139
+ return ar;
140
+ }, __spreadArray$1 = function(to, from, pack) {
141
+ if (pack || arguments.length === 2)
142
+ for (var i = 0, l = from.length, ar; i < l; i++)
143
+ (ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
144
+ return to.concat(ar || Array.prototype.slice.call(from));
145
+ }, __values = function(o) {
146
+ var s = typeof Symbol == "function" && Symbol.iterator, m = s && o[s], i = 0;
147
+ if (m)
148
+ return m.call(o);
149
+ if (o && typeof o.length == "number")
150
+ return {
151
+ next: function() {
152
+ return o && i >= o.length && (o = void 0), { value: o && o[i++], done: !o };
153
+ }
154
+ };
155
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
156
+ }, HeapAsync = (
157
+ /** @class */
158
+ function() {
159
+ function HeapAsync2(compare) {
160
+ compare === void 0 && (compare = HeapAsync2.minComparator);
161
+ var _this = this;
162
+ this.compare = compare, this.heapArray = [], this._limit = 0, this.offer = this.add, this.element = this.peek, this.poll = this.pop, this._invertedCompare = function(a, b) {
163
+ return _this.compare(a, b).then(function(res) {
164
+ return -1 * res;
165
+ });
166
+ };
167
+ }
168
+ return HeapAsync2.getChildrenIndexOf = function(idx) {
169
+ return [idx * 2 + 1, idx * 2 + 2];
170
+ }, HeapAsync2.getParentIndexOf = function(idx) {
171
+ if (idx <= 0)
172
+ return -1;
173
+ var whichChildren = idx % 2 ? 1 : 2;
174
+ return Math.floor((idx - whichChildren) / 2);
175
+ }, HeapAsync2.getSiblingIndexOf = function(idx) {
176
+ if (idx <= 0)
177
+ return -1;
178
+ var whichChildren = idx % 2 ? 1 : -1;
179
+ return idx + whichChildren;
180
+ }, HeapAsync2.minComparator = function(a, b) {
181
+ return __awaiter(this, void 0, void 0, function() {
182
+ return __generator$1(this, function(_a) {
183
+ return a > b ? [2, 1] : a < b ? [2, -1] : [2, 0];
184
+ });
185
+ });
186
+ }, HeapAsync2.maxComparator = function(a, b) {
187
+ return __awaiter(this, void 0, void 0, function() {
188
+ return __generator$1(this, function(_a) {
189
+ return b > a ? [2, 1] : b < a ? [2, -1] : [2, 0];
190
+ });
191
+ });
192
+ }, HeapAsync2.minComparatorNumber = function(a, b) {
193
+ return __awaiter(this, void 0, void 0, function() {
194
+ return __generator$1(this, function(_a) {
195
+ return [2, a - b];
196
+ });
197
+ });
198
+ }, HeapAsync2.maxComparatorNumber = function(a, b) {
199
+ return __awaiter(this, void 0, void 0, function() {
200
+ return __generator$1(this, function(_a) {
201
+ return [2, b - a];
202
+ });
203
+ });
204
+ }, HeapAsync2.defaultIsEqual = function(a, b) {
205
+ return __awaiter(this, void 0, void 0, function() {
206
+ return __generator$1(this, function(_a) {
207
+ return [2, a === b];
208
+ });
209
+ });
210
+ }, HeapAsync2.print = function(heap) {
211
+ function deep(i2) {
212
+ var pi = HeapAsync2.getParentIndexOf(i2);
213
+ return Math.floor(Math.log2(pi + 1));
214
+ }
215
+ function repeat(str, times) {
216
+ for (var out = ""; times > 0; --times)
217
+ out += str;
218
+ return out;
219
+ }
220
+ for (var node = 0, lines = [], maxLines = deep(heap.length - 1) + 2, maxLength = 0; node < heap.length; ) {
221
+ var i = deep(node) + 1;
222
+ node === 0 && (i = 0);
223
+ var nodeText = String(heap.get(node));
224
+ nodeText.length > maxLength && (maxLength = nodeText.length), lines[i] = lines[i] || [], lines[i].push(nodeText), node += 1;
225
+ }
226
+ return lines.map(function(line, i2) {
227
+ var times = Math.pow(2, maxLines - i2) - 1;
228
+ return repeat(" ", Math.floor(times / 2) * maxLength) + line.map(function(el) {
229
+ var half = (maxLength - el.length) / 2;
230
+ return repeat(" ", Math.ceil(half)) + el + repeat(" ", Math.floor(half));
231
+ }).join(repeat(" ", times * maxLength));
232
+ }).join(`
233
+ `);
234
+ }, HeapAsync2.heapify = function(arr, compare) {
235
+ return __awaiter(this, void 0, void 0, function() {
236
+ var heap;
237
+ return __generator$1(this, function(_a) {
238
+ switch (_a.label) {
239
+ case 0:
240
+ return heap = new HeapAsync2(compare), heap.heapArray = arr, [4, heap.init()];
241
+ case 1:
242
+ return _a.sent(), [2, heap];
243
+ }
244
+ });
245
+ });
246
+ }, HeapAsync2.heappop = function(heapArr, compare) {
247
+ var heap = new HeapAsync2(compare);
248
+ return heap.heapArray = heapArr, heap.pop();
249
+ }, HeapAsync2.heappush = function(heapArr, item, compare) {
250
+ return __awaiter(this, void 0, void 0, function() {
251
+ var heap;
252
+ return __generator$1(this, function(_a) {
253
+ switch (_a.label) {
254
+ case 0:
255
+ return heap = new HeapAsync2(compare), heap.heapArray = heapArr, [4, heap.push(item)];
256
+ case 1:
257
+ return _a.sent(), [
258
+ 2
259
+ /*return*/
260
+ ];
261
+ }
262
+ });
263
+ });
264
+ }, HeapAsync2.heappushpop = function(heapArr, item, compare) {
265
+ var heap = new HeapAsync2(compare);
266
+ return heap.heapArray = heapArr, heap.pushpop(item);
267
+ }, HeapAsync2.heapreplace = function(heapArr, item, compare) {
268
+ var heap = new HeapAsync2(compare);
269
+ return heap.heapArray = heapArr, heap.replace(item);
270
+ }, HeapAsync2.heaptop = function(heapArr, n2, compare) {
271
+ n2 === void 0 && (n2 = 1);
272
+ var heap = new HeapAsync2(compare);
273
+ return heap.heapArray = heapArr, heap.top(n2);
274
+ }, HeapAsync2.heapbottom = function(heapArr, n2, compare) {
275
+ n2 === void 0 && (n2 = 1);
276
+ var heap = new HeapAsync2(compare);
277
+ return heap.heapArray = heapArr, heap.bottom(n2);
278
+ }, HeapAsync2.nlargest = function(n2, iterable, compare) {
279
+ return __awaiter(this, void 0, void 0, function() {
280
+ var heap;
281
+ return __generator$1(this, function(_a) {
282
+ switch (_a.label) {
283
+ case 0:
284
+ return heap = new HeapAsync2(compare), heap.heapArray = __spreadArray$1([], __read$1(iterable), !1), [4, heap.init()];
285
+ case 1:
286
+ return _a.sent(), [2, heap.top(n2)];
287
+ }
288
+ });
289
+ });
290
+ }, HeapAsync2.nsmallest = function(n2, iterable, compare) {
291
+ return __awaiter(this, void 0, void 0, function() {
292
+ var heap;
293
+ return __generator$1(this, function(_a) {
294
+ switch (_a.label) {
295
+ case 0:
296
+ return heap = new HeapAsync2(compare), heap.heapArray = __spreadArray$1([], __read$1(iterable), !1), [4, heap.init()];
297
+ case 1:
298
+ return _a.sent(), [2, heap.bottom(n2)];
299
+ }
300
+ });
301
+ });
302
+ }, HeapAsync2.prototype.add = function(element) {
303
+ return __awaiter(this, void 0, void 0, function() {
304
+ return __generator$1(this, function(_a) {
305
+ switch (_a.label) {
306
+ case 0:
307
+ return [4, this._sortNodeUp(this.heapArray.push(element) - 1)];
308
+ case 1:
309
+ return _a.sent(), this._applyLimit(), [2, !0];
310
+ }
311
+ });
312
+ });
313
+ }, HeapAsync2.prototype.addAll = function(elements) {
314
+ return __awaiter(this, void 0, void 0, function() {
315
+ var i, l, _a;
316
+ return __generator$1(this, function(_b) {
317
+ switch (_b.label) {
318
+ case 0:
319
+ i = this.length, (_a = this.heapArray).push.apply(_a, __spreadArray$1([], __read$1(elements), !1)), l = this.length, _b.label = 1;
320
+ case 1:
321
+ return i < l ? [4, this._sortNodeUp(i)] : [3, 4];
322
+ case 2:
323
+ _b.sent(), _b.label = 3;
324
+ case 3:
325
+ return ++i, [3, 1];
326
+ case 4:
327
+ return this._applyLimit(), [2, !0];
328
+ }
329
+ });
330
+ });
331
+ }, HeapAsync2.prototype.bottom = function(n2) {
332
+ return n2 === void 0 && (n2 = 1), __awaiter(this, void 0, void 0, function() {
333
+ return __generator$1(this, function(_a) {
334
+ return this.heapArray.length === 0 || n2 <= 0 ? [2, []] : this.heapArray.length === 1 ? [2, [this.heapArray[0]]] : n2 >= this.heapArray.length ? [2, __spreadArray$1([], __read$1(this.heapArray), !1)] : [2, this._bottomN_push(~~n2)];
335
+ });
336
+ });
337
+ }, HeapAsync2.prototype.check = function() {
338
+ return __awaiter(this, void 0, void 0, function() {
339
+ var j, el, children, children_1, children_1_1, ch, e_1_1, e_1, _a;
340
+ return __generator$1(this, function(_b) {
341
+ switch (_b.label) {
342
+ case 0:
343
+ j = 0, _b.label = 1;
344
+ case 1:
345
+ if (!(j < this.heapArray.length))
346
+ return [3, 10];
347
+ el = this.heapArray[j], children = this.getChildrenOf(j), _b.label = 2;
348
+ case 2:
349
+ _b.trys.push([2, 7, 8, 9]), children_1 = (e_1 = void 0, __values(children)), children_1_1 = children_1.next(), _b.label = 3;
350
+ case 3:
351
+ return children_1_1.done ? [3, 6] : (ch = children_1_1.value, [4, this.compare(el, ch)]);
352
+ case 4:
353
+ if (_b.sent() > 0)
354
+ return [2, el];
355
+ _b.label = 5;
356
+ case 5:
357
+ return children_1_1 = children_1.next(), [3, 3];
358
+ case 6:
359
+ return [3, 9];
360
+ case 7:
361
+ return e_1_1 = _b.sent(), e_1 = { error: e_1_1 }, [3, 9];
362
+ case 8:
363
+ try {
364
+ children_1_1 && !children_1_1.done && (_a = children_1.return) && _a.call(children_1);
365
+ } finally {
366
+ if (e_1)
367
+ throw e_1.error;
368
+ }
369
+ return [
370
+ 7
371
+ /*endfinally*/
372
+ ];
373
+ case 9:
374
+ return ++j, [3, 1];
375
+ case 10:
376
+ return [
377
+ 2
378
+ /*return*/
379
+ ];
380
+ }
381
+ });
382
+ });
383
+ }, HeapAsync2.prototype.clear = function() {
384
+ this.heapArray = [];
385
+ }, HeapAsync2.prototype.clone = function() {
386
+ var cloned = new HeapAsync2(this.comparator());
387
+ return cloned.heapArray = this.toArray(), cloned._limit = this._limit, cloned;
388
+ }, HeapAsync2.prototype.comparator = function() {
389
+ return this.compare;
390
+ }, HeapAsync2.prototype.contains = function(o, fn) {
391
+ return fn === void 0 && (fn = HeapAsync2.defaultIsEqual), __awaiter(this, void 0, void 0, function() {
392
+ var _a, _b, el, e_2_1, e_2, _c;
393
+ return __generator$1(this, function(_d) {
394
+ switch (_d.label) {
395
+ case 0:
396
+ _d.trys.push([0, 5, 6, 7]), _a = __values(this.heapArray), _b = _a.next(), _d.label = 1;
397
+ case 1:
398
+ return _b.done ? [3, 4] : (el = _b.value, [4, fn(el, o)]);
399
+ case 2:
400
+ if (_d.sent())
401
+ return [2, !0];
402
+ _d.label = 3;
403
+ case 3:
404
+ return _b = _a.next(), [3, 1];
405
+ case 4:
406
+ return [3, 7];
407
+ case 5:
408
+ return e_2_1 = _d.sent(), e_2 = { error: e_2_1 }, [3, 7];
409
+ case 6:
410
+ try {
411
+ _b && !_b.done && (_c = _a.return) && _c.call(_a);
412
+ } finally {
413
+ if (e_2)
414
+ throw e_2.error;
415
+ }
416
+ return [
417
+ 7
418
+ /*endfinally*/
419
+ ];
420
+ case 7:
421
+ return [2, !1];
422
+ }
423
+ });
424
+ });
425
+ }, HeapAsync2.prototype.init = function(array) {
426
+ return __awaiter(this, void 0, void 0, function() {
427
+ var i;
428
+ return __generator$1(this, function(_a) {
429
+ switch (_a.label) {
430
+ case 0:
431
+ array && (this.heapArray = __spreadArray$1([], __read$1(array), !1)), i = Math.floor(this.heapArray.length), _a.label = 1;
432
+ case 1:
433
+ return i >= 0 ? [4, this._sortNodeDown(i)] : [3, 4];
434
+ case 2:
435
+ _a.sent(), _a.label = 3;
436
+ case 3:
437
+ return --i, [3, 1];
438
+ case 4:
439
+ return this._applyLimit(), [
440
+ 2
441
+ /*return*/
442
+ ];
443
+ }
444
+ });
445
+ });
446
+ }, HeapAsync2.prototype.isEmpty = function() {
447
+ return this.length === 0;
448
+ }, HeapAsync2.prototype.leafs = function() {
449
+ if (this.heapArray.length === 0)
450
+ return [];
451
+ var pi = HeapAsync2.getParentIndexOf(this.heapArray.length - 1);
452
+ return this.heapArray.slice(pi + 1);
453
+ }, Object.defineProperty(HeapAsync2.prototype, "length", {
454
+ /**
455
+ * Length of the heap.
456
+ * @return {Number}
457
+ */
458
+ get: function() {
459
+ return this.heapArray.length;
460
+ },
461
+ enumerable: !1,
462
+ configurable: !0
463
+ }), Object.defineProperty(HeapAsync2.prototype, "limit", {
464
+ /**
465
+ * Get length limit of the heap.
466
+ * @return {Number}
467
+ */
468
+ get: function() {
469
+ return this._limit;
470
+ },
471
+ /**
472
+ * Set length limit of the heap.
473
+ * @return {Number}
474
+ */
475
+ set: function(_l) {
476
+ this._limit = ~~_l, this._applyLimit();
477
+ },
478
+ enumerable: !1,
479
+ configurable: !0
480
+ }), HeapAsync2.prototype.peek = function() {
481
+ return this.heapArray[0];
482
+ }, HeapAsync2.prototype.pop = function() {
483
+ return __awaiter(this, void 0, void 0, function() {
484
+ var last;
485
+ return __generator$1(this, function(_a) {
486
+ return last = this.heapArray.pop(), this.length > 0 && last !== void 0 ? [2, this.replace(last)] : [2, last];
487
+ });
488
+ });
489
+ }, HeapAsync2.prototype.push = function() {
490
+ for (var elements = [], _i = 0; _i < arguments.length; _i++)
491
+ elements[_i] = arguments[_i];
492
+ return __awaiter(this, void 0, void 0, function() {
493
+ return __generator$1(this, function(_a) {
494
+ return elements.length < 1 ? [2, !1] : elements.length === 1 ? [2, this.add(elements[0])] : [2, this.addAll(elements)];
495
+ });
496
+ });
497
+ }, HeapAsync2.prototype.pushpop = function(element) {
498
+ return __awaiter(this, void 0, void 0, function() {
499
+ var _a;
500
+ return __generator$1(this, function(_b) {
501
+ switch (_b.label) {
502
+ case 0:
503
+ return [4, this.compare(this.heapArray[0], element)];
504
+ case 1:
505
+ return _b.sent() < 0 ? (_a = __read$1([this.heapArray[0], element], 2), element = _a[0], this.heapArray[0] = _a[1], [4, this._sortNodeDown(0)]) : [3, 3];
506
+ case 2:
507
+ _b.sent(), _b.label = 3;
508
+ case 3:
509
+ return [2, element];
510
+ }
511
+ });
512
+ });
513
+ }, HeapAsync2.prototype.remove = function(o, fn) {
514
+ return fn === void 0 && (fn = HeapAsync2.defaultIsEqual), __awaiter(this, void 0, void 0, function() {
515
+ var idx, i;
516
+ return __generator$1(this, function(_a) {
517
+ switch (_a.label) {
518
+ case 0:
519
+ return this.length > 0 ? o !== void 0 ? [3, 2] : [4, this.pop()] : [3, 13];
520
+ case 1:
521
+ return _a.sent(), [2, !0];
522
+ case 2:
523
+ idx = -1, i = 0, _a.label = 3;
524
+ case 3:
525
+ return i < this.heapArray.length ? [4, fn(this.heapArray[i], o)] : [3, 6];
526
+ case 4:
527
+ if (_a.sent())
528
+ return idx = i, [3, 6];
529
+ _a.label = 5;
530
+ case 5:
531
+ return ++i, [3, 3];
532
+ case 6:
533
+ return idx >= 0 ? idx !== 0 ? [3, 8] : [4, this.pop()] : [3, 13];
534
+ case 7:
535
+ return _a.sent(), [3, 12];
536
+ case 8:
537
+ return idx !== this.length - 1 ? [3, 9] : (this.heapArray.pop(), [3, 12]);
538
+ case 9:
539
+ return this.heapArray.splice(idx, 1, this.heapArray.pop()), [4, this._sortNodeUp(idx)];
540
+ case 10:
541
+ return _a.sent(), [4, this._sortNodeDown(idx)];
542
+ case 11:
543
+ _a.sent(), _a.label = 12;
544
+ case 12:
545
+ return [2, !0];
546
+ case 13:
547
+ return [2, !1];
548
+ }
549
+ });
550
+ });
551
+ }, HeapAsync2.prototype.replace = function(element) {
552
+ return __awaiter(this, void 0, void 0, function() {
553
+ var peek;
554
+ return __generator$1(this, function(_a) {
555
+ switch (_a.label) {
556
+ case 0:
557
+ return peek = this.heapArray[0], this.heapArray[0] = element, [4, this._sortNodeDown(0)];
558
+ case 1:
559
+ return _a.sent(), [2, peek];
560
+ }
561
+ });
562
+ });
563
+ }, HeapAsync2.prototype.size = function() {
564
+ return this.length;
565
+ }, HeapAsync2.prototype.top = function(n2) {
566
+ return n2 === void 0 && (n2 = 1), __awaiter(this, void 0, void 0, function() {
567
+ return __generator$1(this, function(_a) {
568
+ return this.heapArray.length === 0 || n2 <= 0 ? [2, []] : this.heapArray.length === 1 || n2 === 1 ? [2, [this.heapArray[0]]] : n2 >= this.heapArray.length ? [2, __spreadArray$1([], __read$1(this.heapArray), !1)] : [2, this._topN_push(~~n2)];
569
+ });
570
+ });
571
+ }, HeapAsync2.prototype.toArray = function() {
572
+ return __spreadArray$1([], __read$1(this.heapArray), !1);
573
+ }, HeapAsync2.prototype.toString = function() {
574
+ return this.heapArray.toString();
575
+ }, HeapAsync2.prototype.get = function(i) {
576
+ return this.heapArray[i];
577
+ }, HeapAsync2.prototype.getChildrenOf = function(idx) {
578
+ var _this = this;
579
+ return HeapAsync2.getChildrenIndexOf(idx).map(function(i) {
580
+ return _this.heapArray[i];
581
+ }).filter(function(e) {
582
+ return e !== void 0;
583
+ });
584
+ }, HeapAsync2.prototype.getParentOf = function(idx) {
585
+ var pi = HeapAsync2.getParentIndexOf(idx);
586
+ return this.heapArray[pi];
587
+ }, HeapAsync2.prototype[Symbol.iterator] = function() {
588
+ return __generator$1(this, function(_a) {
589
+ switch (_a.label) {
590
+ case 0:
591
+ return this.length ? [4, this.pop()] : [3, 2];
592
+ case 1:
593
+ return _a.sent(), [3, 0];
594
+ case 2:
595
+ return [
596
+ 2
597
+ /*return*/
598
+ ];
599
+ }
600
+ });
601
+ }, HeapAsync2.prototype.iterator = function() {
602
+ return this;
603
+ }, HeapAsync2.prototype._applyLimit = function() {
604
+ if (this._limit && this._limit < this.heapArray.length)
605
+ for (var rm = this.heapArray.length - this._limit; rm; )
606
+ this.heapArray.pop(), --rm;
607
+ }, HeapAsync2.prototype._bottomN_push = function(n2) {
608
+ return __awaiter(this, void 0, void 0, function() {
609
+ var bottomHeap, startAt, parentStartAt, indices, i, arr, i;
610
+ return __generator$1(this, function(_a) {
611
+ switch (_a.label) {
612
+ case 0:
613
+ return bottomHeap = new HeapAsync2(this.compare), bottomHeap.limit = n2, bottomHeap.heapArray = this.heapArray.slice(-n2), [4, bottomHeap.init()];
614
+ case 1:
615
+ for (_a.sent(), startAt = this.heapArray.length - 1 - n2, parentStartAt = HeapAsync2.getParentIndexOf(startAt), indices = [], i = startAt; i > parentStartAt; --i)
616
+ indices.push(i);
617
+ arr = this.heapArray, _a.label = 2;
618
+ case 2:
619
+ return indices.length ? (i = indices.shift(), [4, this.compare(arr[i], bottomHeap.peek())]) : [3, 6];
620
+ case 3:
621
+ return _a.sent() > 0 ? [4, bottomHeap.replace(arr[i])] : [3, 5];
622
+ case 4:
623
+ _a.sent(), i % 2 && indices.push(HeapAsync2.getParentIndexOf(i)), _a.label = 5;
624
+ case 5:
625
+ return [3, 2];
626
+ case 6:
627
+ return [2, bottomHeap.toArray()];
628
+ }
629
+ });
630
+ });
631
+ }, HeapAsync2.prototype._moveNode = function(j, k) {
632
+ var _a;
633
+ _a = __read$1([this.heapArray[k], this.heapArray[j]], 2), this.heapArray[j] = _a[0], this.heapArray[k] = _a[1];
634
+ }, HeapAsync2.prototype._sortNodeDown = function(i) {
635
+ return __awaiter(this, void 0, void 0, function() {
636
+ var moveIt, self2, getPotentialParent, childrenIdx, bestChildIndex, j, bestChild, _a, _this = this;
637
+ return __generator$1(this, function(_b) {
638
+ switch (_b.label) {
639
+ case 0:
640
+ moveIt = i < this.heapArray.length - 1, self2 = this.heapArray[i], getPotentialParent = function(best, j2) {
641
+ return __awaiter(_this, void 0, void 0, function() {
642
+ var _a2;
643
+ return __generator$1(this, function(_b2) {
644
+ switch (_b2.label) {
645
+ case 0:
646
+ return _a2 = this.heapArray.length > j2, _a2 ? [4, this.compare(this.heapArray[j2], this.heapArray[best])] : [3, 2];
647
+ case 1:
648
+ _a2 = _b2.sent() < 0, _b2.label = 2;
649
+ case 2:
650
+ return _a2 && (best = j2), [2, best];
651
+ }
652
+ });
653
+ });
654
+ }, _b.label = 1;
655
+ case 1:
656
+ if (!moveIt)
657
+ return [3, 8];
658
+ childrenIdx = HeapAsync2.getChildrenIndexOf(i), bestChildIndex = childrenIdx[0], j = 1, _b.label = 2;
659
+ case 2:
660
+ return j < childrenIdx.length ? [4, getPotentialParent(bestChildIndex, childrenIdx[j])] : [3, 5];
661
+ case 3:
662
+ bestChildIndex = _b.sent(), _b.label = 4;
663
+ case 4:
664
+ return ++j, [3, 2];
665
+ case 5:
666
+ return bestChild = this.heapArray[bestChildIndex], _a = typeof bestChild < "u", _a ? [4, this.compare(self2, bestChild)] : [3, 7];
667
+ case 6:
668
+ _a = _b.sent() > 0, _b.label = 7;
669
+ case 7:
670
+ return _a ? (this._moveNode(i, bestChildIndex), i = bestChildIndex) : moveIt = !1, [3, 1];
671
+ case 8:
672
+ return [
673
+ 2
674
+ /*return*/
675
+ ];
676
+ }
677
+ });
678
+ });
679
+ }, HeapAsync2.prototype._sortNodeUp = function(i) {
680
+ return __awaiter(this, void 0, void 0, function() {
681
+ var moveIt, pi, _a;
682
+ return __generator$1(this, function(_b) {
683
+ switch (_b.label) {
684
+ case 0:
685
+ moveIt = i > 0, _b.label = 1;
686
+ case 1:
687
+ return moveIt ? (pi = HeapAsync2.getParentIndexOf(i), _a = pi >= 0, _a ? [4, this.compare(this.heapArray[pi], this.heapArray[i])] : [3, 3]) : [3, 4];
688
+ case 2:
689
+ _a = _b.sent() > 0, _b.label = 3;
690
+ case 3:
691
+ return _a ? (this._moveNode(i, pi), i = pi) : moveIt = !1, [3, 1];
692
+ case 4:
693
+ return [
694
+ 2
695
+ /*return*/
696
+ ];
697
+ }
698
+ });
699
+ });
700
+ }, HeapAsync2.prototype._topN_push = function(n2) {
701
+ return __awaiter(this, void 0, void 0, function() {
702
+ var topHeap, indices, arr, i;
703
+ return __generator$1(this, function(_a) {
704
+ switch (_a.label) {
705
+ case 0:
706
+ topHeap = new HeapAsync2(this._invertedCompare), topHeap.limit = n2, indices = [0], arr = this.heapArray, _a.label = 1;
707
+ case 1:
708
+ return indices.length ? (i = indices.shift(), i < arr.length ? topHeap.length < n2 ? [4, topHeap.push(arr[i])] : [3, 3] : [3, 6]) : [3, 7];
709
+ case 2:
710
+ return _a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), [3, 6];
711
+ case 3:
712
+ return [4, this.compare(arr[i], topHeap.peek())];
713
+ case 4:
714
+ return _a.sent() < 0 ? [4, topHeap.replace(arr[i])] : [3, 6];
715
+ case 5:
716
+ _a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), _a.label = 6;
717
+ case 6:
718
+ return [3, 1];
719
+ case 7:
720
+ return [2, topHeap.toArray()];
721
+ }
722
+ });
723
+ });
724
+ }, HeapAsync2.prototype._topN_fill = function(n2) {
725
+ return __awaiter(this, void 0, void 0, function() {
726
+ var heapArray, topHeap, branch, indices, i, i;
727
+ return __generator$1(this, function(_a) {
728
+ switch (_a.label) {
729
+ case 0:
730
+ return heapArray = this.heapArray, topHeap = new HeapAsync2(this._invertedCompare), topHeap.limit = n2, topHeap.heapArray = heapArray.slice(0, n2), [4, topHeap.init()];
731
+ case 1:
732
+ for (_a.sent(), branch = HeapAsync2.getParentIndexOf(n2 - 1) + 1, indices = [], i = branch; i < n2; ++i)
733
+ indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i).filter(function(l) {
734
+ return l < heapArray.length;
735
+ })), !1));
736
+ (n2 - 1) % 2 && indices.push(n2), _a.label = 2;
737
+ case 2:
738
+ return indices.length ? (i = indices.shift(), i < heapArray.length ? [4, this.compare(heapArray[i], topHeap.peek())] : [3, 5]) : [3, 6];
739
+ case 3:
740
+ return _a.sent() < 0 ? [4, topHeap.replace(heapArray[i])] : [3, 5];
741
+ case 4:
742
+ _a.sent(), indices.push.apply(indices, __spreadArray$1([], __read$1(HeapAsync2.getChildrenIndexOf(i)), !1)), _a.label = 5;
743
+ case 5:
744
+ return [3, 2];
745
+ case 6:
746
+ return [2, topHeap.toArray()];
747
+ }
748
+ });
749
+ });
750
+ }, HeapAsync2.prototype._topN_heap = function(n2) {
751
+ return __awaiter(this, void 0, void 0, function() {
752
+ var topHeap, result, i, _a, _b;
753
+ return __generator$1(this, function(_c) {
754
+ switch (_c.label) {
755
+ case 0:
756
+ topHeap = this.clone(), result = [], i = 0, _c.label = 1;
757
+ case 1:
758
+ return i < n2 ? (_b = (_a = result).push, [4, topHeap.pop()]) : [3, 4];
759
+ case 2:
760
+ _b.apply(_a, [_c.sent()]), _c.label = 3;
761
+ case 3:
762
+ return ++i, [3, 1];
763
+ case 4:
764
+ return [2, result];
765
+ }
766
+ });
767
+ });
768
+ }, HeapAsync2.prototype._topIdxOf = function(list) {
769
+ return __awaiter(this, void 0, void 0, function() {
770
+ var idx, top, i, comp;
771
+ return __generator$1(this, function(_a) {
772
+ switch (_a.label) {
773
+ case 0:
774
+ if (!list.length)
775
+ return [2, -1];
776
+ idx = 0, top = list[idx], i = 1, _a.label = 1;
777
+ case 1:
778
+ return i < list.length ? [4, this.compare(list[i], top)] : [3, 4];
779
+ case 2:
780
+ comp = _a.sent(), comp < 0 && (idx = i, top = list[i]), _a.label = 3;
781
+ case 3:
782
+ return ++i, [3, 1];
783
+ case 4:
784
+ return [2, idx];
785
+ }
786
+ });
787
+ });
788
+ }, HeapAsync2.prototype._topOf = function() {
789
+ for (var list = [], _i = 0; _i < arguments.length; _i++)
790
+ list[_i] = arguments[_i];
791
+ return __awaiter(this, void 0, void 0, function() {
792
+ var heap;
793
+ return __generator$1(this, function(_a) {
794
+ switch (_a.label) {
795
+ case 0:
796
+ return heap = new HeapAsync2(this.compare), [4, heap.init(list)];
797
+ case 1:
798
+ return _a.sent(), [2, heap.peek()];
799
+ }
800
+ });
801
+ });
802
+ }, HeapAsync2;
803
+ }()
804
+ ), __generator = function(thisArg, body) {
805
+ var _ = { label: 0, sent: function() {
806
+ if (t[0] & 1)
807
+ throw t[1];
808
+ return t[1];
809
+ }, trys: [], ops: [] }, f, y, t, g;
810
+ return g = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol == "function" && (g[Symbol.iterator] = function() {
811
+ return this;
812
+ }), g;
813
+ function verb(n2) {
814
+ return function(v) {
815
+ return step([n2, v]);
816
+ };
817
+ }
818
+ function step(op) {
819
+ if (f)
820
+ throw new TypeError("Generator is already executing.");
821
+ for (; g && (g = 0, op[0] && (_ = 0)), _; )
822
+ try {
823
+ if (f = 1, y && (t = op[0] & 2 ? y.return : op[0] ? y.throw || ((t = y.return) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
824
+ return t;
825
+ switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
826
+ case 0:
827
+ case 1:
828
+ t = op;
829
+ break;
830
+ case 4:
831
+ return _.label++, { value: op[1], done: !1 };
832
+ case 5:
833
+ _.label++, y = op[1], op = [0];
834
+ continue;
835
+ case 7:
836
+ op = _.ops.pop(), _.trys.pop();
837
+ continue;
838
+ default:
839
+ if (t = _.trys, !(t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
840
+ _ = 0;
841
+ continue;
842
+ }
843
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
844
+ _.label = op[1];
845
+ break;
846
+ }
847
+ if (op[0] === 6 && _.label < t[1]) {
848
+ _.label = t[1], t = op;
849
+ break;
850
+ }
851
+ if (t && _.label < t[2]) {
852
+ _.label = t[2], _.ops.push(op);
853
+ break;
854
+ }
855
+ t[2] && _.ops.pop(), _.trys.pop();
856
+ continue;
857
+ }
858
+ op = body.call(thisArg, _);
859
+ } catch (e) {
860
+ op = [6, e], y = 0;
861
+ } finally {
862
+ f = t = 0;
863
+ }
864
+ if (op[0] & 5)
865
+ throw op[1];
866
+ return { value: op[0] ? op[1] : void 0, done: !0 };
867
+ }
868
+ }, __read = function(o, n2) {
869
+ var m = typeof Symbol == "function" && o[Symbol.iterator];
870
+ if (!m)
871
+ return o;
872
+ var i = m.call(o), r2, ar = [], e;
873
+ try {
874
+ for (; (n2 === void 0 || n2-- > 0) && !(r2 = i.next()).done; )
875
+ ar.push(r2.value);
876
+ } catch (error) {
877
+ e = { error };
878
+ } finally {
879
+ try {
880
+ r2 && !r2.done && (m = i.return) && m.call(i);
881
+ } finally {
882
+ if (e)
883
+ throw e.error;
884
+ }
885
+ }
886
+ return ar;
887
+ }, __spreadArray = function(to, from, pack) {
888
+ if (pack || arguments.length === 2)
889
+ for (var i = 0, l = from.length, ar; i < l; i++)
890
+ (ar || !(i in from)) && (ar || (ar = Array.prototype.slice.call(from, 0, i)), ar[i] = from[i]);
891
+ return to.concat(ar || Array.prototype.slice.call(from));
892
+ }, toInt = function(n2) {
893
+ return ~~n2;
894
+ }, Heap2 = (
895
+ /** @class */
896
+ function() {
897
+ function Heap3(compare) {
898
+ compare === void 0 && (compare = Heap3.minComparator);
899
+ var _this = this;
900
+ this.compare = compare, this.heapArray = [], this._limit = 0, this.offer = this.add, this.element = this.peek, this.poll = this.pop, this.removeAll = this.clear, this._invertedCompare = function(a, b) {
901
+ return -1 * _this.compare(a, b);
902
+ };
903
+ }
904
+ return Heap3.getChildrenIndexOf = function(idx) {
905
+ return [idx * 2 + 1, idx * 2 + 2];
906
+ }, Heap3.getParentIndexOf = function(idx) {
907
+ if (idx <= 0)
908
+ return -1;
909
+ var whichChildren = idx % 2 ? 1 : 2;
910
+ return Math.floor((idx - whichChildren) / 2);
911
+ }, Heap3.getSiblingIndexOf = function(idx) {
912
+ if (idx <= 0)
913
+ return -1;
914
+ var whichChildren = idx % 2 ? 1 : -1;
915
+ return idx + whichChildren;
916
+ }, Heap3.minComparator = function(a, b) {
917
+ return a > b ? 1 : a < b ? -1 : 0;
918
+ }, Heap3.maxComparator = function(a, b) {
919
+ return b > a ? 1 : b < a ? -1 : 0;
920
+ }, Heap3.minComparatorNumber = function(a, b) {
921
+ return a - b;
922
+ }, Heap3.maxComparatorNumber = function(a, b) {
923
+ return b - a;
924
+ }, Heap3.defaultIsEqual = function(a, b) {
925
+ return a === b;
926
+ }, Heap3.print = function(heap) {
927
+ function deep(i2) {
928
+ var pi = Heap3.getParentIndexOf(i2);
929
+ return Math.floor(Math.log2(pi + 1));
930
+ }
931
+ function repeat(str, times) {
932
+ for (var out = ""; times > 0; --times)
933
+ out += str;
934
+ return out;
935
+ }
936
+ for (var node = 0, lines = [], maxLines = deep(heap.length - 1) + 2, maxLength = 0; node < heap.length; ) {
937
+ var i = deep(node) + 1;
938
+ node === 0 && (i = 0);
939
+ var nodeText = String(heap.get(node));
940
+ nodeText.length > maxLength && (maxLength = nodeText.length), lines[i] = lines[i] || [], lines[i].push(nodeText), node += 1;
941
+ }
942
+ return lines.map(function(line, i2) {
943
+ var times = Math.pow(2, maxLines - i2) - 1;
944
+ return repeat(" ", Math.floor(times / 2) * maxLength) + line.map(function(el) {
945
+ var half = (maxLength - el.length) / 2;
946
+ return repeat(" ", Math.ceil(half)) + el + repeat(" ", Math.floor(half));
947
+ }).join(repeat(" ", times * maxLength));
948
+ }).join(`
949
+ `);
950
+ }, Heap3.heapify = function(arr, compare) {
951
+ var heap = new Heap3(compare);
952
+ return heap.heapArray = arr, heap.init(), heap;
953
+ }, Heap3.heappop = function(heapArr, compare) {
954
+ var heap = new Heap3(compare);
955
+ return heap.heapArray = heapArr, heap.pop();
956
+ }, Heap3.heappush = function(heapArr, item, compare) {
957
+ var heap = new Heap3(compare);
958
+ heap.heapArray = heapArr, heap.push(item);
959
+ }, Heap3.heappushpop = function(heapArr, item, compare) {
960
+ var heap = new Heap3(compare);
961
+ return heap.heapArray = heapArr, heap.pushpop(item);
962
+ }, Heap3.heapreplace = function(heapArr, item, compare) {
963
+ var heap = new Heap3(compare);
964
+ return heap.heapArray = heapArr, heap.replace(item);
965
+ }, Heap3.heaptop = function(heapArr, n2, compare) {
966
+ n2 === void 0 && (n2 = 1);
967
+ var heap = new Heap3(compare);
968
+ return heap.heapArray = heapArr, heap.top(n2);
969
+ }, Heap3.heapbottom = function(heapArr, n2, compare) {
970
+ n2 === void 0 && (n2 = 1);
971
+ var heap = new Heap3(compare);
972
+ return heap.heapArray = heapArr, heap.bottom(n2);
973
+ }, Heap3.nlargest = function(n2, iterable, compare) {
974
+ var heap = new Heap3(compare);
975
+ return heap.heapArray = __spreadArray([], __read(iterable), !1), heap.init(), heap.top(n2);
976
+ }, Heap3.nsmallest = function(n2, iterable, compare) {
977
+ var heap = new Heap3(compare);
978
+ return heap.heapArray = __spreadArray([], __read(iterable), !1), heap.init(), heap.bottom(n2);
979
+ }, Heap3.prototype.add = function(element) {
980
+ return this._sortNodeUp(this.heapArray.push(element) - 1), this._applyLimit(), !0;
981
+ }, Heap3.prototype.addAll = function(elements) {
982
+ var _a, i = this.length;
983
+ (_a = this.heapArray).push.apply(_a, __spreadArray([], __read(elements), !1));
984
+ for (var l = this.length; i < l; ++i)
985
+ this._sortNodeUp(i);
986
+ return this._applyLimit(), !0;
987
+ }, Heap3.prototype.bottom = function(n2) {
988
+ return n2 === void 0 && (n2 = 1), this.heapArray.length === 0 || n2 <= 0 ? [] : this.heapArray.length === 1 ? [this.heapArray[0]] : n2 >= this.heapArray.length ? __spreadArray([], __read(this.heapArray), !1) : this._bottomN_push(~~n2);
989
+ }, Heap3.prototype.check = function() {
990
+ var _this = this;
991
+ return this.heapArray.find(function(el, j) {
992
+ return !!_this.getChildrenOf(j).find(function(ch) {
993
+ return _this.compare(el, ch) > 0;
994
+ });
995
+ });
996
+ }, Heap3.prototype.clear = function() {
997
+ this.heapArray = [];
998
+ }, Heap3.prototype.clone = function() {
999
+ var cloned = new Heap3(this.comparator());
1000
+ return cloned.heapArray = this.toArray(), cloned._limit = this._limit, cloned;
1001
+ }, Heap3.prototype.comparator = function() {
1002
+ return this.compare;
1003
+ }, Heap3.prototype.contains = function(o, callbackFn) {
1004
+ return callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.indexOf(o, callbackFn) !== -1;
1005
+ }, Heap3.prototype.init = function(array) {
1006
+ array && (this.heapArray = __spreadArray([], __read(array), !1));
1007
+ for (var i = Math.floor(this.heapArray.length); i >= 0; --i)
1008
+ this._sortNodeDown(i);
1009
+ this._applyLimit();
1010
+ }, Heap3.prototype.isEmpty = function() {
1011
+ return this.length === 0;
1012
+ }, Heap3.prototype.indexOf = function(element, callbackFn) {
1013
+ if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.heapArray.length === 0)
1014
+ return -1;
1015
+ for (var indexes = [], currentIndex = 0; currentIndex < this.heapArray.length; ) {
1016
+ var currentElement = this.heapArray[currentIndex];
1017
+ if (callbackFn(currentElement, element))
1018
+ return currentIndex;
1019
+ this.compare(currentElement, element) <= 0 && indexes.push.apply(indexes, __spreadArray([], __read(Heap3.getChildrenIndexOf(currentIndex)), !1)), currentIndex = indexes.shift() || this.heapArray.length;
1020
+ }
1021
+ return -1;
1022
+ }, Heap3.prototype.indexOfEvery = function(element, callbackFn) {
1023
+ if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.heapArray.length === 0)
1024
+ return [];
1025
+ for (var indexes = [], foundIndexes = [], currentIndex = 0; currentIndex < this.heapArray.length; ) {
1026
+ var currentElement = this.heapArray[currentIndex];
1027
+ callbackFn(currentElement, element) ? (foundIndexes.push(currentIndex), indexes.push.apply(indexes, __spreadArray([], __read(Heap3.getChildrenIndexOf(currentIndex)), !1))) : this.compare(currentElement, element) <= 0 && indexes.push.apply(indexes, __spreadArray([], __read(Heap3.getChildrenIndexOf(currentIndex)), !1)), currentIndex = indexes.shift() || this.heapArray.length;
1028
+ }
1029
+ return foundIndexes;
1030
+ }, Heap3.prototype.leafs = function() {
1031
+ if (this.heapArray.length === 0)
1032
+ return [];
1033
+ var pi = Heap3.getParentIndexOf(this.heapArray.length - 1);
1034
+ return this.heapArray.slice(pi + 1);
1035
+ }, Object.defineProperty(Heap3.prototype, "length", {
1036
+ /**
1037
+ * Length of the heap. Aliases: {@link size}.
1038
+ * @return {Number}
1039
+ * @see size
1040
+ */
1041
+ get: function() {
1042
+ return this.heapArray.length;
1043
+ },
1044
+ enumerable: !1,
1045
+ configurable: !0
1046
+ }), Object.defineProperty(Heap3.prototype, "limit", {
1047
+ /**
1048
+ * Get length limit of the heap.
1049
+ * Use {@link setLimit} or {@link limit} to set the limit.
1050
+ * @return {Number}
1051
+ * @see setLimit
1052
+ */
1053
+ get: function() {
1054
+ return this._limit;
1055
+ },
1056
+ /**
1057
+ * Set length limit of the heap. Same as using {@link setLimit}.
1058
+ * @description If the heap is longer than the limit, the needed amount of leafs are removed.
1059
+ * @param {Number} _l Limit, defaults to 0 (no limit). Negative, Infinity, or NaN values set the limit to 0.
1060
+ * @see setLimit
1061
+ */
1062
+ set: function(_l) {
1063
+ _l < 0 || isNaN(_l) ? this._limit = 0 : this._limit = ~~_l, this._applyLimit();
1064
+ },
1065
+ enumerable: !1,
1066
+ configurable: !0
1067
+ }), Heap3.prototype.setLimit = function(_l) {
1068
+ return this.limit = _l, _l < 0 || isNaN(_l) ? NaN : this._limit;
1069
+ }, Heap3.prototype.peek = function() {
1070
+ return this.heapArray[0];
1071
+ }, Heap3.prototype.pop = function() {
1072
+ var last = this.heapArray.pop();
1073
+ return this.length > 0 && last !== void 0 ? this.replace(last) : last;
1074
+ }, Heap3.prototype.push = function() {
1075
+ for (var elements = [], _i = 0; _i < arguments.length; _i++)
1076
+ elements[_i] = arguments[_i];
1077
+ return elements.length < 1 ? !1 : elements.length === 1 ? this.add(elements[0]) : this.addAll(elements);
1078
+ }, Heap3.prototype.pushpop = function(element) {
1079
+ var _a;
1080
+ return this.compare(this.heapArray[0], element) < 0 && (_a = __read([this.heapArray[0], element], 2), element = _a[0], this.heapArray[0] = _a[1], this._sortNodeDown(0)), element;
1081
+ }, Heap3.prototype.remove = function(o, callbackFn) {
1082
+ if (callbackFn === void 0 && (callbackFn = Heap3.defaultIsEqual), this.length > 0) {
1083
+ if (o === void 0)
1084
+ return this.pop(), !0;
1085
+ var idx = this.indexOf(o, callbackFn);
1086
+ if (idx >= 0)
1087
+ return idx === 0 ? this.pop() : idx === this.length - 1 ? this.heapArray.pop() : (this.heapArray.splice(idx, 1, this.heapArray.pop()), this._sortNodeUp(idx), this._sortNodeDown(idx)), !0;
1088
+ }
1089
+ return !1;
1090
+ }, Heap3.prototype.replace = function(element) {
1091
+ var peek = this.heapArray[0];
1092
+ return this.heapArray[0] = element, this._sortNodeDown(0), peek;
1093
+ }, Heap3.prototype.size = function() {
1094
+ return this.length;
1095
+ }, Heap3.prototype.top = function(n2) {
1096
+ return n2 === void 0 && (n2 = 1), this.heapArray.length === 0 || n2 <= 0 ? [] : this.heapArray.length === 1 || n2 === 1 ? [this.heapArray[0]] : n2 >= this.heapArray.length ? __spreadArray([], __read(this.heapArray), !1) : this._topN_push(~~n2);
1097
+ }, Heap3.prototype.toArray = function() {
1098
+ return __spreadArray([], __read(this.heapArray), !1);
1099
+ }, Heap3.prototype.toString = function() {
1100
+ return this.heapArray.toString();
1101
+ }, Heap3.prototype.get = function(i) {
1102
+ return this.heapArray[i];
1103
+ }, Heap3.prototype.getChildrenOf = function(idx) {
1104
+ var _this = this;
1105
+ return Heap3.getChildrenIndexOf(idx).map(function(i) {
1106
+ return _this.heapArray[i];
1107
+ }).filter(function(e) {
1108
+ return e !== void 0;
1109
+ });
1110
+ }, Heap3.prototype.getParentOf = function(idx) {
1111
+ var pi = Heap3.getParentIndexOf(idx);
1112
+ return this.heapArray[pi];
1113
+ }, Heap3.prototype[Symbol.iterator] = function() {
1114
+ return __generator(this, function(_a) {
1115
+ switch (_a.label) {
1116
+ case 0:
1117
+ return this.length ? [4, this.pop()] : [3, 2];
1118
+ case 1:
1119
+ return _a.sent(), [3, 0];
1120
+ case 2:
1121
+ return [
1122
+ 2
1123
+ /*return*/
1124
+ ];
1125
+ }
1126
+ });
1127
+ }, Heap3.prototype.iterator = function() {
1128
+ return this.toArray();
1129
+ }, Heap3.prototype._applyLimit = function() {
1130
+ if (this._limit > 0 && this._limit < this.heapArray.length)
1131
+ for (var rm = this.heapArray.length - this._limit; rm; )
1132
+ this.heapArray.pop(), --rm;
1133
+ }, Heap3.prototype._bottomN_push = function(n2) {
1134
+ var bottomHeap = new Heap3(this.compare);
1135
+ bottomHeap.limit = n2, bottomHeap.heapArray = this.heapArray.slice(-n2), bottomHeap.init();
1136
+ for (var startAt = this.heapArray.length - 1 - n2, parentStartAt = Heap3.getParentIndexOf(startAt), indices = [], i = startAt; i > parentStartAt; --i)
1137
+ indices.push(i);
1138
+ for (var arr = this.heapArray; indices.length; ) {
1139
+ var i = indices.shift();
1140
+ this.compare(arr[i], bottomHeap.peek()) > 0 && (bottomHeap.replace(arr[i]), i % 2 && indices.push(Heap3.getParentIndexOf(i)));
1141
+ }
1142
+ return bottomHeap.toArray();
1143
+ }, Heap3.prototype._moveNode = function(j, k) {
1144
+ var _a;
1145
+ _a = __read([this.heapArray[k], this.heapArray[j]], 2), this.heapArray[j] = _a[0], this.heapArray[k] = _a[1];
1146
+ }, Heap3.prototype._sortNodeDown = function(i) {
1147
+ for (var _this = this, moveIt = i < this.heapArray.length - 1, self2 = this.heapArray[i], getPotentialParent = function(best, j) {
1148
+ return _this.heapArray.length > j && _this.compare(_this.heapArray[j], _this.heapArray[best]) < 0 && (best = j), best;
1149
+ }; moveIt; ) {
1150
+ var childrenIdx = Heap3.getChildrenIndexOf(i), bestChildIndex = childrenIdx.reduce(getPotentialParent, childrenIdx[0]), bestChild = this.heapArray[bestChildIndex];
1151
+ typeof bestChild < "u" && this.compare(self2, bestChild) > 0 ? (this._moveNode(i, bestChildIndex), i = bestChildIndex) : moveIt = !1;
1152
+ }
1153
+ }, Heap3.prototype._sortNodeUp = function(i) {
1154
+ for (var moveIt = i > 0; moveIt; ) {
1155
+ var pi = Heap3.getParentIndexOf(i);
1156
+ pi >= 0 && this.compare(this.heapArray[pi], this.heapArray[i]) > 0 ? (this._moveNode(i, pi), i = pi) : moveIt = !1;
1157
+ }
1158
+ }, Heap3.prototype._topN_push = function(n2) {
1159
+ var topHeap = new Heap3(this._invertedCompare);
1160
+ topHeap.limit = n2;
1161
+ for (var indices = [0], arr = this.heapArray; indices.length; ) {
1162
+ var i = indices.shift();
1163
+ i < arr.length && (topHeap.length < n2 ? (topHeap.push(arr[i]), indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i)), !1))) : this.compare(arr[i], topHeap.peek()) < 0 && (topHeap.replace(arr[i]), indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i)), !1))));
1164
+ }
1165
+ return topHeap.toArray();
1166
+ }, Heap3.prototype._topN_fill = function(n2) {
1167
+ var heapArray = this.heapArray, topHeap = new Heap3(this._invertedCompare);
1168
+ topHeap.limit = n2, topHeap.heapArray = heapArray.slice(0, n2), topHeap.init();
1169
+ for (var branch = Heap3.getParentIndexOf(n2 - 1) + 1, indices = [], i = branch; i < n2; ++i)
1170
+ indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i).filter(function(l) {
1171
+ return l < heapArray.length;
1172
+ })), !1));
1173
+ for ((n2 - 1) % 2 && indices.push(n2); indices.length; ) {
1174
+ var i = indices.shift();
1175
+ i < heapArray.length && this.compare(heapArray[i], topHeap.peek()) < 0 && (topHeap.replace(heapArray[i]), indices.push.apply(indices, __spreadArray([], __read(Heap3.getChildrenIndexOf(i)), !1)));
1176
+ }
1177
+ return topHeap.toArray();
1178
+ }, Heap3.prototype._topN_heap = function(n2) {
1179
+ for (var topHeap = this.clone(), result = [], i = 0; i < n2; ++i)
1180
+ result.push(topHeap.pop());
1181
+ return result;
1182
+ }, Heap3.prototype._topIdxOf = function(list) {
1183
+ if (!list.length)
1184
+ return -1;
1185
+ for (var idx = 0, top = list[idx], i = 1; i < list.length; ++i) {
1186
+ var comp = this.compare(list[i], top);
1187
+ comp < 0 && (idx = i, top = list[i]);
1188
+ }
1189
+ return idx;
1190
+ }, Heap3.prototype._topOf = function() {
1191
+ for (var list = [], _i = 0; _i < arguments.length; _i++)
1192
+ list[_i] = arguments[_i];
1193
+ var heap = new Heap3(this.compare);
1194
+ return heap.init(list), heap.peek();
1195
+ }, Heap3;
1196
+ }()
1197
+ );
1198
+ exports2.Heap = Heap2, exports2.HeapAsync = HeapAsync, exports2.default = Heap2, exports2.toInt = toInt, Object.defineProperty(exports2, "__esModule", { value: !0 });
1199
+ });
1200
+ }
1201
+ });
1202
+
1203
+ // ../workflows-shared/src/binding.ts
1204
+ import { RpcTarget, WorkerEntrypoint } from "cloudflare:workers";
1205
+
1206
+ // ../workflows-shared/src/instance.ts
1207
+ var INSTANCE_METADATA = "INSTANCE_METADATA";
1208
+ function instanceStatusName(status) {
1209
+ switch (status) {
1210
+ case 0 /* Queued */:
1211
+ return "queued";
1212
+ case 1 /* Running */:
1213
+ return "running";
1214
+ case 2 /* Paused */:
1215
+ return "paused";
1216
+ case 3 /* Errored */:
1217
+ return "errored";
1218
+ case 4 /* Terminated */:
1219
+ return "terminated";
1220
+ case 5 /* Complete */:
1221
+ return "complete";
1222
+ default:
1223
+ return "unknown";
1224
+ }
1225
+ }
1226
+
1227
+ // ../workflows-shared/src/binding.ts
1228
+ var WorkflowBinding = class extends WorkerEntrypoint {
1229
+ async create({
1230
+ id = crypto.randomUUID(),
1231
+ params = {}
1232
+ } = {}) {
1233
+ let stubId = this.env.ENGINE.idFromName(id), stub = this.env.ENGINE.get(stubId);
1234
+ stub.init(
1235
+ 0,
1236
+ // accountId: number,
1237
+ {},
1238
+ // workflow: DatabaseWorkflow,
1239
+ {},
1240
+ // version: DatabaseVersion,
1241
+ { id },
1242
+ // instance: DatabaseInstance,
1243
+ {
1244
+ timestamp: /* @__PURE__ */ new Date(),
1245
+ payload: params,
1246
+ instanceId: id
1247
+ }
1248
+ );
1249
+ let handle = new WorkflowHandle(id, stub);
1250
+ return {
1251
+ id,
1252
+ pause: handle.pause.bind(handle),
1253
+ resume: handle.resume.bind(handle),
1254
+ terminate: handle.terminate.bind(handle),
1255
+ restart: handle.restart.bind(handle),
1256
+ status: handle.status.bind(handle)
1257
+ };
1258
+ }
1259
+ async get(id) {
1260
+ let engineStubId = this.env.ENGINE.idFromName(id), engineStub = this.env.ENGINE.get(engineStubId), handle = new WorkflowHandle(id, engineStub);
1261
+ try {
1262
+ await handle.status();
1263
+ } catch {
1264
+ throw new Error("instance.not_found");
1265
+ }
1266
+ return {
1267
+ id,
1268
+ pause: handle.pause.bind(handle),
1269
+ resume: handle.resume.bind(handle),
1270
+ terminate: handle.terminate.bind(handle),
1271
+ restart: handle.restart.bind(handle),
1272
+ status: handle.status.bind(handle)
1273
+ };
1274
+ }
1275
+ }, WorkflowHandle = class extends RpcTarget {
1276
+ constructor(id, stub) {
1277
+ super();
1278
+ this.id = id;
1279
+ this.stub = stub;
1280
+ }
1281
+ async pause() {
1282
+ throw new Error("Not implemented yet");
1283
+ }
1284
+ async resume() {
1285
+ throw new Error("Not implemented yet");
1286
+ }
1287
+ async terminate() {
1288
+ throw new Error("Not implemented yet");
1289
+ }
1290
+ async restart() {
1291
+ throw new Error("Not implemented yet");
1292
+ }
1293
+ async status() {
1294
+ let status = await this.stub.getStatus(0, this.id), { logs } = await this.stub.readLogs(), workflowSuccessEvent = logs.filter((log) => log.event === 2 /* WORKFLOW_SUCCESS */).at(0), stepOutputs = logs.filter(
1295
+ (log) => log.event === 6 /* STEP_SUCCESS */
1296
+ ).map((log) => log.metadata.result), workflowOutput = workflowSuccessEvent !== void 0 ? workflowSuccessEvent.metadata.result : null;
1297
+ return {
1298
+ status: instanceStatusName(status),
1299
+ __LOCAL_DEV_STEP_OUTPUTS: stepOutputs,
1300
+ // @ts-expect-error types are wrong, will remove this expect-error once I fix them
1301
+ output: workflowOutput
1302
+ };
1303
+ }
1304
+ };
1305
+
1306
+ // ../workflows-shared/src/engine.ts
1307
+ import { DurableObject } from "cloudflare:workers";
1308
+
1309
+ // ../workflows-shared/src/context.ts
1310
+ import { RpcTarget as RpcTarget2 } from "cloudflare:workers";
1311
+
1312
+ // ../../node_modules/.pnpm/itty-time@1.0.6/node_modules/itty-time/index.mjs
1313
+ var n = { year: 315576e5, month: 2592e6, week: 6048e5, day: 864e5, hour: 36e5, minute: 6e4, second: 1e3, m: 1 }, r = (e) => {
1314
+ if (+e)
1315
+ return +e;
1316
+ let [, t, r2] = e.match(/^([^ ]+) +(\w\w*?)s?$/) || [];
1317
+ return +t * (n[r2] || 1);
1318
+ };
1319
+
1320
+ // ../workflows-shared/src/lib/cache.ts
1321
+ async function computeHash(value) {
1322
+ let msgUint8 = new TextEncoder().encode(value), hashBuffer = await crypto.subtle.digest("SHA-1", msgUint8);
1323
+ return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
1324
+ }
1325
+
1326
+ // ../workflows-shared/src/lib/errors.ts
1327
+ var WorkflowTimeoutError = class extends Error {
1328
+ name = "WorkflowTimeoutError";
1329
+ }, WorkflowInternalError = class extends Error {
1330
+ name = "WorkflowInternalError";
1331
+ }, WorkflowFatalError = class extends Error {
1332
+ name = "WorkflowFatalError";
1333
+ toJSON() {
1334
+ return {
1335
+ name: this.name,
1336
+ message: this.message
1337
+ };
1338
+ }
1339
+ };
1340
+
1341
+ // ../workflows-shared/src/lib/retries.ts
1342
+ function calcRetryDuration(config, stepState) {
1343
+ let { attemptedCount: attemptCount } = stepState, { retries } = config, delay = r(retries.delay);
1344
+ switch (retries.backoff) {
1345
+ case "exponential":
1346
+ return delay * Math.pow(2, attemptCount - 1);
1347
+ case "linear":
1348
+ return delay * attemptCount;
1349
+ case "constant":
1350
+ default:
1351
+ return delay;
1352
+ }
1353
+ }
1354
+
1355
+ // ../workflows-shared/src/lib/validators.ts
1356
+ var CONTROL_CHAR_REGEX = new RegExp("[\0-]");
1357
+ function validateStepName(string) {
1358
+ return string.length > 256 ? !1 : !CONTROL_CHAR_REGEX.test(string);
1359
+ }
1360
+
1361
+ // ../workflows-shared/src/context.ts
1362
+ var defaultConfig = {
1363
+ retries: {
1364
+ limit: 5,
1365
+ delay: 1e3,
1366
+ backoff: "constant"
1367
+ },
1368
+ timeout: "15 minutes"
1369
+ }, Context = class extends RpcTarget2 {
1370
+ #engine;
1371
+ #state;
1372
+ #counters = /* @__PURE__ */ new Map();
1373
+ constructor(engine, state) {
1374
+ super(), this.#engine = engine, this.#state = state;
1375
+ }
1376
+ #getCount(name) {
1377
+ let val = this.#counters.get(name) ?? 0;
1378
+ return val++, this.#counters.set(name, val), val;
1379
+ }
1380
+ async do(name, configOrCallback, callback) {
1381
+ let closure, stepConfig;
1382
+ if (callback ? (closure = callback, stepConfig = configOrCallback) : (closure = configOrCallback, stepConfig = {}), !validateStepName(name)) {
1383
+ let error = new WorkflowFatalError(
1384
+ `Step name "${name}" exceeds max length (${256} chars) or invalid characters found`
1385
+ );
1386
+ throw error.isUserError = !0, error;
1387
+ }
1388
+ let config = {
1389
+ ...defaultConfig,
1390
+ ...stepConfig,
1391
+ retries: {
1392
+ ...defaultConfig.retries,
1393
+ ...stepConfig.retries
1394
+ }
1395
+ }, hash = await computeHash(name), count = this.#getCount("run-" + name), cacheKey = `${hash}-${count}`, valueKey = `${cacheKey}-value`, configKey = `${cacheKey}-config`, stepNameWithCounter = `${name}-${count}`, stepStateKey = `${cacheKey}-metadata`, maybeMap = await this.#state.storage.get([valueKey, configKey]), maybeResult = maybeMap.get(valueKey);
1396
+ if (maybeResult)
1397
+ return maybeResult.value;
1398
+ maybeMap.has(configKey) ? config = maybeMap.get(configKey) : await this.#state.storage.put(configKey, config);
1399
+ let attemptLogs = this.#engine.readLogsFromStep(cacheKey).filter(
1400
+ (val) => [
1401
+ 11 /* ATTEMPT_SUCCESS */,
1402
+ 12 /* ATTEMPT_FAILURE */,
1403
+ 10 /* ATTEMPT_START */
1404
+ ].includes(val.event)
1405
+ );
1406
+ if (attemptLogs.length > 0 && attemptLogs.at(-1)?.event === 10 /* ATTEMPT_START */) {
1407
+ let stepState = await this.#state.storage.get(
1408
+ stepStateKey
1409
+ ) ?? {
1410
+ attemptedCount: 1
1411
+ }, priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`, timeoutEntryPQ = this.#engine.priorityQueue.getFirst(
1412
+ (a) => a.hash === priorityQueueHash && a.type === "timeout"
1413
+ );
1414
+ timeoutEntryPQ !== void 0 && this.#engine.priorityQueue.remove(timeoutEntryPQ), this.#engine.writeLog(
1415
+ 12 /* ATTEMPT_FAILURE */,
1416
+ cacheKey,
1417
+ stepNameWithCounter,
1418
+ {
1419
+ attempt: stepState.attemptedCount,
1420
+ error: {
1421
+ name: "WorkflowInternalError",
1422
+ message: "Attempt failed due to internal workflows error"
1423
+ }
1424
+ }
1425
+ ), await this.#state.storage.put(stepStateKey, stepState);
1426
+ }
1427
+ let doWrapper = async (doWrapperClosure) => {
1428
+ let stepState = await this.#state.storage.get(
1429
+ stepStateKey
1430
+ ) ?? {
1431
+ attemptedCount: 0
1432
+ };
1433
+ if (await this.#engine.timeoutHandler.acquire(this.#engine), stepState.attemptedCount == 0)
1434
+ this.#engine.writeLog(
1435
+ 5 /* STEP_START */,
1436
+ cacheKey,
1437
+ stepNameWithCounter,
1438
+ {
1439
+ config
1440
+ }
1441
+ );
1442
+ else {
1443
+ let priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`, retryEntryPQ = this.#engine.priorityQueue.getFirst(
1444
+ (a) => a.hash === priorityQueueHash && a.type === "retry"
1445
+ );
1446
+ retryEntryPQ !== void 0 && (await this.#engine.timeoutHandler.release(this.#engine), await scheduler.wait(retryEntryPQ.targetTimestamp - Date.now()), await this.#engine.timeoutHandler.acquire(this.#engine), this.#engine.priorityQueue.remove({
1447
+ hash: priorityQueueHash,
1448
+ type: "retry"
1449
+ }));
1450
+ }
1451
+ let result, instanceMetadata = await this.#state.storage.get(INSTANCE_METADATA);
1452
+ if (!instanceMetadata)
1453
+ throw new Error("instanceMetadata is undefined");
1454
+ let { accountId, instance } = instanceMetadata;
1455
+ try {
1456
+ let timeoutPromise = async () => {
1457
+ let priorityQueueHash2 = `${cacheKey}-${stepState.attemptedCount}`, timeout = r(config.timeout);
1458
+ throw await this.#engine.priorityQueue.add({
1459
+ hash: priorityQueueHash2,
1460
+ targetTimestamp: Date.now() + timeout,
1461
+ type: "timeout"
1462
+ }), await scheduler.wait(timeout), await this.#engine.priorityQueue.remove({
1463
+ hash: priorityQueueHash2,
1464
+ type: "timeout"
1465
+ }), new WorkflowTimeoutError(
1466
+ `Execution timed out after ${timeout}ms`
1467
+ );
1468
+ };
1469
+ this.#engine.writeLog(
1470
+ 10 /* ATTEMPT_START */,
1471
+ cacheKey,
1472
+ stepNameWithCounter,
1473
+ {
1474
+ attempt: stepState.attemptedCount + 1
1475
+ }
1476
+ ), stepState.attemptedCount++, await this.#state.storage.put(stepStateKey, stepState);
1477
+ let priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`;
1478
+ result = await Promise.race([doWrapperClosure(), timeoutPromise()]), await this.#engine.priorityQueue.remove({
1479
+ hash: priorityQueueHash,
1480
+ type: "timeout"
1481
+ });
1482
+ try {
1483
+ await this.#state.storage.put(valueKey, { value: result });
1484
+ } catch (e) {
1485
+ if (e instanceof Error && e.name === "DataCloneError")
1486
+ this.#engine.writeLog(
1487
+ 12 /* ATTEMPT_FAILURE */,
1488
+ cacheKey,
1489
+ stepNameWithCounter,
1490
+ {
1491
+ attempt: stepState.attemptedCount,
1492
+ error: new WorkflowFatalError(
1493
+ `Value returned from step "${name}" is not serialisable`
1494
+ )
1495
+ }
1496
+ ), this.#engine.writeLog(
1497
+ 7 /* STEP_FAILURE */,
1498
+ cacheKey,
1499
+ stepNameWithCounter,
1500
+ {}
1501
+ ), this.#engine.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
1502
+ error: new WorkflowFatalError(
1503
+ `The execution of the Workflow instance was terminated, as the step "${name}" returned a value which is not serialisable`
1504
+ )
1505
+ }), await this.#engine.setStatus(
1506
+ accountId,
1507
+ instance.id,
1508
+ 3 /* Errored */
1509
+ ), await this.#engine.timeoutHandler.release(this.#engine), await this.#engine.abort("Value is not serialisable");
1510
+ else
1511
+ throw new WorkflowInternalError(
1512
+ `Storage failure for ${valueKey}: ${e} `
1513
+ );
1514
+ return;
1515
+ }
1516
+ this.#engine.writeLog(
1517
+ 11 /* ATTEMPT_SUCCESS */,
1518
+ cacheKey,
1519
+ stepNameWithCounter,
1520
+ {
1521
+ attempt: stepState.attemptedCount
1522
+ }
1523
+ );
1524
+ } catch (e) {
1525
+ let error = e;
1526
+ if (this.#engine.priorityQueue.remove({
1527
+ hash: `${cacheKey}-${stepState.attemptedCount}`,
1528
+ type: "timeout"
1529
+ }), e instanceof Error && error.name === "NonRetryableError")
1530
+ return this.#engine.writeLog(
1531
+ 12 /* ATTEMPT_FAILURE */,
1532
+ cacheKey,
1533
+ stepNameWithCounter,
1534
+ {
1535
+ attempt: stepState.attemptedCount,
1536
+ error: new WorkflowFatalError(
1537
+ `Step threw a NonRetryableError with message "${e.message}"`
1538
+ )
1539
+ }
1540
+ ), this.#engine.writeLog(
1541
+ 7 /* STEP_FAILURE */,
1542
+ cacheKey,
1543
+ stepNameWithCounter,
1544
+ {}
1545
+ ), this.#engine.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
1546
+ error: new WorkflowFatalError(
1547
+ `The execution of the Workflow instance was terminated, as the step "${name}" threw a NonRetryableError`
1548
+ )
1549
+ }), await this.#engine.setStatus(
1550
+ accountId,
1551
+ instance.id,
1552
+ 3 /* Errored */
1553
+ ), await this.#engine.timeoutHandler.release(this.#engine), this.#engine.abort(`Step "${name}" threw a NonRetryableError`);
1554
+ if (this.#engine.writeLog(
1555
+ 12 /* ATTEMPT_FAILURE */,
1556
+ cacheKey,
1557
+ stepNameWithCounter,
1558
+ {
1559
+ attempt: stepState.attemptedCount,
1560
+ error: {
1561
+ name: error.name,
1562
+ message: error.message
1563
+ // TODO (WOR-79): Stacks are all incorrect over RPC and need work
1564
+ // stack: error.stack,
1565
+ }
1566
+ }
1567
+ ), await this.#state.storage.put(stepStateKey, stepState), stepState.attemptedCount <= config.retries.limit) {
1568
+ let durationMs = calcRetryDuration(config, stepState), priorityQueueHash = `${cacheKey}-${stepState.attemptedCount}`;
1569
+ return await this.#engine.priorityQueue.add({
1570
+ hash: priorityQueueHash,
1571
+ targetTimestamp: Date.now() + durationMs,
1572
+ type: "retry"
1573
+ }), await this.#engine.timeoutHandler.release(this.#engine), await scheduler.wait(durationMs), this.#engine.priorityQueue.remove({
1574
+ hash: priorityQueueHash,
1575
+ type: "retry"
1576
+ }), doWrapper(doWrapperClosure);
1577
+ } else
1578
+ throw await this.#engine.timeoutHandler.release(this.#engine), this.#engine.writeLog(
1579
+ 7 /* STEP_FAILURE */,
1580
+ cacheKey,
1581
+ stepNameWithCounter,
1582
+ {}
1583
+ ), this.#engine.writeLog(
1584
+ 3 /* WORKFLOW_FAILURE */,
1585
+ cacheKey,
1586
+ null,
1587
+ {}
1588
+ ), await this.#engine.setStatus(
1589
+ accountId,
1590
+ instance.id,
1591
+ 3 /* Errored */
1592
+ ), error;
1593
+ }
1594
+ return this.#engine.writeLog(
1595
+ 6 /* STEP_SUCCESS */,
1596
+ cacheKey,
1597
+ stepNameWithCounter,
1598
+ {
1599
+ // TODO (WOR-86): Add limits, figure out serialization
1600
+ result
1601
+ }
1602
+ ), await this.#engine.timeoutHandler.release(this.#engine), result;
1603
+ };
1604
+ return doWrapper(closure);
1605
+ }
1606
+ async sleep(name, duration) {
1607
+ typeof duration == "string" && (duration = r(duration));
1608
+ let hash = await computeHash(name + duration.toString()), count = this.#getCount("sleep-" + name + duration.toString()), cacheKey = `${hash}-${count}`, sleepNameWithCounter = `${name}-${count}`, sleepKey = `${cacheKey}-value`, sleepLogWrittenKey = `${cacheKey}-log-written`;
1609
+ if (await this.#state.storage.get(sleepKey) != null) {
1610
+ let entryPQ = this.#engine.priorityQueue.getFirst(
1611
+ (a) => a.hash === cacheKey && a.type === "sleep"
1612
+ );
1613
+ entryPQ !== void 0 && (await scheduler.wait(entryPQ.targetTimestamp - Date.now()), this.#engine.priorityQueue.remove({ hash: cacheKey, type: "sleep" })), await this.#state.storage.get(sleepLogWrittenKey) == null && (this.#engine.writeLog(
1614
+ 9 /* SLEEP_COMPLETE */,
1615
+ cacheKey,
1616
+ sleepNameWithCounter,
1617
+ {}
1618
+ ), await this.#state.storage.put(sleepLogWrittenKey, !0));
1619
+ return;
1620
+ }
1621
+ if (this.#engine.writeLog(
1622
+ 8 /* SLEEP_START */,
1623
+ cacheKey,
1624
+ sleepNameWithCounter,
1625
+ {
1626
+ durationMs: duration
1627
+ }
1628
+ ), !await this.#state.storage.get(INSTANCE_METADATA))
1629
+ throw new Error("instanceMetadata is undefined");
1630
+ await this.#state.storage.put(sleepKey, !0), await this.#engine.priorityQueue.add({
1631
+ hash: cacheKey,
1632
+ targetTimestamp: Date.now() + duration,
1633
+ type: "sleep"
1634
+ }), await scheduler.wait(duration), this.#engine.writeLog(
1635
+ 9 /* SLEEP_COMPLETE */,
1636
+ cacheKey,
1637
+ sleepNameWithCounter,
1638
+ {}
1639
+ ), await this.#state.storage.put(sleepLogWrittenKey, !0), this.#engine.priorityQueue.remove({ hash: cacheKey, type: "sleep" });
1640
+ }
1641
+ async sleepUntil(name, timestamp) {
1642
+ timestamp instanceof Date && (timestamp = timestamp.valueOf());
1643
+ let now = Date.now();
1644
+ if (timestamp < now)
1645
+ throw new Error(
1646
+ "You can't sleep until a time in the past, time-traveler"
1647
+ );
1648
+ return this.sleep(name, timestamp - now);
1649
+ }
1650
+ };
1651
+
1652
+ // ../workflows-shared/src/lib/gracePeriodSemaphore.ts
1653
+ var ENGINE_TIMEOUT = r("5 minutes"), latestGracePeriodTimestamp, GracePeriodSemaphore = class {
1654
+ #counter = 0;
1655
+ callback;
1656
+ timeoutMs;
1657
+ constructor(callback, timeoutMs) {
1658
+ this.callback = callback, this.timeoutMs = timeoutMs;
1659
+ }
1660
+ // acquire takes engine to be the same as release
1661
+ async acquire(_engine) {
1662
+ this.#counter == 0 && (latestGracePeriodTimestamp = void 0), this.#counter += 1;
1663
+ }
1664
+ async release(engine) {
1665
+ this.#counter = Math.max(this.#counter - 1, 0), this.#counter == 0 && this.callback(engine, this.timeoutMs);
1666
+ }
1667
+ isRunningStep() {
1668
+ return this.#counter > 0;
1669
+ }
1670
+ }, startGracePeriod = async (engine, timeoutMs) => {
1671
+ (async () => {
1672
+ let thisTimestamp = (/* @__PURE__ */ new Date()).valueOf();
1673
+ if (!(latestGracePeriodTimestamp === void 0 || latestGracePeriodTimestamp < thisTimestamp))
1674
+ throw new Error(
1675
+ "Can't start grace period since there is already an active one started on " + latestGracePeriodTimestamp
1676
+ );
1677
+ latestGracePeriodTimestamp = thisTimestamp, await scheduler.wait(timeoutMs), !(thisTimestamp !== latestGracePeriodTimestamp || engine.timeoutHandler.isRunningStep()) && (await engine.priorityQueue?.handleNextAlarm(), await engine.abort("Grace period complete"));
1678
+ })();
1679
+ };
1680
+
1681
+ // ../workflows-shared/src/lib/timePriorityQueue.ts
1682
+ var import_heap_js = __toESM(require_heap_js_umd()), wakerPriorityEntryComparator = (a, b) => a.targetTimestamp - b.targetTimestamp;
1683
+ var TimePriorityQueue = class {
1684
+ #heap = new import_heap_js.default(wakerPriorityEntryComparator);
1685
+ // #env: Env;
1686
+ #ctx;
1687
+ #instanceMetadata;
1688
+ constructor(ctx, instanceMetadata) {
1689
+ this.#ctx = ctx, this.#instanceMetadata = instanceMetadata, this.#heap.init(this.getEntries());
1690
+ }
1691
+ popPastEntries() {
1692
+ if (this.#heap.length === 0)
1693
+ return;
1694
+ let res = [], currentTimestamp = (/* @__PURE__ */ new Date()).valueOf();
1695
+ for (; ; ) {
1696
+ let element = this.#heap.peek();
1697
+ if (element === void 0 || element.targetTimestamp > currentTimestamp)
1698
+ break;
1699
+ res.push(element), this.#heap.pop();
1700
+ }
1701
+ return this.#ctx.storage.transactionSync(() => {
1702
+ for (let entry of res)
1703
+ this.removeEntryDB(entry);
1704
+ }), res;
1705
+ }
1706
+ /**
1707
+ * `add` is ran using a transaction so it's race condition free, if it's ran atomically
1708
+ * @param entry
1709
+ */
1710
+ async add(entry) {
1711
+ await this.#ctx.storage.transaction(async () => {
1712
+ this.#heap.add(entry), this.addEntryDB(entry);
1713
+ });
1714
+ }
1715
+ /**
1716
+ * `remove` is ran using a transaction so it's race condition free, if it's ran atomically
1717
+ * @param entry
1718
+ */
1719
+ remove(entry) {
1720
+ this.#ctx.storage.transactionSync(() => {
1721
+ this.removeFirst((e) => e.hash === entry.hash && e.type === entry.type);
1722
+ });
1723
+ }
1724
+ popTypeAll(entryType) {
1725
+ this.#ctx.storage.transactionSync(() => {
1726
+ this.filter((e) => e.type !== entryType);
1727
+ });
1728
+ }
1729
+ // Idempotent, perhaps name should suggest so
1730
+ async handleNextAlarm() {
1731
+ this.#heap.peek();
1732
+ }
1733
+ getFirst(callbackFn) {
1734
+ return structuredClone(this.#heap.toArray().find(callbackFn));
1735
+ }
1736
+ removeFirst(callbackFn) {
1737
+ let elements = this.#heap.toArray(), index = elements.findIndex(callbackFn);
1738
+ if (index === -1)
1739
+ return;
1740
+ let removedEntry = elements.splice(index, 1)[0];
1741
+ this.removeEntryDB(removedEntry), this.#heap = new import_heap_js.default(wakerPriorityEntryComparator), this.#heap.init(elements);
1742
+ }
1743
+ filter(callbackFn) {
1744
+ let filteredElements = this.#heap.toArray().filter(callbackFn), removedElements = this.#heap.toArray().filter((a) => !callbackFn(a));
1745
+ this.#ctx.storage.transactionSync(() => {
1746
+ for (let entry of removedElements)
1747
+ this.removeEntryDB(entry);
1748
+ }), this.#heap = new import_heap_js.default(wakerPriorityEntryComparator), this.#heap.init(filteredElements);
1749
+ }
1750
+ length() {
1751
+ return this.#heap.length;
1752
+ }
1753
+ getEntries() {
1754
+ let entries = [
1755
+ ...this.#ctx.storage.sql.exec("SELECT * FROM priority_queue ORDER BY id")
1756
+ ], activeEntries = [];
1757
+ return entries.forEach((val) => {
1758
+ let entryType = toWakerPriorityType(val.entryType);
1759
+ if (val.action == 0) {
1760
+ let index = activeEntries.findIndex(
1761
+ (activeVal) => val.hash == activeVal.hash && entryType == activeVal.type
1762
+ );
1763
+ index !== -1 && activeEntries.splice(index, 1);
1764
+ } else
1765
+ activeEntries.findIndex(
1766
+ (activeVal) => val.hash == activeVal.hash && entryType == activeVal.type
1767
+ ) === -1 && activeEntries.push({
1768
+ hash: val.hash,
1769
+ targetTimestamp: val.target_timestamp,
1770
+ type: entryType
1771
+ });
1772
+ }), activeEntries;
1773
+ }
1774
+ removeEntryDB(entry) {
1775
+ this.#ctx.storage.sql.exec(
1776
+ `
1777
+ INSERT INTO priority_queue (target_timestamp, action, entryType, hash)
1778
+ VALUES (?, ?, ? ,?)
1779
+ `,
1780
+ entry.targetTimestamp,
1781
+ 0 /* FALSE */,
1782
+ fromWakerPriorityType(entry.type),
1783
+ entry.hash
1784
+ );
1785
+ }
1786
+ addEntryDB(entry) {
1787
+ this.#ctx.storage.sql.exec(
1788
+ `
1789
+ INSERT INTO priority_queue (target_timestamp, action, entryType, hash)
1790
+ VALUES (?, ?, ? ,?)
1791
+ `,
1792
+ entry.targetTimestamp,
1793
+ 1 /* TRUE */,
1794
+ fromWakerPriorityType(entry.type),
1795
+ entry.hash
1796
+ );
1797
+ }
1798
+ }, toWakerPriorityType = (entryType) => {
1799
+ switch (entryType) {
1800
+ case 0 /* RETRY */:
1801
+ return "retry";
1802
+ case 1 /* SLEEP */:
1803
+ return "sleep";
1804
+ case 2 /* TIMEOUT */:
1805
+ return "timeout";
1806
+ }
1807
+ }, fromWakerPriorityType = (entryType) => {
1808
+ switch (entryType) {
1809
+ case "retry":
1810
+ return 0 /* RETRY */;
1811
+ case "sleep":
1812
+ return 1 /* SLEEP */;
1813
+ case "timeout":
1814
+ return 2 /* TIMEOUT */;
1815
+ default:
1816
+ throw new Error(`WakerPriorityType "${entryType}" has not been handled`);
1817
+ }
1818
+ };
1819
+
1820
+ // ../workflows-shared/src/engine.ts
1821
+ var ENGINE_STATUS_KEY = "ENGINE_STATUS", Engine = class extends DurableObject {
1822
+ logs = [];
1823
+ isRunning = !1;
1824
+ accountId;
1825
+ instanceId;
1826
+ workflowName;
1827
+ timeoutHandler;
1828
+ priorityQueue;
1829
+ constructor(state, env) {
1830
+ super(state, env), this.ctx.blockConcurrencyWhile(async () => {
1831
+ this.ctx.storage.transactionSync(() => {
1832
+ try {
1833
+ this.ctx.storage.sql.exec(`
1834
+ CREATE TABLE IF NOT EXISTS priority_queue (
1835
+ id INTEGER PRIMARY KEY NOT NULL,
1836
+ created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
1837
+ target_timestamp INTEGER NOT NULL,
1838
+ action INTEGER NOT NULL, -- should only be 0 or 1 (1 for added, 0 for deleted),
1839
+ entryType INTEGER NOT NULL,
1840
+ hash TEXT NOT NULL,
1841
+ CHECK (action IN (0, 1)), -- guararentee that action can only be 0 or 1
1842
+ UNIQUE (action, entryType, hash)
1843
+ );
1844
+ CREATE TABLE IF NOT EXISTS states (
1845
+ id INTEGER PRIMARY KEY NOT NULL,
1846
+ groupKey TEXT,
1847
+ target TEXT,
1848
+ metadata TEXT,
1849
+ event INTEGER NOT NULL
1850
+ )
1851
+ `);
1852
+ } catch (e) {
1853
+ throw console.error(e), e;
1854
+ }
1855
+ });
1856
+ }), this.timeoutHandler = new GracePeriodSemaphore(
1857
+ startGracePeriod,
1858
+ ENGINE_TIMEOUT
1859
+ );
1860
+ }
1861
+ writeLog(event, group, target = null, metadata) {
1862
+ this.ctx.storage.sql.exec(
1863
+ "INSERT INTO states (event, groupKey, target, metadata) VALUES (?, ?, ?, ?)",
1864
+ event,
1865
+ group,
1866
+ target,
1867
+ JSON.stringify(metadata)
1868
+ );
1869
+ }
1870
+ readLogsFromStep(_cacheKey) {
1871
+ return [];
1872
+ }
1873
+ readLogs() {
1874
+ return {
1875
+ logs: [
1876
+ ...this.ctx.storage.sql.exec("SELECT event, groupKey, target, metadata FROM states")
1877
+ ].map((log) => ({
1878
+ ...log,
1879
+ metadata: JSON.parse(log.metadata),
1880
+ group: log.groupKey
1881
+ }))
1882
+ };
1883
+ }
1884
+ async getStatus(_accountId, _instanceId) {
1885
+ if (this.accountId === void 0)
1886
+ throw new Error("stub not initialized");
1887
+ let res = await this.ctx.storage.get(ENGINE_STATUS_KEY);
1888
+ return res === void 0 ? 0 /* Queued */ : res;
1889
+ }
1890
+ async setStatus(accountId, instanceId, status) {
1891
+ await this.ctx.storage.put(ENGINE_STATUS_KEY, status);
1892
+ }
1893
+ async abort(_reason) {
1894
+ }
1895
+ async userTriggeredTerminate() {
1896
+ }
1897
+ async init(accountId, workflow, version, instance, event) {
1898
+ if (this.priorityQueue === void 0 && (this.priorityQueue = new TimePriorityQueue(
1899
+ this.ctx,
1900
+ // this.env,
1901
+ {
1902
+ accountId,
1903
+ workflow,
1904
+ version,
1905
+ instance,
1906
+ event
1907
+ }
1908
+ )), this.priorityQueue.popPastEntries(), await this.priorityQueue.handleNextAlarm(), this.isRunning)
1909
+ return;
1910
+ this.accountId = accountId, this.instanceId = instance.id, this.workflowName = workflow.name;
1911
+ let status = await this.getStatus(accountId, instance.id);
1912
+ if ([
1913
+ 3 /* Errored */,
1914
+ // TODO (WOR-85): Remove this once upgrade story is done
1915
+ 4 /* Terminated */,
1916
+ 5 /* Complete */
1917
+ ].includes(status))
1918
+ return;
1919
+ if (await this.ctx.storage.get(INSTANCE_METADATA) == null) {
1920
+ let instanceMetadata = {
1921
+ accountId,
1922
+ workflow,
1923
+ version,
1924
+ instance,
1925
+ event
1926
+ };
1927
+ await this.ctx.storage.put(INSTANCE_METADATA, instanceMetadata), this.writeLog(0 /* WORKFLOW_QUEUED */, null, null, {
1928
+ params: event.payload,
1929
+ versionId: version.id,
1930
+ trigger: {
1931
+ source: 0 /* API */
1932
+ }
1933
+ }), this.writeLog(1 /* WORKFLOW_START */, null, null, {});
1934
+ }
1935
+ let stubStep = new Context(this, this.ctx), workflowRunningHandler = async () => {
1936
+ await this.ctx.storage.transaction(async () => {
1937
+ await this.setStatus(accountId, instance.id, 1 /* Running */);
1938
+ });
1939
+ };
1940
+ this.isRunning = !0, workflowRunningHandler();
1941
+ try {
1942
+ let result = await this.env.USER_WORKFLOW.run(event, stubStep);
1943
+ this.writeLog(2 /* WORKFLOW_SUCCESS */, null, null, {
1944
+ result
1945
+ }), await this.ctx.storage.transaction(async () => {
1946
+ await this.setStatus(accountId, instance.id, 5 /* Complete */);
1947
+ }), this.isRunning = !1;
1948
+ } catch (err) {
1949
+ let error;
1950
+ err instanceof Error ? error = {
1951
+ message: err.message,
1952
+ name: err.name
1953
+ } : error = {
1954
+ name: "Error",
1955
+ message: err
1956
+ }, this.writeLog(3 /* WORKFLOW_FAILURE */, null, null, {
1957
+ error
1958
+ }), await this.ctx.storage.transaction(async () => {
1959
+ await this.setStatus(accountId, instance.id, 3 /* Errored */);
1960
+ }), this.isRunning = !1;
1961
+ }
1962
+ return {
1963
+ id: instance.id
1964
+ };
1965
+ }
1966
+ };
1967
+ export {
1968
+ Engine,
1969
+ WorkflowBinding
1970
+ };
1971
+ //# sourceMappingURL=binding.worker.js.map