kernel-script 1.0.0

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,4051 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __typeError = (msg) => {
9
+ throw TypeError(msg);
10
+ };
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __commonJS = (cb, mod) => function __require() {
13
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
14
+ };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
28
+ // If the importer is in node compatibility mode or this is not an ESM
29
+ // file that has been converted to a CommonJS file using a Babel-
30
+ // compatible transform (i.e. "__esModule" has not been set), then set
31
+ // "default" to the CommonJS "module.exports" for node compatibility.
32
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
33
+ mod
34
+ ));
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
37
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
38
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
39
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
40
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
41
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
42
+ var __privateWrapper = (obj, member, setter, getter) => ({
43
+ set _(value) {
44
+ __privateSet(obj, member, value, setter);
45
+ },
46
+ get _() {
47
+ return __privateGet(obj, member, getter);
48
+ }
49
+ });
50
+
51
+ // node_modules/eventemitter3/index.js
52
+ var require_eventemitter3 = __commonJS({
53
+ "node_modules/eventemitter3/index.js"(exports2, module2) {
54
+ "use strict";
55
+ var has = Object.prototype.hasOwnProperty;
56
+ var prefix = "~";
57
+ function Events() {
58
+ }
59
+ if (Object.create) {
60
+ Events.prototype = /* @__PURE__ */ Object.create(null);
61
+ if (!new Events().__proto__) prefix = false;
62
+ }
63
+ function EE(fn, context, once) {
64
+ this.fn = fn;
65
+ this.context = context;
66
+ this.once = once || false;
67
+ }
68
+ function addListener(emitter, event, fn, context, once) {
69
+ if (typeof fn !== "function") {
70
+ throw new TypeError("The listener must be a function");
71
+ }
72
+ var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
73
+ if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
74
+ else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
75
+ else emitter._events[evt] = [emitter._events[evt], listener];
76
+ return emitter;
77
+ }
78
+ function clearEvent(emitter, evt) {
79
+ if (--emitter._eventsCount === 0) emitter._events = new Events();
80
+ else delete emitter._events[evt];
81
+ }
82
+ function EventEmitter2() {
83
+ this._events = new Events();
84
+ this._eventsCount = 0;
85
+ }
86
+ EventEmitter2.prototype.eventNames = function eventNames() {
87
+ var names = [], events, name;
88
+ if (this._eventsCount === 0) return names;
89
+ for (name in events = this._events) {
90
+ if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
91
+ }
92
+ if (Object.getOwnPropertySymbols) {
93
+ return names.concat(Object.getOwnPropertySymbols(events));
94
+ }
95
+ return names;
96
+ };
97
+ EventEmitter2.prototype.listeners = function listeners(event) {
98
+ var evt = prefix ? prefix + event : event, handlers = this._events[evt];
99
+ if (!handlers) return [];
100
+ if (handlers.fn) return [handlers.fn];
101
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
102
+ ee[i] = handlers[i].fn;
103
+ }
104
+ return ee;
105
+ };
106
+ EventEmitter2.prototype.listenerCount = function listenerCount(event) {
107
+ var evt = prefix ? prefix + event : event, listeners = this._events[evt];
108
+ if (!listeners) return 0;
109
+ if (listeners.fn) return 1;
110
+ return listeners.length;
111
+ };
112
+ EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
113
+ var evt = prefix ? prefix + event : event;
114
+ if (!this._events[evt]) return false;
115
+ var listeners = this._events[evt], len = arguments.length, args, i;
116
+ if (listeners.fn) {
117
+ if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
118
+ switch (len) {
119
+ case 1:
120
+ return listeners.fn.call(listeners.context), true;
121
+ case 2:
122
+ return listeners.fn.call(listeners.context, a1), true;
123
+ case 3:
124
+ return listeners.fn.call(listeners.context, a1, a2), true;
125
+ case 4:
126
+ return listeners.fn.call(listeners.context, a1, a2, a3), true;
127
+ case 5:
128
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
129
+ case 6:
130
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
131
+ }
132
+ for (i = 1, args = new Array(len - 1); i < len; i++) {
133
+ args[i - 1] = arguments[i];
134
+ }
135
+ listeners.fn.apply(listeners.context, args);
136
+ } else {
137
+ var length = listeners.length, j;
138
+ for (i = 0; i < length; i++) {
139
+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true);
140
+ switch (len) {
141
+ case 1:
142
+ listeners[i].fn.call(listeners[i].context);
143
+ break;
144
+ case 2:
145
+ listeners[i].fn.call(listeners[i].context, a1);
146
+ break;
147
+ case 3:
148
+ listeners[i].fn.call(listeners[i].context, a1, a2);
149
+ break;
150
+ case 4:
151
+ listeners[i].fn.call(listeners[i].context, a1, a2, a3);
152
+ break;
153
+ default:
154
+ if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
155
+ args[j - 1] = arguments[j];
156
+ }
157
+ listeners[i].fn.apply(listeners[i].context, args);
158
+ }
159
+ }
160
+ }
161
+ return true;
162
+ };
163
+ EventEmitter2.prototype.on = function on(event, fn, context) {
164
+ return addListener(this, event, fn, context, false);
165
+ };
166
+ EventEmitter2.prototype.once = function once(event, fn, context) {
167
+ return addListener(this, event, fn, context, true);
168
+ };
169
+ EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
170
+ var evt = prefix ? prefix + event : event;
171
+ if (!this._events[evt]) return this;
172
+ if (!fn) {
173
+ clearEvent(this, evt);
174
+ return this;
175
+ }
176
+ var listeners = this._events[evt];
177
+ if (listeners.fn) {
178
+ if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
179
+ clearEvent(this, evt);
180
+ }
181
+ } else {
182
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
183
+ if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
184
+ events.push(listeners[i]);
185
+ }
186
+ }
187
+ if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
188
+ else clearEvent(this, evt);
189
+ }
190
+ return this;
191
+ };
192
+ EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
193
+ var evt;
194
+ if (event) {
195
+ evt = prefix ? prefix + event : event;
196
+ if (this._events[evt]) clearEvent(this, evt);
197
+ } else {
198
+ this._events = new Events();
199
+ this._eventsCount = 0;
200
+ }
201
+ return this;
202
+ };
203
+ EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
204
+ EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
205
+ EventEmitter2.prefixed = prefix;
206
+ EventEmitter2.EventEmitter = EventEmitter2;
207
+ if ("undefined" !== typeof module2) {
208
+ module2.exports = EventEmitter2;
209
+ }
210
+ }
211
+ });
212
+
213
+ // node_modules/react/cjs/react.production.js
214
+ var require_react_production = __commonJS({
215
+ "node_modules/react/cjs/react.production.js"(exports2) {
216
+ "use strict";
217
+ var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element");
218
+ var REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal");
219
+ var REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment");
220
+ var REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode");
221
+ var REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler");
222
+ var REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer");
223
+ var REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context");
224
+ var REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref");
225
+ var REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense");
226
+ var REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo");
227
+ var REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy");
228
+ var REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity");
229
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
230
+ function getIteratorFn(maybeIterable) {
231
+ if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
232
+ maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
233
+ return "function" === typeof maybeIterable ? maybeIterable : null;
234
+ }
235
+ var ReactNoopUpdateQueue = {
236
+ isMounted: function() {
237
+ return false;
238
+ },
239
+ enqueueForceUpdate: function() {
240
+ },
241
+ enqueueReplaceState: function() {
242
+ },
243
+ enqueueSetState: function() {
244
+ }
245
+ };
246
+ var assign = Object.assign;
247
+ var emptyObject = {};
248
+ function Component(props, context, updater) {
249
+ this.props = props;
250
+ this.context = context;
251
+ this.refs = emptyObject;
252
+ this.updater = updater || ReactNoopUpdateQueue;
253
+ }
254
+ Component.prototype.isReactComponent = {};
255
+ Component.prototype.setState = function(partialState, callback) {
256
+ if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState)
257
+ throw Error(
258
+ "takes an object of state variables to update or a function which returns an object of state variables."
259
+ );
260
+ this.updater.enqueueSetState(this, partialState, callback, "setState");
261
+ };
262
+ Component.prototype.forceUpdate = function(callback) {
263
+ this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
264
+ };
265
+ function ComponentDummy() {
266
+ }
267
+ ComponentDummy.prototype = Component.prototype;
268
+ function PureComponent(props, context, updater) {
269
+ this.props = props;
270
+ this.context = context;
271
+ this.refs = emptyObject;
272
+ this.updater = updater || ReactNoopUpdateQueue;
273
+ }
274
+ var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
275
+ pureComponentPrototype.constructor = PureComponent;
276
+ assign(pureComponentPrototype, Component.prototype);
277
+ pureComponentPrototype.isPureReactComponent = true;
278
+ var isArrayImpl = Array.isArray;
279
+ function noop() {
280
+ }
281
+ var ReactSharedInternals = { H: null, A: null, T: null, S: null };
282
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
283
+ function ReactElement(type, key, props) {
284
+ var refProp = props.ref;
285
+ return {
286
+ $$typeof: REACT_ELEMENT_TYPE,
287
+ type,
288
+ key,
289
+ ref: void 0 !== refProp ? refProp : null,
290
+ props
291
+ };
292
+ }
293
+ function cloneAndReplaceKey(oldElement, newKey) {
294
+ return ReactElement(oldElement.type, newKey, oldElement.props);
295
+ }
296
+ function isValidElement(object) {
297
+ return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
298
+ }
299
+ function escape(key) {
300
+ var escaperLookup = { "=": "=0", ":": "=2" };
301
+ return "$" + key.replace(/[=:]/g, function(match) {
302
+ return escaperLookup[match];
303
+ });
304
+ }
305
+ var userProvidedKeyEscapeRegex = /\/+/g;
306
+ function getElementKey(element, index) {
307
+ return "object" === typeof element && null !== element && null != element.key ? escape("" + element.key) : index.toString(36);
308
+ }
309
+ function resolveThenable(thenable) {
310
+ switch (thenable.status) {
311
+ case "fulfilled":
312
+ return thenable.value;
313
+ case "rejected":
314
+ throw thenable.reason;
315
+ default:
316
+ switch ("string" === typeof thenable.status ? thenable.then(noop, noop) : (thenable.status = "pending", thenable.then(
317
+ function(fulfilledValue) {
318
+ "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
319
+ },
320
+ function(error) {
321
+ "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error);
322
+ }
323
+ )), thenable.status) {
324
+ case "fulfilled":
325
+ return thenable.value;
326
+ case "rejected":
327
+ throw thenable.reason;
328
+ }
329
+ }
330
+ throw thenable;
331
+ }
332
+ function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
333
+ var type = typeof children;
334
+ if ("undefined" === type || "boolean" === type) children = null;
335
+ var invokeCallback = false;
336
+ if (null === children) invokeCallback = true;
337
+ else
338
+ switch (type) {
339
+ case "bigint":
340
+ case "string":
341
+ case "number":
342
+ invokeCallback = true;
343
+ break;
344
+ case "object":
345
+ switch (children.$$typeof) {
346
+ case REACT_ELEMENT_TYPE:
347
+ case REACT_PORTAL_TYPE:
348
+ invokeCallback = true;
349
+ break;
350
+ case REACT_LAZY_TYPE:
351
+ return invokeCallback = children._init, mapIntoArray(
352
+ invokeCallback(children._payload),
353
+ array,
354
+ escapedPrefix,
355
+ nameSoFar,
356
+ callback
357
+ );
358
+ }
359
+ }
360
+ if (invokeCallback)
361
+ return callback = callback(children), invokeCallback = "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar, isArrayImpl(callback) ? (escapedPrefix = "", null != invokeCallback && (escapedPrefix = invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) {
362
+ return c;
363
+ })) : null != callback && (isValidElement(callback) && (callback = cloneAndReplaceKey(
364
+ callback,
365
+ escapedPrefix + (null == callback.key || children && children.key === callback.key ? "" : ("" + callback.key).replace(
366
+ userProvidedKeyEscapeRegex,
367
+ "$&/"
368
+ ) + "/") + invokeCallback
369
+ )), array.push(callback)), 1;
370
+ invokeCallback = 0;
371
+ var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":";
372
+ if (isArrayImpl(children))
373
+ for (var i = 0; i < children.length; i++)
374
+ nameSoFar = children[i], type = nextNamePrefix + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(
375
+ nameSoFar,
376
+ array,
377
+ escapedPrefix,
378
+ type,
379
+ callback
380
+ );
381
+ else if (i = getIteratorFn(children), "function" === typeof i)
382
+ for (children = i.call(children), i = 0; !(nameSoFar = children.next()).done; )
383
+ nameSoFar = nameSoFar.value, type = nextNamePrefix + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(
384
+ nameSoFar,
385
+ array,
386
+ escapedPrefix,
387
+ type,
388
+ callback
389
+ );
390
+ else if ("object" === type) {
391
+ if ("function" === typeof children.then)
392
+ return mapIntoArray(
393
+ resolveThenable(children),
394
+ array,
395
+ escapedPrefix,
396
+ nameSoFar,
397
+ callback
398
+ );
399
+ array = String(children);
400
+ throw Error(
401
+ "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead."
402
+ );
403
+ }
404
+ return invokeCallback;
405
+ }
406
+ function mapChildren(children, func, context) {
407
+ if (null == children) return children;
408
+ var result = [], count = 0;
409
+ mapIntoArray(children, result, "", "", function(child) {
410
+ return func.call(context, child, count++);
411
+ });
412
+ return result;
413
+ }
414
+ function lazyInitializer(payload) {
415
+ if (-1 === payload._status) {
416
+ var ctor = payload._result;
417
+ ctor = ctor();
418
+ ctor.then(
419
+ function(moduleObject) {
420
+ if (0 === payload._status || -1 === payload._status)
421
+ payload._status = 1, payload._result = moduleObject;
422
+ },
423
+ function(error) {
424
+ if (0 === payload._status || -1 === payload._status)
425
+ payload._status = 2, payload._result = error;
426
+ }
427
+ );
428
+ -1 === payload._status && (payload._status = 0, payload._result = ctor);
429
+ }
430
+ if (1 === payload._status) return payload._result.default;
431
+ throw payload._result;
432
+ }
433
+ var reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
434
+ if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
435
+ var event = new window.ErrorEvent("error", {
436
+ bubbles: true,
437
+ cancelable: true,
438
+ message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
439
+ error
440
+ });
441
+ if (!window.dispatchEvent(event)) return;
442
+ } else if ("object" === typeof process && "function" === typeof process.emit) {
443
+ process.emit("uncaughtException", error);
444
+ return;
445
+ }
446
+ console.error(error);
447
+ };
448
+ var Children = {
449
+ map: mapChildren,
450
+ forEach: function(children, forEachFunc, forEachContext) {
451
+ mapChildren(
452
+ children,
453
+ function() {
454
+ forEachFunc.apply(this, arguments);
455
+ },
456
+ forEachContext
457
+ );
458
+ },
459
+ count: function(children) {
460
+ var n = 0;
461
+ mapChildren(children, function() {
462
+ n++;
463
+ });
464
+ return n;
465
+ },
466
+ toArray: function(children) {
467
+ return mapChildren(children, function(child) {
468
+ return child;
469
+ }) || [];
470
+ },
471
+ only: function(children) {
472
+ if (!isValidElement(children))
473
+ throw Error(
474
+ "React.Children.only expected to receive a single React element child."
475
+ );
476
+ return children;
477
+ }
478
+ };
479
+ exports2.Activity = REACT_ACTIVITY_TYPE;
480
+ exports2.Children = Children;
481
+ exports2.Component = Component;
482
+ exports2.Fragment = REACT_FRAGMENT_TYPE;
483
+ exports2.Profiler = REACT_PROFILER_TYPE;
484
+ exports2.PureComponent = PureComponent;
485
+ exports2.StrictMode = REACT_STRICT_MODE_TYPE;
486
+ exports2.Suspense = REACT_SUSPENSE_TYPE;
487
+ exports2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
488
+ exports2.__COMPILER_RUNTIME = {
489
+ __proto__: null,
490
+ c: function(size) {
491
+ return ReactSharedInternals.H.useMemoCache(size);
492
+ }
493
+ };
494
+ exports2.cache = function(fn) {
495
+ return function() {
496
+ return fn.apply(null, arguments);
497
+ };
498
+ };
499
+ exports2.cacheSignal = function() {
500
+ return null;
501
+ };
502
+ exports2.cloneElement = function(element, config, children) {
503
+ if (null === element || void 0 === element)
504
+ throw Error(
505
+ "The argument must be a React element, but you passed " + element + "."
506
+ );
507
+ var props = assign({}, element.props), key = element.key;
508
+ if (null != config)
509
+ for (propName in void 0 !== config.key && (key = "" + config.key), config)
510
+ !hasOwnProperty.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]);
511
+ var propName = arguments.length - 2;
512
+ if (1 === propName) props.children = children;
513
+ else if (1 < propName) {
514
+ for (var childArray = Array(propName), i = 0; i < propName; i++)
515
+ childArray[i] = arguments[i + 2];
516
+ props.children = childArray;
517
+ }
518
+ return ReactElement(element.type, key, props);
519
+ };
520
+ exports2.createContext = function(defaultValue) {
521
+ defaultValue = {
522
+ $$typeof: REACT_CONTEXT_TYPE,
523
+ _currentValue: defaultValue,
524
+ _currentValue2: defaultValue,
525
+ _threadCount: 0,
526
+ Provider: null,
527
+ Consumer: null
528
+ };
529
+ defaultValue.Provider = defaultValue;
530
+ defaultValue.Consumer = {
531
+ $$typeof: REACT_CONSUMER_TYPE,
532
+ _context: defaultValue
533
+ };
534
+ return defaultValue;
535
+ };
536
+ exports2.createElement = function(type, config, children) {
537
+ var propName, props = {}, key = null;
538
+ if (null != config)
539
+ for (propName in void 0 !== config.key && (key = "" + config.key), config)
540
+ hasOwnProperty.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (props[propName] = config[propName]);
541
+ var childrenLength = arguments.length - 2;
542
+ if (1 === childrenLength) props.children = children;
543
+ else if (1 < childrenLength) {
544
+ for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)
545
+ childArray[i] = arguments[i + 2];
546
+ props.children = childArray;
547
+ }
548
+ if (type && type.defaultProps)
549
+ for (propName in childrenLength = type.defaultProps, childrenLength)
550
+ void 0 === props[propName] && (props[propName] = childrenLength[propName]);
551
+ return ReactElement(type, key, props);
552
+ };
553
+ exports2.createRef = function() {
554
+ return { current: null };
555
+ };
556
+ exports2.forwardRef = function(render) {
557
+ return { $$typeof: REACT_FORWARD_REF_TYPE, render };
558
+ };
559
+ exports2.isValidElement = isValidElement;
560
+ exports2.lazy = function(ctor) {
561
+ return {
562
+ $$typeof: REACT_LAZY_TYPE,
563
+ _payload: { _status: -1, _result: ctor },
564
+ _init: lazyInitializer
565
+ };
566
+ };
567
+ exports2.memo = function(type, compare) {
568
+ return {
569
+ $$typeof: REACT_MEMO_TYPE,
570
+ type,
571
+ compare: void 0 === compare ? null : compare
572
+ };
573
+ };
574
+ exports2.startTransition = function(scope) {
575
+ var prevTransition = ReactSharedInternals.T, currentTransition = {};
576
+ ReactSharedInternals.T = currentTransition;
577
+ try {
578
+ var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
579
+ null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
580
+ "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && returnValue.then(noop, reportGlobalError);
581
+ } catch (error) {
582
+ reportGlobalError(error);
583
+ } finally {
584
+ null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
585
+ }
586
+ };
587
+ exports2.unstable_useCacheRefresh = function() {
588
+ return ReactSharedInternals.H.useCacheRefresh();
589
+ };
590
+ exports2.use = function(usable) {
591
+ return ReactSharedInternals.H.use(usable);
592
+ };
593
+ exports2.useActionState = function(action, initialState, permalink) {
594
+ return ReactSharedInternals.H.useActionState(action, initialState, permalink);
595
+ };
596
+ exports2.useCallback = function(callback, deps) {
597
+ return ReactSharedInternals.H.useCallback(callback, deps);
598
+ };
599
+ exports2.useContext = function(Context) {
600
+ return ReactSharedInternals.H.useContext(Context);
601
+ };
602
+ exports2.useDebugValue = function() {
603
+ };
604
+ exports2.useDeferredValue = function(value, initialValue) {
605
+ return ReactSharedInternals.H.useDeferredValue(value, initialValue);
606
+ };
607
+ exports2.useEffect = function(create2, deps) {
608
+ return ReactSharedInternals.H.useEffect(create2, deps);
609
+ };
610
+ exports2.useEffectEvent = function(callback) {
611
+ return ReactSharedInternals.H.useEffectEvent(callback);
612
+ };
613
+ exports2.useId = function() {
614
+ return ReactSharedInternals.H.useId();
615
+ };
616
+ exports2.useImperativeHandle = function(ref, create2, deps) {
617
+ return ReactSharedInternals.H.useImperativeHandle(ref, create2, deps);
618
+ };
619
+ exports2.useInsertionEffect = function(create2, deps) {
620
+ return ReactSharedInternals.H.useInsertionEffect(create2, deps);
621
+ };
622
+ exports2.useLayoutEffect = function(create2, deps) {
623
+ return ReactSharedInternals.H.useLayoutEffect(create2, deps);
624
+ };
625
+ exports2.useMemo = function(create2, deps) {
626
+ return ReactSharedInternals.H.useMemo(create2, deps);
627
+ };
628
+ exports2.useOptimistic = function(passthrough, reducer) {
629
+ return ReactSharedInternals.H.useOptimistic(passthrough, reducer);
630
+ };
631
+ exports2.useReducer = function(reducer, initialArg, init) {
632
+ return ReactSharedInternals.H.useReducer(reducer, initialArg, init);
633
+ };
634
+ exports2.useRef = function(initialValue) {
635
+ return ReactSharedInternals.H.useRef(initialValue);
636
+ };
637
+ exports2.useState = function(initialState) {
638
+ return ReactSharedInternals.H.useState(initialState);
639
+ };
640
+ exports2.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
641
+ return ReactSharedInternals.H.useSyncExternalStore(
642
+ subscribe,
643
+ getSnapshot,
644
+ getServerSnapshot
645
+ );
646
+ };
647
+ exports2.useTransition = function() {
648
+ return ReactSharedInternals.H.useTransition();
649
+ };
650
+ exports2.version = "19.2.5";
651
+ }
652
+ });
653
+
654
+ // node_modules/react/cjs/react.development.js
655
+ var require_react_development = __commonJS({
656
+ "node_modules/react/cjs/react.development.js"(exports2, module2) {
657
+ "use strict";
658
+ "production" !== process.env.NODE_ENV && (function() {
659
+ function defineDeprecationWarning(methodName, info) {
660
+ Object.defineProperty(Component.prototype, methodName, {
661
+ get: function() {
662
+ console.warn(
663
+ "%s(...) is deprecated in plain JavaScript React classes. %s",
664
+ info[0],
665
+ info[1]
666
+ );
667
+ }
668
+ });
669
+ }
670
+ function getIteratorFn(maybeIterable) {
671
+ if (null === maybeIterable || "object" !== typeof maybeIterable)
672
+ return null;
673
+ maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
674
+ return "function" === typeof maybeIterable ? maybeIterable : null;
675
+ }
676
+ function warnNoop(publicInstance, callerName) {
677
+ publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass";
678
+ var warningKey = publicInstance + "." + callerName;
679
+ didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error(
680
+ "Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",
681
+ callerName,
682
+ publicInstance
683
+ ), didWarnStateUpdateForUnmountedComponent[warningKey] = true);
684
+ }
685
+ function Component(props, context, updater) {
686
+ this.props = props;
687
+ this.context = context;
688
+ this.refs = emptyObject;
689
+ this.updater = updater || ReactNoopUpdateQueue;
690
+ }
691
+ function ComponentDummy() {
692
+ }
693
+ function PureComponent(props, context, updater) {
694
+ this.props = props;
695
+ this.context = context;
696
+ this.refs = emptyObject;
697
+ this.updater = updater || ReactNoopUpdateQueue;
698
+ }
699
+ function noop() {
700
+ }
701
+ function testStringCoercion(value) {
702
+ return "" + value;
703
+ }
704
+ function checkKeyStringCoercion(value) {
705
+ try {
706
+ testStringCoercion(value);
707
+ var JSCompiler_inline_result = false;
708
+ } catch (e) {
709
+ JSCompiler_inline_result = true;
710
+ }
711
+ if (JSCompiler_inline_result) {
712
+ JSCompiler_inline_result = console;
713
+ var JSCompiler_temp_const = JSCompiler_inline_result.error;
714
+ var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
715
+ JSCompiler_temp_const.call(
716
+ JSCompiler_inline_result,
717
+ "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
718
+ JSCompiler_inline_result$jscomp$0
719
+ );
720
+ return testStringCoercion(value);
721
+ }
722
+ }
723
+ function getComponentNameFromType(type) {
724
+ if (null == type) return null;
725
+ if ("function" === typeof type)
726
+ return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
727
+ if ("string" === typeof type) return type;
728
+ switch (type) {
729
+ case REACT_FRAGMENT_TYPE:
730
+ return "Fragment";
731
+ case REACT_PROFILER_TYPE:
732
+ return "Profiler";
733
+ case REACT_STRICT_MODE_TYPE:
734
+ return "StrictMode";
735
+ case REACT_SUSPENSE_TYPE:
736
+ return "Suspense";
737
+ case REACT_SUSPENSE_LIST_TYPE:
738
+ return "SuspenseList";
739
+ case REACT_ACTIVITY_TYPE:
740
+ return "Activity";
741
+ }
742
+ if ("object" === typeof type)
743
+ switch ("number" === typeof type.tag && console.error(
744
+ "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
745
+ ), type.$$typeof) {
746
+ case REACT_PORTAL_TYPE:
747
+ return "Portal";
748
+ case REACT_CONTEXT_TYPE:
749
+ return type.displayName || "Context";
750
+ case REACT_CONSUMER_TYPE:
751
+ return (type._context.displayName || "Context") + ".Consumer";
752
+ case REACT_FORWARD_REF_TYPE:
753
+ var innerType = type.render;
754
+ type = type.displayName;
755
+ type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
756
+ return type;
757
+ case REACT_MEMO_TYPE:
758
+ return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
759
+ case REACT_LAZY_TYPE:
760
+ innerType = type._payload;
761
+ type = type._init;
762
+ try {
763
+ return getComponentNameFromType(type(innerType));
764
+ } catch (x) {
765
+ }
766
+ }
767
+ return null;
768
+ }
769
+ function getTaskName(type) {
770
+ if (type === REACT_FRAGMENT_TYPE) return "<>";
771
+ if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
772
+ return "<...>";
773
+ try {
774
+ var name = getComponentNameFromType(type);
775
+ return name ? "<" + name + ">" : "<...>";
776
+ } catch (x) {
777
+ return "<...>";
778
+ }
779
+ }
780
+ function getOwner() {
781
+ var dispatcher = ReactSharedInternals.A;
782
+ return null === dispatcher ? null : dispatcher.getOwner();
783
+ }
784
+ function UnknownOwner() {
785
+ return Error("react-stack-top-frame");
786
+ }
787
+ function hasValidKey(config) {
788
+ if (hasOwnProperty.call(config, "key")) {
789
+ var getter = Object.getOwnPropertyDescriptor(config, "key").get;
790
+ if (getter && getter.isReactWarning) return false;
791
+ }
792
+ return void 0 !== config.key;
793
+ }
794
+ function defineKeyPropWarningGetter(props, displayName) {
795
+ function warnAboutAccessingKey() {
796
+ specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
797
+ "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
798
+ displayName
799
+ ));
800
+ }
801
+ warnAboutAccessingKey.isReactWarning = true;
802
+ Object.defineProperty(props, "key", {
803
+ get: warnAboutAccessingKey,
804
+ configurable: true
805
+ });
806
+ }
807
+ function elementRefGetterWithDeprecationWarning() {
808
+ var componentName = getComponentNameFromType(this.type);
809
+ didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
810
+ "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
811
+ ));
812
+ componentName = this.props.ref;
813
+ return void 0 !== componentName ? componentName : null;
814
+ }
815
+ function ReactElement(type, key, props, owner, debugStack, debugTask) {
816
+ var refProp = props.ref;
817
+ type = {
818
+ $$typeof: REACT_ELEMENT_TYPE,
819
+ type,
820
+ key,
821
+ props,
822
+ _owner: owner
823
+ };
824
+ null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
825
+ enumerable: false,
826
+ get: elementRefGetterWithDeprecationWarning
827
+ }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
828
+ type._store = {};
829
+ Object.defineProperty(type._store, "validated", {
830
+ configurable: false,
831
+ enumerable: false,
832
+ writable: true,
833
+ value: 0
834
+ });
835
+ Object.defineProperty(type, "_debugInfo", {
836
+ configurable: false,
837
+ enumerable: false,
838
+ writable: true,
839
+ value: null
840
+ });
841
+ Object.defineProperty(type, "_debugStack", {
842
+ configurable: false,
843
+ enumerable: false,
844
+ writable: true,
845
+ value: debugStack
846
+ });
847
+ Object.defineProperty(type, "_debugTask", {
848
+ configurable: false,
849
+ enumerable: false,
850
+ writable: true,
851
+ value: debugTask
852
+ });
853
+ Object.freeze && (Object.freeze(type.props), Object.freeze(type));
854
+ return type;
855
+ }
856
+ function cloneAndReplaceKey(oldElement, newKey) {
857
+ newKey = ReactElement(
858
+ oldElement.type,
859
+ newKey,
860
+ oldElement.props,
861
+ oldElement._owner,
862
+ oldElement._debugStack,
863
+ oldElement._debugTask
864
+ );
865
+ oldElement._store && (newKey._store.validated = oldElement._store.validated);
866
+ return newKey;
867
+ }
868
+ function validateChildKeys(node) {
869
+ isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
870
+ }
871
+ function isValidElement(object) {
872
+ return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
873
+ }
874
+ function escape(key) {
875
+ var escaperLookup = { "=": "=0", ":": "=2" };
876
+ return "$" + key.replace(/[=:]/g, function(match) {
877
+ return escaperLookup[match];
878
+ });
879
+ }
880
+ function getElementKey(element, index) {
881
+ return "object" === typeof element && null !== element && null != element.key ? (checkKeyStringCoercion(element.key), escape("" + element.key)) : index.toString(36);
882
+ }
883
+ function resolveThenable(thenable) {
884
+ switch (thenable.status) {
885
+ case "fulfilled":
886
+ return thenable.value;
887
+ case "rejected":
888
+ throw thenable.reason;
889
+ default:
890
+ switch ("string" === typeof thenable.status ? thenable.then(noop, noop) : (thenable.status = "pending", thenable.then(
891
+ function(fulfilledValue) {
892
+ "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
893
+ },
894
+ function(error) {
895
+ "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error);
896
+ }
897
+ )), thenable.status) {
898
+ case "fulfilled":
899
+ return thenable.value;
900
+ case "rejected":
901
+ throw thenable.reason;
902
+ }
903
+ }
904
+ throw thenable;
905
+ }
906
+ function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
907
+ var type = typeof children;
908
+ if ("undefined" === type || "boolean" === type) children = null;
909
+ var invokeCallback = false;
910
+ if (null === children) invokeCallback = true;
911
+ else
912
+ switch (type) {
913
+ case "bigint":
914
+ case "string":
915
+ case "number":
916
+ invokeCallback = true;
917
+ break;
918
+ case "object":
919
+ switch (children.$$typeof) {
920
+ case REACT_ELEMENT_TYPE:
921
+ case REACT_PORTAL_TYPE:
922
+ invokeCallback = true;
923
+ break;
924
+ case REACT_LAZY_TYPE:
925
+ return invokeCallback = children._init, mapIntoArray(
926
+ invokeCallback(children._payload),
927
+ array,
928
+ escapedPrefix,
929
+ nameSoFar,
930
+ callback
931
+ );
932
+ }
933
+ }
934
+ if (invokeCallback) {
935
+ invokeCallback = children;
936
+ callback = callback(invokeCallback);
937
+ var childKey = "" === nameSoFar ? "." + getElementKey(invokeCallback, 0) : nameSoFar;
938
+ isArrayImpl(callback) ? (escapedPrefix = "", null != childKey && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) {
939
+ return c;
940
+ })) : null != callback && (isValidElement(callback) && (null != callback.key && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey(
941
+ callback,
942
+ escapedPrefix + (null == callback.key || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace(
943
+ userProvidedKeyEscapeRegex,
944
+ "$&/"
945
+ ) + "/") + childKey
946
+ ), "" !== nameSoFar && null != invokeCallback && isValidElement(invokeCallback) && null == invokeCallback.key && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array.push(callback));
947
+ return 1;
948
+ }
949
+ invokeCallback = 0;
950
+ childKey = "" === nameSoFar ? "." : nameSoFar + ":";
951
+ if (isArrayImpl(children))
952
+ for (var i = 0; i < children.length; i++)
953
+ nameSoFar = children[i], type = childKey + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(
954
+ nameSoFar,
955
+ array,
956
+ escapedPrefix,
957
+ type,
958
+ callback
959
+ );
960
+ else if (i = getIteratorFn(children), "function" === typeof i)
961
+ for (i === children.entries && (didWarnAboutMaps || console.warn(
962
+ "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
963
+ ), didWarnAboutMaps = true), children = i.call(children), i = 0; !(nameSoFar = children.next()).done; )
964
+ nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(
965
+ nameSoFar,
966
+ array,
967
+ escapedPrefix,
968
+ type,
969
+ callback
970
+ );
971
+ else if ("object" === type) {
972
+ if ("function" === typeof children.then)
973
+ return mapIntoArray(
974
+ resolveThenable(children),
975
+ array,
976
+ escapedPrefix,
977
+ nameSoFar,
978
+ callback
979
+ );
980
+ array = String(children);
981
+ throw Error(
982
+ "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead."
983
+ );
984
+ }
985
+ return invokeCallback;
986
+ }
987
+ function mapChildren(children, func, context) {
988
+ if (null == children) return children;
989
+ var result = [], count = 0;
990
+ mapIntoArray(children, result, "", "", function(child) {
991
+ return func.call(context, child, count++);
992
+ });
993
+ return result;
994
+ }
995
+ function lazyInitializer(payload) {
996
+ if (-1 === payload._status) {
997
+ var ioInfo = payload._ioInfo;
998
+ null != ioInfo && (ioInfo.start = ioInfo.end = performance.now());
999
+ ioInfo = payload._result;
1000
+ var thenable = ioInfo();
1001
+ thenable.then(
1002
+ function(moduleObject) {
1003
+ if (0 === payload._status || -1 === payload._status) {
1004
+ payload._status = 1;
1005
+ payload._result = moduleObject;
1006
+ var _ioInfo = payload._ioInfo;
1007
+ null != _ioInfo && (_ioInfo.end = performance.now());
1008
+ void 0 === thenable.status && (thenable.status = "fulfilled", thenable.value = moduleObject);
1009
+ }
1010
+ },
1011
+ function(error) {
1012
+ if (0 === payload._status || -1 === payload._status) {
1013
+ payload._status = 2;
1014
+ payload._result = error;
1015
+ var _ioInfo2 = payload._ioInfo;
1016
+ null != _ioInfo2 && (_ioInfo2.end = performance.now());
1017
+ void 0 === thenable.status && (thenable.status = "rejected", thenable.reason = error);
1018
+ }
1019
+ }
1020
+ );
1021
+ ioInfo = payload._ioInfo;
1022
+ if (null != ioInfo) {
1023
+ ioInfo.value = thenable;
1024
+ var displayName = thenable.displayName;
1025
+ "string" === typeof displayName && (ioInfo.name = displayName);
1026
+ }
1027
+ -1 === payload._status && (payload._status = 0, payload._result = thenable);
1028
+ }
1029
+ if (1 === payload._status)
1030
+ return ioInfo = payload._result, void 0 === ioInfo && console.error(
1031
+ "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",
1032
+ ioInfo
1033
+ ), "default" in ioInfo || console.error(
1034
+ "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))",
1035
+ ioInfo
1036
+ ), ioInfo.default;
1037
+ throw payload._result;
1038
+ }
1039
+ function resolveDispatcher() {
1040
+ var dispatcher = ReactSharedInternals.H;
1041
+ null === dispatcher && console.error(
1042
+ "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
1043
+ );
1044
+ return dispatcher;
1045
+ }
1046
+ function releaseAsyncTransition() {
1047
+ ReactSharedInternals.asyncTransitions--;
1048
+ }
1049
+ function enqueueTask(task) {
1050
+ if (null === enqueueTaskImpl)
1051
+ try {
1052
+ var requireString = ("require" + Math.random()).slice(0, 7);
1053
+ enqueueTaskImpl = (module2 && module2[requireString]).call(
1054
+ module2,
1055
+ "timers"
1056
+ ).setImmediate;
1057
+ } catch (_err) {
1058
+ enqueueTaskImpl = function(callback) {
1059
+ false === didWarnAboutMessageChannel && (didWarnAboutMessageChannel = true, "undefined" === typeof MessageChannel && console.error(
1060
+ "This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."
1061
+ ));
1062
+ var channel = new MessageChannel();
1063
+ channel.port1.onmessage = callback;
1064
+ channel.port2.postMessage(void 0);
1065
+ };
1066
+ }
1067
+ return enqueueTaskImpl(task);
1068
+ }
1069
+ function aggregateErrors(errors) {
1070
+ return 1 < errors.length && "function" === typeof AggregateError ? new AggregateError(errors) : errors[0];
1071
+ }
1072
+ function popActScope(prevActQueue, prevActScopeDepth) {
1073
+ prevActScopeDepth !== actScopeDepth - 1 && console.error(
1074
+ "You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "
1075
+ );
1076
+ actScopeDepth = prevActScopeDepth;
1077
+ }
1078
+ function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
1079
+ var queue = ReactSharedInternals.actQueue;
1080
+ if (null !== queue)
1081
+ if (0 !== queue.length)
1082
+ try {
1083
+ flushActQueue(queue);
1084
+ enqueueTask(function() {
1085
+ return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
1086
+ });
1087
+ return;
1088
+ } catch (error) {
1089
+ ReactSharedInternals.thrownErrors.push(error);
1090
+ }
1091
+ else ReactSharedInternals.actQueue = null;
1092
+ 0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve(returnValue);
1093
+ }
1094
+ function flushActQueue(queue) {
1095
+ if (!isFlushing) {
1096
+ isFlushing = true;
1097
+ var i = 0;
1098
+ try {
1099
+ for (; i < queue.length; i++) {
1100
+ var callback = queue[i];
1101
+ do {
1102
+ ReactSharedInternals.didUsePromise = false;
1103
+ var continuation = callback(false);
1104
+ if (null !== continuation) {
1105
+ if (ReactSharedInternals.didUsePromise) {
1106
+ queue[i] = callback;
1107
+ queue.splice(0, i);
1108
+ return;
1109
+ }
1110
+ callback = continuation;
1111
+ } else break;
1112
+ } while (1);
1113
+ }
1114
+ queue.length = 0;
1115
+ } catch (error) {
1116
+ queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error);
1117
+ } finally {
1118
+ isFlushing = false;
1119
+ }
1120
+ }
1121
+ }
1122
+ "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
1123
+ var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = {
1124
+ isMounted: function() {
1125
+ return false;
1126
+ },
1127
+ enqueueForceUpdate: function(publicInstance) {
1128
+ warnNoop(publicInstance, "forceUpdate");
1129
+ },
1130
+ enqueueReplaceState: function(publicInstance) {
1131
+ warnNoop(publicInstance, "replaceState");
1132
+ },
1133
+ enqueueSetState: function(publicInstance) {
1134
+ warnNoop(publicInstance, "setState");
1135
+ }
1136
+ }, assign = Object.assign, emptyObject = {};
1137
+ Object.freeze(emptyObject);
1138
+ Component.prototype.isReactComponent = {};
1139
+ Component.prototype.setState = function(partialState, callback) {
1140
+ if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState)
1141
+ throw Error(
1142
+ "takes an object of state variables to update or a function which returns an object of state variables."
1143
+ );
1144
+ this.updater.enqueueSetState(this, partialState, callback, "setState");
1145
+ };
1146
+ Component.prototype.forceUpdate = function(callback) {
1147
+ this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
1148
+ };
1149
+ var deprecatedAPIs = {
1150
+ isMounted: [
1151
+ "isMounted",
1152
+ "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
1153
+ ],
1154
+ replaceState: [
1155
+ "replaceState",
1156
+ "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
1157
+ ]
1158
+ };
1159
+ for (fnName in deprecatedAPIs)
1160
+ deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
1161
+ ComponentDummy.prototype = Component.prototype;
1162
+ deprecatedAPIs = PureComponent.prototype = new ComponentDummy();
1163
+ deprecatedAPIs.constructor = PureComponent;
1164
+ assign(deprecatedAPIs, Component.prototype);
1165
+ deprecatedAPIs.isPureReactComponent = true;
1166
+ var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = {
1167
+ H: null,
1168
+ A: null,
1169
+ T: null,
1170
+ S: null,
1171
+ actQueue: null,
1172
+ asyncTransitions: 0,
1173
+ isBatchingLegacy: false,
1174
+ didScheduleLegacyUpdate: false,
1175
+ didUsePromise: false,
1176
+ thrownErrors: [],
1177
+ getCurrentStack: null,
1178
+ recentlyCreatedOwnerStacks: 0
1179
+ }, hasOwnProperty = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() {
1180
+ return null;
1181
+ };
1182
+ deprecatedAPIs = {
1183
+ react_stack_bottom_frame: function(callStackForError) {
1184
+ return callStackForError();
1185
+ }
1186
+ };
1187
+ var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
1188
+ var didWarnAboutElementRef = {};
1189
+ var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(
1190
+ deprecatedAPIs,
1191
+ UnknownOwner
1192
+ )();
1193
+ var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
1194
+ var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
1195
+ if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
1196
+ var event = new window.ErrorEvent("error", {
1197
+ bubbles: true,
1198
+ cancelable: true,
1199
+ message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
1200
+ error
1201
+ });
1202
+ if (!window.dispatchEvent(event)) return;
1203
+ } else if ("object" === typeof process && "function" === typeof process.emit) {
1204
+ process.emit("uncaughtException", error);
1205
+ return;
1206
+ }
1207
+ console.error(error);
1208
+ }, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = "function" === typeof queueMicrotask ? function(callback) {
1209
+ queueMicrotask(function() {
1210
+ return queueMicrotask(callback);
1211
+ });
1212
+ } : enqueueTask;
1213
+ deprecatedAPIs = Object.freeze({
1214
+ __proto__: null,
1215
+ c: function(size) {
1216
+ return resolveDispatcher().useMemoCache(size);
1217
+ }
1218
+ });
1219
+ var fnName = {
1220
+ map: mapChildren,
1221
+ forEach: function(children, forEachFunc, forEachContext) {
1222
+ mapChildren(
1223
+ children,
1224
+ function() {
1225
+ forEachFunc.apply(this, arguments);
1226
+ },
1227
+ forEachContext
1228
+ );
1229
+ },
1230
+ count: function(children) {
1231
+ var n = 0;
1232
+ mapChildren(children, function() {
1233
+ n++;
1234
+ });
1235
+ return n;
1236
+ },
1237
+ toArray: function(children) {
1238
+ return mapChildren(children, function(child) {
1239
+ return child;
1240
+ }) || [];
1241
+ },
1242
+ only: function(children) {
1243
+ if (!isValidElement(children))
1244
+ throw Error(
1245
+ "React.Children.only expected to receive a single React element child."
1246
+ );
1247
+ return children;
1248
+ }
1249
+ };
1250
+ exports2.Activity = REACT_ACTIVITY_TYPE;
1251
+ exports2.Children = fnName;
1252
+ exports2.Component = Component;
1253
+ exports2.Fragment = REACT_FRAGMENT_TYPE;
1254
+ exports2.Profiler = REACT_PROFILER_TYPE;
1255
+ exports2.PureComponent = PureComponent;
1256
+ exports2.StrictMode = REACT_STRICT_MODE_TYPE;
1257
+ exports2.Suspense = REACT_SUSPENSE_TYPE;
1258
+ exports2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
1259
+ exports2.__COMPILER_RUNTIME = deprecatedAPIs;
1260
+ exports2.act = function(callback) {
1261
+ var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth;
1262
+ actScopeDepth++;
1263
+ var queue = ReactSharedInternals.actQueue = null !== prevActQueue ? prevActQueue : [], didAwaitActCall = false;
1264
+ try {
1265
+ var result = callback();
1266
+ } catch (error) {
1267
+ ReactSharedInternals.thrownErrors.push(error);
1268
+ }
1269
+ if (0 < ReactSharedInternals.thrownErrors.length)
1270
+ throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
1271
+ if (null !== result && "object" === typeof result && "function" === typeof result.then) {
1272
+ var thenable = result;
1273
+ queueSeveralMicrotasks(function() {
1274
+ didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
1275
+ "You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"
1276
+ ));
1277
+ });
1278
+ return {
1279
+ then: function(resolve, reject) {
1280
+ didAwaitActCall = true;
1281
+ thenable.then(
1282
+ function(returnValue) {
1283
+ popActScope(prevActQueue, prevActScopeDepth);
1284
+ if (0 === prevActScopeDepth) {
1285
+ try {
1286
+ flushActQueue(queue), enqueueTask(function() {
1287
+ return recursivelyFlushAsyncActWork(
1288
+ returnValue,
1289
+ resolve,
1290
+ reject
1291
+ );
1292
+ });
1293
+ } catch (error$0) {
1294
+ ReactSharedInternals.thrownErrors.push(error$0);
1295
+ }
1296
+ if (0 < ReactSharedInternals.thrownErrors.length) {
1297
+ var _thrownError = aggregateErrors(
1298
+ ReactSharedInternals.thrownErrors
1299
+ );
1300
+ ReactSharedInternals.thrownErrors.length = 0;
1301
+ reject(_thrownError);
1302
+ }
1303
+ } else resolve(returnValue);
1304
+ },
1305
+ function(error) {
1306
+ popActScope(prevActQueue, prevActScopeDepth);
1307
+ 0 < ReactSharedInternals.thrownErrors.length ? (error = aggregateErrors(
1308
+ ReactSharedInternals.thrownErrors
1309
+ ), ReactSharedInternals.thrownErrors.length = 0, reject(error)) : reject(error);
1310
+ }
1311
+ );
1312
+ }
1313
+ };
1314
+ }
1315
+ var returnValue$jscomp$0 = result;
1316
+ popActScope(prevActQueue, prevActScopeDepth);
1317
+ 0 === prevActScopeDepth && (flushActQueue(queue), 0 !== queue.length && queueSeveralMicrotasks(function() {
1318
+ didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
1319
+ "A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"
1320
+ ));
1321
+ }), ReactSharedInternals.actQueue = null);
1322
+ if (0 < ReactSharedInternals.thrownErrors.length)
1323
+ throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
1324
+ return {
1325
+ then: function(resolve, reject) {
1326
+ didAwaitActCall = true;
1327
+ 0 === prevActScopeDepth ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
1328
+ return recursivelyFlushAsyncActWork(
1329
+ returnValue$jscomp$0,
1330
+ resolve,
1331
+ reject
1332
+ );
1333
+ })) : resolve(returnValue$jscomp$0);
1334
+ }
1335
+ };
1336
+ };
1337
+ exports2.cache = function(fn) {
1338
+ return function() {
1339
+ return fn.apply(null, arguments);
1340
+ };
1341
+ };
1342
+ exports2.cacheSignal = function() {
1343
+ return null;
1344
+ };
1345
+ exports2.captureOwnerStack = function() {
1346
+ var getCurrentStack = ReactSharedInternals.getCurrentStack;
1347
+ return null === getCurrentStack ? null : getCurrentStack();
1348
+ };
1349
+ exports2.cloneElement = function(element, config, children) {
1350
+ if (null === element || void 0 === element)
1351
+ throw Error(
1352
+ "The argument must be a React element, but you passed " + element + "."
1353
+ );
1354
+ var props = assign({}, element.props), key = element.key, owner = element._owner;
1355
+ if (null != config) {
1356
+ var JSCompiler_inline_result;
1357
+ a: {
1358
+ if (hasOwnProperty.call(config, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(
1359
+ config,
1360
+ "ref"
1361
+ ).get) && JSCompiler_inline_result.isReactWarning) {
1362
+ JSCompiler_inline_result = false;
1363
+ break a;
1364
+ }
1365
+ JSCompiler_inline_result = void 0 !== config.ref;
1366
+ }
1367
+ JSCompiler_inline_result && (owner = getOwner());
1368
+ hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key);
1369
+ for (propName in config)
1370
+ !hasOwnProperty.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]);
1371
+ }
1372
+ var propName = arguments.length - 2;
1373
+ if (1 === propName) props.children = children;
1374
+ else if (1 < propName) {
1375
+ JSCompiler_inline_result = Array(propName);
1376
+ for (var i = 0; i < propName; i++)
1377
+ JSCompiler_inline_result[i] = arguments[i + 2];
1378
+ props.children = JSCompiler_inline_result;
1379
+ }
1380
+ props = ReactElement(
1381
+ element.type,
1382
+ key,
1383
+ props,
1384
+ owner,
1385
+ element._debugStack,
1386
+ element._debugTask
1387
+ );
1388
+ for (key = 2; key < arguments.length; key++)
1389
+ validateChildKeys(arguments[key]);
1390
+ return props;
1391
+ };
1392
+ exports2.createContext = function(defaultValue) {
1393
+ defaultValue = {
1394
+ $$typeof: REACT_CONTEXT_TYPE,
1395
+ _currentValue: defaultValue,
1396
+ _currentValue2: defaultValue,
1397
+ _threadCount: 0,
1398
+ Provider: null,
1399
+ Consumer: null
1400
+ };
1401
+ defaultValue.Provider = defaultValue;
1402
+ defaultValue.Consumer = {
1403
+ $$typeof: REACT_CONSUMER_TYPE,
1404
+ _context: defaultValue
1405
+ };
1406
+ defaultValue._currentRenderer = null;
1407
+ defaultValue._currentRenderer2 = null;
1408
+ return defaultValue;
1409
+ };
1410
+ exports2.createElement = function(type, config, children) {
1411
+ for (var i = 2; i < arguments.length; i++)
1412
+ validateChildKeys(arguments[i]);
1413
+ i = {};
1414
+ var key = null;
1415
+ if (null != config)
1416
+ for (propName in didWarnAboutOldJSXRuntime || !("__self" in config) || "key" in config || (didWarnAboutOldJSXRuntime = true, console.warn(
1417
+ "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform"
1418
+ )), hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key), config)
1419
+ hasOwnProperty.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (i[propName] = config[propName]);
1420
+ var childrenLength = arguments.length - 2;
1421
+ if (1 === childrenLength) i.children = children;
1422
+ else if (1 < childrenLength) {
1423
+ for (var childArray = Array(childrenLength), _i = 0; _i < childrenLength; _i++)
1424
+ childArray[_i] = arguments[_i + 2];
1425
+ Object.freeze && Object.freeze(childArray);
1426
+ i.children = childArray;
1427
+ }
1428
+ if (type && type.defaultProps)
1429
+ for (propName in childrenLength = type.defaultProps, childrenLength)
1430
+ void 0 === i[propName] && (i[propName] = childrenLength[propName]);
1431
+ key && defineKeyPropWarningGetter(
1432
+ i,
1433
+ "function" === typeof type ? type.displayName || type.name || "Unknown" : type
1434
+ );
1435
+ var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
1436
+ return ReactElement(
1437
+ type,
1438
+ key,
1439
+ i,
1440
+ getOwner(),
1441
+ propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
1442
+ propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask
1443
+ );
1444
+ };
1445
+ exports2.createRef = function() {
1446
+ var refObject = { current: null };
1447
+ Object.seal(refObject);
1448
+ return refObject;
1449
+ };
1450
+ exports2.forwardRef = function(render) {
1451
+ null != render && render.$$typeof === REACT_MEMO_TYPE ? console.error(
1452
+ "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."
1453
+ ) : "function" !== typeof render ? console.error(
1454
+ "forwardRef requires a render function but was given %s.",
1455
+ null === render ? "null" : typeof render
1456
+ ) : 0 !== render.length && 2 !== render.length && console.error(
1457
+ "forwardRef render functions accept exactly two parameters: props and ref. %s",
1458
+ 1 === render.length ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."
1459
+ );
1460
+ null != render && null != render.defaultProps && console.error(
1461
+ "forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?"
1462
+ );
1463
+ var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }, ownName;
1464
+ Object.defineProperty(elementType, "displayName", {
1465
+ enumerable: false,
1466
+ configurable: true,
1467
+ get: function() {
1468
+ return ownName;
1469
+ },
1470
+ set: function(name) {
1471
+ ownName = name;
1472
+ render.name || render.displayName || (Object.defineProperty(render, "name", { value: name }), render.displayName = name);
1473
+ }
1474
+ });
1475
+ return elementType;
1476
+ };
1477
+ exports2.isValidElement = isValidElement;
1478
+ exports2.lazy = function(ctor) {
1479
+ ctor = { _status: -1, _result: ctor };
1480
+ var lazyType = {
1481
+ $$typeof: REACT_LAZY_TYPE,
1482
+ _payload: ctor,
1483
+ _init: lazyInitializer
1484
+ }, ioInfo = {
1485
+ name: "lazy",
1486
+ start: -1,
1487
+ end: -1,
1488
+ value: null,
1489
+ owner: null,
1490
+ debugStack: Error("react-stack-top-frame"),
1491
+ debugTask: console.createTask ? console.createTask("lazy()") : null
1492
+ };
1493
+ ctor._ioInfo = ioInfo;
1494
+ lazyType._debugInfo = [{ awaited: ioInfo }];
1495
+ return lazyType;
1496
+ };
1497
+ exports2.memo = function(type, compare) {
1498
+ null == type && console.error(
1499
+ "memo: The first argument must be a component. Instead received: %s",
1500
+ null === type ? "null" : typeof type
1501
+ );
1502
+ compare = {
1503
+ $$typeof: REACT_MEMO_TYPE,
1504
+ type,
1505
+ compare: void 0 === compare ? null : compare
1506
+ };
1507
+ var ownName;
1508
+ Object.defineProperty(compare, "displayName", {
1509
+ enumerable: false,
1510
+ configurable: true,
1511
+ get: function() {
1512
+ return ownName;
1513
+ },
1514
+ set: function(name) {
1515
+ ownName = name;
1516
+ type.name || type.displayName || (Object.defineProperty(type, "name", { value: name }), type.displayName = name);
1517
+ }
1518
+ });
1519
+ return compare;
1520
+ };
1521
+ exports2.startTransition = function(scope) {
1522
+ var prevTransition = ReactSharedInternals.T, currentTransition = {};
1523
+ currentTransition._updatedFibers = /* @__PURE__ */ new Set();
1524
+ ReactSharedInternals.T = currentTransition;
1525
+ try {
1526
+ var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
1527
+ null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
1528
+ "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop, reportGlobalError));
1529
+ } catch (error) {
1530
+ reportGlobalError(error);
1531
+ } finally {
1532
+ null === prevTransition && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn(
1533
+ "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
1534
+ )), null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
1535
+ "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
1536
+ ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
1537
+ }
1538
+ };
1539
+ exports2.unstable_useCacheRefresh = function() {
1540
+ return resolveDispatcher().useCacheRefresh();
1541
+ };
1542
+ exports2.use = function(usable) {
1543
+ return resolveDispatcher().use(usable);
1544
+ };
1545
+ exports2.useActionState = function(action, initialState, permalink) {
1546
+ return resolveDispatcher().useActionState(
1547
+ action,
1548
+ initialState,
1549
+ permalink
1550
+ );
1551
+ };
1552
+ exports2.useCallback = function(callback, deps) {
1553
+ return resolveDispatcher().useCallback(callback, deps);
1554
+ };
1555
+ exports2.useContext = function(Context) {
1556
+ var dispatcher = resolveDispatcher();
1557
+ Context.$$typeof === REACT_CONSUMER_TYPE && console.error(
1558
+ "Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"
1559
+ );
1560
+ return dispatcher.useContext(Context);
1561
+ };
1562
+ exports2.useDebugValue = function(value, formatterFn) {
1563
+ return resolveDispatcher().useDebugValue(value, formatterFn);
1564
+ };
1565
+ exports2.useDeferredValue = function(value, initialValue) {
1566
+ return resolveDispatcher().useDeferredValue(value, initialValue);
1567
+ };
1568
+ exports2.useEffect = function(create2, deps) {
1569
+ null == create2 && console.warn(
1570
+ "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"
1571
+ );
1572
+ return resolveDispatcher().useEffect(create2, deps);
1573
+ };
1574
+ exports2.useEffectEvent = function(callback) {
1575
+ return resolveDispatcher().useEffectEvent(callback);
1576
+ };
1577
+ exports2.useId = function() {
1578
+ return resolveDispatcher().useId();
1579
+ };
1580
+ exports2.useImperativeHandle = function(ref, create2, deps) {
1581
+ return resolveDispatcher().useImperativeHandle(ref, create2, deps);
1582
+ };
1583
+ exports2.useInsertionEffect = function(create2, deps) {
1584
+ null == create2 && console.warn(
1585
+ "React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"
1586
+ );
1587
+ return resolveDispatcher().useInsertionEffect(create2, deps);
1588
+ };
1589
+ exports2.useLayoutEffect = function(create2, deps) {
1590
+ null == create2 && console.warn(
1591
+ "React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"
1592
+ );
1593
+ return resolveDispatcher().useLayoutEffect(create2, deps);
1594
+ };
1595
+ exports2.useMemo = function(create2, deps) {
1596
+ return resolveDispatcher().useMemo(create2, deps);
1597
+ };
1598
+ exports2.useOptimistic = function(passthrough, reducer) {
1599
+ return resolveDispatcher().useOptimistic(passthrough, reducer);
1600
+ };
1601
+ exports2.useReducer = function(reducer, initialArg, init) {
1602
+ return resolveDispatcher().useReducer(reducer, initialArg, init);
1603
+ };
1604
+ exports2.useRef = function(initialValue) {
1605
+ return resolveDispatcher().useRef(initialValue);
1606
+ };
1607
+ exports2.useState = function(initialState) {
1608
+ return resolveDispatcher().useState(initialState);
1609
+ };
1610
+ exports2.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
1611
+ return resolveDispatcher().useSyncExternalStore(
1612
+ subscribe,
1613
+ getSnapshot,
1614
+ getServerSnapshot
1615
+ );
1616
+ };
1617
+ exports2.useTransition = function() {
1618
+ return resolveDispatcher().useTransition();
1619
+ };
1620
+ exports2.version = "19.2.5";
1621
+ "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
1622
+ })();
1623
+ }
1624
+ });
1625
+
1626
+ // node_modules/react/index.js
1627
+ var require_react = __commonJS({
1628
+ "node_modules/react/index.js"(exports2, module2) {
1629
+ "use strict";
1630
+ if (process.env.NODE_ENV === "production") {
1631
+ module2.exports = require_react_production();
1632
+ } else {
1633
+ module2.exports = require_react_development();
1634
+ }
1635
+ }
1636
+ });
1637
+
1638
+ // src/index.ts
1639
+ var index_exports = {};
1640
+ __export(index_exports, {
1641
+ QUEUE_COMMAND: () => QUEUE_COMMAND,
1642
+ QueueManager: () => QueueManager,
1643
+ TaskContext: () => TaskContext,
1644
+ createTaskStore: () => createTaskStore,
1645
+ engineHub: () => engineHub,
1646
+ getQueueManager: () => getQueueManager,
1647
+ persistenceManager: () => persistenceManager,
1648
+ registerAllEngines: () => registerAllEngines,
1649
+ setupBackgroundEngine: () => setupBackgroundEngine,
1650
+ sleep: () => sleep,
1651
+ useQueue: () => useQueue
1652
+ });
1653
+ module.exports = __toCommonJS(index_exports);
1654
+
1655
+ // node_modules/eventemitter3/index.mjs
1656
+ var import_index = __toESM(require_eventemitter3(), 1);
1657
+
1658
+ // node_modules/p-timeout/index.js
1659
+ var TimeoutError = class _TimeoutError extends Error {
1660
+ constructor(message, options) {
1661
+ super(message, options);
1662
+ __publicField(this, "name", "TimeoutError");
1663
+ Error.captureStackTrace?.(this, _TimeoutError);
1664
+ }
1665
+ };
1666
+ var getAbortedReason = (signal) => signal.reason ?? new DOMException("This operation was aborted.", "AbortError");
1667
+ function pTimeout(promise, options) {
1668
+ const {
1669
+ milliseconds,
1670
+ fallback,
1671
+ message,
1672
+ customTimers = { setTimeout, clearTimeout },
1673
+ signal
1674
+ } = options;
1675
+ let timer;
1676
+ let abortHandler;
1677
+ const wrappedPromise = new Promise((resolve, reject) => {
1678
+ if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) {
1679
+ throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
1680
+ }
1681
+ if (signal?.aborted) {
1682
+ reject(getAbortedReason(signal));
1683
+ return;
1684
+ }
1685
+ if (signal) {
1686
+ abortHandler = () => {
1687
+ reject(getAbortedReason(signal));
1688
+ };
1689
+ signal.addEventListener("abort", abortHandler, { once: true });
1690
+ }
1691
+ promise.then(resolve, reject);
1692
+ if (milliseconds === Number.POSITIVE_INFINITY) {
1693
+ return;
1694
+ }
1695
+ const timeoutError = new TimeoutError();
1696
+ timer = customTimers.setTimeout.call(void 0, () => {
1697
+ if (fallback) {
1698
+ try {
1699
+ resolve(fallback());
1700
+ } catch (error) {
1701
+ reject(error);
1702
+ }
1703
+ return;
1704
+ }
1705
+ if (typeof promise.cancel === "function") {
1706
+ promise.cancel();
1707
+ }
1708
+ if (message === false) {
1709
+ resolve();
1710
+ } else if (message instanceof Error) {
1711
+ reject(message);
1712
+ } else {
1713
+ timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
1714
+ reject(timeoutError);
1715
+ }
1716
+ }, milliseconds);
1717
+ });
1718
+ const cancelablePromise = wrappedPromise.finally(() => {
1719
+ cancelablePromise.clear();
1720
+ if (abortHandler && signal) {
1721
+ signal.removeEventListener("abort", abortHandler);
1722
+ }
1723
+ });
1724
+ cancelablePromise.clear = () => {
1725
+ customTimers.clearTimeout.call(void 0, timer);
1726
+ timer = void 0;
1727
+ };
1728
+ return cancelablePromise;
1729
+ }
1730
+
1731
+ // node_modules/p-queue/dist/lower-bound.js
1732
+ function lowerBound(array, value, comparator) {
1733
+ let first = 0;
1734
+ let count = array.length;
1735
+ while (count > 0) {
1736
+ const step = Math.trunc(count / 2);
1737
+ let it = first + step;
1738
+ if (comparator(array[it], value) <= 0) {
1739
+ first = ++it;
1740
+ count -= step + 1;
1741
+ } else {
1742
+ count = step;
1743
+ }
1744
+ }
1745
+ return first;
1746
+ }
1747
+
1748
+ // node_modules/p-queue/dist/priority-queue.js
1749
+ var _queue;
1750
+ var PriorityQueue = class {
1751
+ constructor() {
1752
+ __privateAdd(this, _queue, []);
1753
+ }
1754
+ enqueue(run, options) {
1755
+ const { priority = 0, id } = options ?? {};
1756
+ const element = {
1757
+ priority,
1758
+ id,
1759
+ run
1760
+ };
1761
+ if (this.size === 0 || __privateGet(this, _queue)[this.size - 1].priority >= priority) {
1762
+ __privateGet(this, _queue).push(element);
1763
+ return;
1764
+ }
1765
+ const index = lowerBound(__privateGet(this, _queue), element, (a, b) => b.priority - a.priority);
1766
+ __privateGet(this, _queue).splice(index, 0, element);
1767
+ }
1768
+ setPriority(id, priority) {
1769
+ const index = __privateGet(this, _queue).findIndex((element) => element.id === id);
1770
+ if (index === -1) {
1771
+ throw new ReferenceError(`No promise function with the id "${id}" exists in the queue.`);
1772
+ }
1773
+ const [item] = __privateGet(this, _queue).splice(index, 1);
1774
+ this.enqueue(item.run, { priority, id });
1775
+ }
1776
+ remove(idOrRun) {
1777
+ const index = __privateGet(this, _queue).findIndex((element) => {
1778
+ if (typeof idOrRun === "string") {
1779
+ return element.id === idOrRun;
1780
+ }
1781
+ return element.run === idOrRun;
1782
+ });
1783
+ if (index !== -1) {
1784
+ __privateGet(this, _queue).splice(index, 1);
1785
+ }
1786
+ }
1787
+ dequeue() {
1788
+ const item = __privateGet(this, _queue).shift();
1789
+ return item?.run;
1790
+ }
1791
+ filter(options) {
1792
+ return __privateGet(this, _queue).filter((element) => element.priority === options.priority).map((element) => element.run);
1793
+ }
1794
+ get size() {
1795
+ return __privateGet(this, _queue).length;
1796
+ }
1797
+ };
1798
+ _queue = new WeakMap();
1799
+
1800
+ // node_modules/p-queue/dist/index.js
1801
+ var _carryoverIntervalCount, _isIntervalIgnored, _intervalCount, _intervalCap, _rateLimitedInInterval, _rateLimitFlushScheduled, _interval, _intervalEnd, _lastExecutionTime, _intervalId, _timeoutId, _strict, _strictTicks, _strictTicksStartIndex, _queue2, _queueClass, _pending, _concurrency, _isPaused, _idAssigner, _runningTasks, _queueAbortListenerCleanupFunctions, _PQueue_instances, cleanupStrictTicks_fn, consumeIntervalSlot_fn, rollbackIntervalSlot_fn, getActiveTicksCount_fn, doesIntervalAllowAnother_get, doesConcurrentAllowAnother_get, next_fn, onResumeInterval_fn, isIntervalPausedAt_fn, createIntervalTimeout_fn, clearIntervalTimer_fn, clearTimeoutTimer_fn, tryToStartAnother_fn, initializeIntervalIfNeeded_fn, onInterval_fn, processQueue_fn, onEvent_fn, setupRateLimitTracking_fn, scheduleRateLimitUpdate_fn, rollbackIntervalConsumption_fn, updateRateLimitState_fn;
1802
+ var PQueue = class extends import_index.default {
1803
+ constructor(options) {
1804
+ super();
1805
+ __privateAdd(this, _PQueue_instances);
1806
+ __privateAdd(this, _carryoverIntervalCount);
1807
+ __privateAdd(this, _isIntervalIgnored);
1808
+ __privateAdd(this, _intervalCount, 0);
1809
+ __privateAdd(this, _intervalCap);
1810
+ __privateAdd(this, _rateLimitedInInterval, false);
1811
+ __privateAdd(this, _rateLimitFlushScheduled, false);
1812
+ __privateAdd(this, _interval);
1813
+ __privateAdd(this, _intervalEnd, 0);
1814
+ __privateAdd(this, _lastExecutionTime, 0);
1815
+ __privateAdd(this, _intervalId);
1816
+ __privateAdd(this, _timeoutId);
1817
+ __privateAdd(this, _strict);
1818
+ // Circular buffer implementation for better performance
1819
+ __privateAdd(this, _strictTicks, []);
1820
+ __privateAdd(this, _strictTicksStartIndex, 0);
1821
+ __privateAdd(this, _queue2);
1822
+ __privateAdd(this, _queueClass);
1823
+ __privateAdd(this, _pending, 0);
1824
+ // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194
1825
+ __privateAdd(this, _concurrency);
1826
+ __privateAdd(this, _isPaused);
1827
+ // Use to assign a unique identifier to a promise function, if not explicitly specified
1828
+ __privateAdd(this, _idAssigner, 1n);
1829
+ // Track currently running tasks for debugging
1830
+ __privateAdd(this, _runningTasks, /* @__PURE__ */ new Map());
1831
+ __privateAdd(this, _queueAbortListenerCleanupFunctions, /* @__PURE__ */ new Set());
1832
+ /**
1833
+ Get or set the default timeout for all tasks. Can be changed at runtime.
1834
+
1835
+ Operations will throw a `TimeoutError` if they don't complete within the specified time.
1836
+
1837
+ The timeout begins when the operation is dequeued and starts execution, not while it's waiting in the queue.
1838
+
1839
+ @example
1840
+ ```
1841
+ const queue = new PQueue({timeout: 5000});
1842
+
1843
+ // Change timeout for all future tasks
1844
+ queue.timeout = 10000;
1845
+ ```
1846
+ */
1847
+ __publicField(this, "timeout");
1848
+ options = {
1849
+ carryoverIntervalCount: false,
1850
+ intervalCap: Number.POSITIVE_INFINITY,
1851
+ interval: 0,
1852
+ concurrency: Number.POSITIVE_INFINITY,
1853
+ autoStart: true,
1854
+ queueClass: PriorityQueue,
1855
+ strict: false,
1856
+ ...options
1857
+ };
1858
+ if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) {
1859
+ throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${options.intervalCap?.toString() ?? ""}\` (${typeof options.intervalCap})`);
1860
+ }
1861
+ if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) {
1862
+ throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${options.interval?.toString() ?? ""}\` (${typeof options.interval})`);
1863
+ }
1864
+ if (options.strict && options.interval === 0) {
1865
+ throw new TypeError("The `strict` option requires a non-zero `interval`");
1866
+ }
1867
+ if (options.strict && options.intervalCap === Number.POSITIVE_INFINITY) {
1868
+ throw new TypeError("The `strict` option requires a finite `intervalCap`");
1869
+ }
1870
+ __privateSet(this, _carryoverIntervalCount, options.carryoverIntervalCount ?? options.carryoverConcurrencyCount ?? false);
1871
+ __privateSet(this, _isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0);
1872
+ __privateSet(this, _intervalCap, options.intervalCap);
1873
+ __privateSet(this, _interval, options.interval);
1874
+ __privateSet(this, _strict, options.strict);
1875
+ __privateSet(this, _queue2, new options.queueClass());
1876
+ __privateSet(this, _queueClass, options.queueClass);
1877
+ this.concurrency = options.concurrency;
1878
+ if (options.timeout !== void 0 && !(Number.isFinite(options.timeout) && options.timeout > 0)) {
1879
+ throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${options.timeout}\` (${typeof options.timeout})`);
1880
+ }
1881
+ this.timeout = options.timeout;
1882
+ __privateSet(this, _isPaused, options.autoStart === false);
1883
+ __privateMethod(this, _PQueue_instances, setupRateLimitTracking_fn).call(this);
1884
+ }
1885
+ get concurrency() {
1886
+ return __privateGet(this, _concurrency);
1887
+ }
1888
+ set concurrency(newConcurrency) {
1889
+ if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) {
1890
+ throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`);
1891
+ }
1892
+ __privateSet(this, _concurrency, newConcurrency);
1893
+ __privateMethod(this, _PQueue_instances, processQueue_fn).call(this);
1894
+ }
1895
+ /**
1896
+ Updates the priority of a promise function by its id, affecting its execution order. Requires a defined concurrency limit to take effect.
1897
+
1898
+ For example, this can be used to prioritize a promise function to run earlier.
1899
+
1900
+ ```js
1901
+ import PQueue from 'p-queue';
1902
+
1903
+ const queue = new PQueue({concurrency: 1});
1904
+
1905
+ queue.add(async () => '🦄', {priority: 1});
1906
+ queue.add(async () => '🦀', {priority: 0, id: '🦀'});
1907
+ queue.add(async () => '🦄', {priority: 1});
1908
+ queue.add(async () => '🦄', {priority: 1});
1909
+
1910
+ queue.setPriority('🦀', 2);
1911
+ ```
1912
+
1913
+ In this case, the promise function with `id: '🦀'` runs second.
1914
+
1915
+ You can also deprioritize a promise function to delay its execution:
1916
+
1917
+ ```js
1918
+ import PQueue from 'p-queue';
1919
+
1920
+ const queue = new PQueue({concurrency: 1});
1921
+
1922
+ queue.add(async () => '🦄', {priority: 1});
1923
+ queue.add(async () => '🦀', {priority: 1, id: '🦀'});
1924
+ queue.add(async () => '🦄');
1925
+ queue.add(async () => '🦄', {priority: 0});
1926
+
1927
+ queue.setPriority('🦀', -1);
1928
+ ```
1929
+ Here, the promise function with `id: '🦀'` executes last.
1930
+ */
1931
+ setPriority(id, priority) {
1932
+ if (typeof priority !== "number" || !Number.isFinite(priority)) {
1933
+ throw new TypeError(`Expected \`priority\` to be a finite number, got \`${priority}\` (${typeof priority})`);
1934
+ }
1935
+ __privateGet(this, _queue2).setPriority(id, priority);
1936
+ }
1937
+ async add(function_, options = {}) {
1938
+ options = {
1939
+ timeout: this.timeout,
1940
+ ...options,
1941
+ // Assign unique ID if not provided
1942
+ id: options.id ?? (__privateWrapper(this, _idAssigner)._++).toString()
1943
+ };
1944
+ return new Promise((resolve, reject) => {
1945
+ const taskSymbol = /* @__PURE__ */ Symbol(`task-${options.id}`);
1946
+ let cleanupQueueAbortHandler = () => void 0;
1947
+ const run = async () => {
1948
+ cleanupQueueAbortHandler();
1949
+ __privateWrapper(this, _pending)._++;
1950
+ __privateGet(this, _runningTasks).set(taskSymbol, {
1951
+ id: options.id,
1952
+ priority: options.priority ?? 0,
1953
+ // Match priority-queue default
1954
+ startTime: Date.now(),
1955
+ timeout: options.timeout
1956
+ });
1957
+ let eventListener;
1958
+ try {
1959
+ try {
1960
+ options.signal?.throwIfAborted();
1961
+ } catch (error) {
1962
+ __privateMethod(this, _PQueue_instances, rollbackIntervalConsumption_fn).call(this);
1963
+ __privateGet(this, _runningTasks).delete(taskSymbol);
1964
+ throw error;
1965
+ }
1966
+ __privateSet(this, _lastExecutionTime, Date.now());
1967
+ let operation = function_({ signal: options.signal });
1968
+ if (options.timeout) {
1969
+ operation = pTimeout(Promise.resolve(operation), {
1970
+ milliseconds: options.timeout,
1971
+ message: `Task timed out after ${options.timeout}ms (queue has ${__privateGet(this, _pending)} running, ${__privateGet(this, _queue2).size} waiting)`
1972
+ });
1973
+ }
1974
+ if (options.signal) {
1975
+ const { signal } = options;
1976
+ operation = Promise.race([operation, new Promise((_resolve, reject2) => {
1977
+ eventListener = () => {
1978
+ reject2(signal.reason);
1979
+ };
1980
+ signal.addEventListener("abort", eventListener, { once: true });
1981
+ })]);
1982
+ }
1983
+ const result = await operation;
1984
+ resolve(result);
1985
+ this.emit("completed", result);
1986
+ } catch (error) {
1987
+ reject(error);
1988
+ this.emit("error", error);
1989
+ } finally {
1990
+ if (eventListener) {
1991
+ options.signal?.removeEventListener("abort", eventListener);
1992
+ }
1993
+ __privateGet(this, _runningTasks).delete(taskSymbol);
1994
+ queueMicrotask(() => {
1995
+ __privateMethod(this, _PQueue_instances, next_fn).call(this);
1996
+ });
1997
+ }
1998
+ };
1999
+ __privateGet(this, _queue2).enqueue(run, options);
2000
+ const removeQueuedTask = () => {
2001
+ if (__privateGet(this, _queue2) instanceof PriorityQueue) {
2002
+ __privateGet(this, _queue2).remove(run);
2003
+ return;
2004
+ }
2005
+ __privateGet(this, _queue2).remove?.(options.id);
2006
+ };
2007
+ if (options.signal) {
2008
+ const { signal } = options;
2009
+ const queueAbortHandler = () => {
2010
+ cleanupQueueAbortHandler();
2011
+ removeQueuedTask();
2012
+ reject(signal.reason);
2013
+ __privateMethod(this, _PQueue_instances, tryToStartAnother_fn).call(this);
2014
+ this.emit("next");
2015
+ };
2016
+ cleanupQueueAbortHandler = () => {
2017
+ signal.removeEventListener("abort", queueAbortHandler);
2018
+ __privateGet(this, _queueAbortListenerCleanupFunctions).delete(cleanupQueueAbortHandler);
2019
+ };
2020
+ if (signal.aborted) {
2021
+ queueAbortHandler();
2022
+ return;
2023
+ }
2024
+ signal.addEventListener("abort", queueAbortHandler, { once: true });
2025
+ __privateGet(this, _queueAbortListenerCleanupFunctions).add(cleanupQueueAbortHandler);
2026
+ }
2027
+ this.emit("add");
2028
+ __privateMethod(this, _PQueue_instances, tryToStartAnother_fn).call(this);
2029
+ });
2030
+ }
2031
+ async addAll(functions, options) {
2032
+ return Promise.all(functions.map(async (function_) => this.add(function_, options)));
2033
+ }
2034
+ /**
2035
+ Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
2036
+ */
2037
+ start() {
2038
+ if (!__privateGet(this, _isPaused)) {
2039
+ return this;
2040
+ }
2041
+ __privateSet(this, _isPaused, false);
2042
+ __privateMethod(this, _PQueue_instances, processQueue_fn).call(this);
2043
+ return this;
2044
+ }
2045
+ /**
2046
+ Put queue execution on hold.
2047
+ */
2048
+ pause() {
2049
+ __privateSet(this, _isPaused, true);
2050
+ }
2051
+ /**
2052
+ Clear the queue.
2053
+ */
2054
+ clear() {
2055
+ for (const cleanupQueueAbortHandler of __privateGet(this, _queueAbortListenerCleanupFunctions)) {
2056
+ cleanupQueueAbortHandler();
2057
+ }
2058
+ __privateSet(this, _queue2, new (__privateGet(this, _queueClass))());
2059
+ __privateMethod(this, _PQueue_instances, clearIntervalTimer_fn).call(this);
2060
+ __privateMethod(this, _PQueue_instances, updateRateLimitState_fn).call(this);
2061
+ this.emit("empty");
2062
+ if (__privateGet(this, _pending) === 0) {
2063
+ __privateMethod(this, _PQueue_instances, clearTimeoutTimer_fn).call(this);
2064
+ this.emit("idle");
2065
+ }
2066
+ this.emit("next");
2067
+ }
2068
+ /**
2069
+ Can be called multiple times. Useful if you for example add additional items at a later time.
2070
+
2071
+ @returns A promise that settles when the queue becomes empty.
2072
+ */
2073
+ async onEmpty() {
2074
+ if (__privateGet(this, _queue2).size === 0) {
2075
+ return;
2076
+ }
2077
+ await __privateMethod(this, _PQueue_instances, onEvent_fn).call(this, "empty");
2078
+ }
2079
+ /**
2080
+ @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.
2081
+
2082
+ If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.
2083
+
2084
+ Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.
2085
+ */
2086
+ async onSizeLessThan(limit) {
2087
+ if (__privateGet(this, _queue2).size < limit) {
2088
+ return;
2089
+ }
2090
+ await __privateMethod(this, _PQueue_instances, onEvent_fn).call(this, "next", () => __privateGet(this, _queue2).size < limit);
2091
+ }
2092
+ /**
2093
+ The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
2094
+
2095
+ @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
2096
+ */
2097
+ async onIdle() {
2098
+ if (__privateGet(this, _pending) === 0 && __privateGet(this, _queue2).size === 0) {
2099
+ return;
2100
+ }
2101
+ await __privateMethod(this, _PQueue_instances, onEvent_fn).call(this, "idle");
2102
+ }
2103
+ /**
2104
+ The difference with `.onIdle` is that `.onPendingZero` only waits for currently running tasks to finish, ignoring queued tasks.
2105
+
2106
+ @returns A promise that settles when all currently running tasks have completed; `queue.pending === 0`.
2107
+ */
2108
+ async onPendingZero() {
2109
+ if (__privateGet(this, _pending) === 0) {
2110
+ return;
2111
+ }
2112
+ await __privateMethod(this, _PQueue_instances, onEvent_fn).call(this, "pendingZero");
2113
+ }
2114
+ /**
2115
+ @returns A promise that settles when the queue becomes rate-limited due to intervalCap.
2116
+ */
2117
+ async onRateLimit() {
2118
+ if (this.isRateLimited) {
2119
+ return;
2120
+ }
2121
+ await __privateMethod(this, _PQueue_instances, onEvent_fn).call(this, "rateLimit");
2122
+ }
2123
+ /**
2124
+ @returns A promise that settles when the queue is no longer rate-limited.
2125
+ */
2126
+ async onRateLimitCleared() {
2127
+ if (!this.isRateLimited) {
2128
+ return;
2129
+ }
2130
+ await __privateMethod(this, _PQueue_instances, onEvent_fn).call(this, "rateLimitCleared");
2131
+ }
2132
+ /**
2133
+ @returns A promise that rejects when any task in the queue errors.
2134
+
2135
+ Use with `Promise.race([queue.onError(), queue.onIdle()])` to fail fast on the first error while still resolving normally when the queue goes idle.
2136
+
2137
+ Important: The promise returned by `add()` still rejects. You must handle each `add()` promise (for example, `.catch(() => {})`) to avoid unhandled rejections.
2138
+
2139
+ @example
2140
+ ```
2141
+ import PQueue from 'p-queue';
2142
+
2143
+ const queue = new PQueue({concurrency: 2});
2144
+
2145
+ queue.add(() => fetchData(1)).catch(() => {});
2146
+ queue.add(() => fetchData(2)).catch(() => {});
2147
+ queue.add(() => fetchData(3)).catch(() => {});
2148
+
2149
+ // Stop processing on first error
2150
+ try {
2151
+ await Promise.race([
2152
+ queue.onError(),
2153
+ queue.onIdle()
2154
+ ]);
2155
+ } catch (error) {
2156
+ queue.pause(); // Stop processing remaining tasks
2157
+ console.error('Queue failed:', error);
2158
+ }
2159
+ ```
2160
+ */
2161
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
2162
+ onError() {
2163
+ return new Promise((_resolve, reject) => {
2164
+ const handleError = (error) => {
2165
+ this.off("error", handleError);
2166
+ reject(error);
2167
+ };
2168
+ this.on("error", handleError);
2169
+ });
2170
+ }
2171
+ /**
2172
+ Size of the queue, the number of queued items waiting to run.
2173
+ */
2174
+ get size() {
2175
+ return __privateGet(this, _queue2).size;
2176
+ }
2177
+ /**
2178
+ Size of the queue, filtered by the given options.
2179
+
2180
+ For example, this can be used to find the number of items remaining in the queue with a specific priority level.
2181
+ */
2182
+ sizeBy(options) {
2183
+ return __privateGet(this, _queue2).filter(options).length;
2184
+ }
2185
+ /**
2186
+ Number of running items (no longer in the queue).
2187
+ */
2188
+ get pending() {
2189
+ return __privateGet(this, _pending);
2190
+ }
2191
+ /**
2192
+ Whether the queue is currently paused.
2193
+ */
2194
+ get isPaused() {
2195
+ return __privateGet(this, _isPaused);
2196
+ }
2197
+ /**
2198
+ Whether the queue is currently rate-limited due to intervalCap.
2199
+ */
2200
+ get isRateLimited() {
2201
+ return __privateGet(this, _rateLimitedInInterval);
2202
+ }
2203
+ /**
2204
+ Whether the queue is saturated. Returns `true` when:
2205
+ - All concurrency slots are occupied and tasks are waiting, OR
2206
+ - The queue is rate-limited and tasks are waiting
2207
+
2208
+ Useful for detecting backpressure and potential hanging tasks.
2209
+
2210
+ ```js
2211
+ import PQueue from 'p-queue';
2212
+
2213
+ const queue = new PQueue({concurrency: 2});
2214
+
2215
+ // Backpressure handling
2216
+ if (queue.isSaturated) {
2217
+ console.log('Queue is saturated, waiting for capacity...');
2218
+ await queue.onSizeLessThan(queue.concurrency);
2219
+ }
2220
+
2221
+ // Monitoring for stuck tasks
2222
+ setInterval(() => {
2223
+ if (queue.isSaturated) {
2224
+ console.warn(`Queue saturated: ${queue.pending} running, ${queue.size} waiting`);
2225
+ }
2226
+ }, 60000);
2227
+ ```
2228
+ */
2229
+ get isSaturated() {
2230
+ return __privateGet(this, _pending) === __privateGet(this, _concurrency) && __privateGet(this, _queue2).size > 0 || this.isRateLimited && __privateGet(this, _queue2).size > 0;
2231
+ }
2232
+ /**
2233
+ The tasks currently being executed. Each task includes its `id`, `priority`, `startTime`, and `timeout` (if set).
2234
+
2235
+ Returns an array of task info objects.
2236
+
2237
+ ```js
2238
+ import PQueue from 'p-queue';
2239
+
2240
+ const queue = new PQueue({concurrency: 2});
2241
+
2242
+ // Add tasks with IDs for better debugging
2243
+ queue.add(() => fetchUser(123), {id: 'user-123'});
2244
+ queue.add(() => fetchPosts(456), {id: 'posts-456', priority: 1});
2245
+
2246
+ // Check what's running
2247
+ console.log(queue.runningTasks);
2248
+ // => [{
2249
+ // id: 'user-123',
2250
+ // priority: 0,
2251
+ // startTime: 1759253001716,
2252
+ // timeout: undefined
2253
+ // }, {
2254
+ // id: 'posts-456',
2255
+ // priority: 1,
2256
+ // startTime: 1759253001916,
2257
+ // timeout: undefined
2258
+ // }]
2259
+ ```
2260
+ */
2261
+ get runningTasks() {
2262
+ return [...__privateGet(this, _runningTasks).values()].map((task) => ({ ...task }));
2263
+ }
2264
+ };
2265
+ _carryoverIntervalCount = new WeakMap();
2266
+ _isIntervalIgnored = new WeakMap();
2267
+ _intervalCount = new WeakMap();
2268
+ _intervalCap = new WeakMap();
2269
+ _rateLimitedInInterval = new WeakMap();
2270
+ _rateLimitFlushScheduled = new WeakMap();
2271
+ _interval = new WeakMap();
2272
+ _intervalEnd = new WeakMap();
2273
+ _lastExecutionTime = new WeakMap();
2274
+ _intervalId = new WeakMap();
2275
+ _timeoutId = new WeakMap();
2276
+ _strict = new WeakMap();
2277
+ _strictTicks = new WeakMap();
2278
+ _strictTicksStartIndex = new WeakMap();
2279
+ _queue2 = new WeakMap();
2280
+ _queueClass = new WeakMap();
2281
+ _pending = new WeakMap();
2282
+ _concurrency = new WeakMap();
2283
+ _isPaused = new WeakMap();
2284
+ _idAssigner = new WeakMap();
2285
+ _runningTasks = new WeakMap();
2286
+ _queueAbortListenerCleanupFunctions = new WeakMap();
2287
+ _PQueue_instances = new WeakSet();
2288
+ cleanupStrictTicks_fn = function(now) {
2289
+ while (__privateGet(this, _strictTicksStartIndex) < __privateGet(this, _strictTicks).length) {
2290
+ const oldestTick = __privateGet(this, _strictTicks)[__privateGet(this, _strictTicksStartIndex)];
2291
+ if (oldestTick !== void 0 && now - oldestTick >= __privateGet(this, _interval)) {
2292
+ __privateWrapper(this, _strictTicksStartIndex)._++;
2293
+ } else {
2294
+ break;
2295
+ }
2296
+ }
2297
+ const shouldCompact = __privateGet(this, _strictTicksStartIndex) > 100 && __privateGet(this, _strictTicksStartIndex) > __privateGet(this, _strictTicks).length / 2 || __privateGet(this, _strictTicksStartIndex) === __privateGet(this, _strictTicks).length;
2298
+ if (shouldCompact) {
2299
+ __privateSet(this, _strictTicks, __privateGet(this, _strictTicks).slice(__privateGet(this, _strictTicksStartIndex)));
2300
+ __privateSet(this, _strictTicksStartIndex, 0);
2301
+ }
2302
+ };
2303
+ // Helper methods for interval consumption
2304
+ consumeIntervalSlot_fn = function(now) {
2305
+ if (__privateGet(this, _strict)) {
2306
+ __privateGet(this, _strictTicks).push(now);
2307
+ } else {
2308
+ __privateWrapper(this, _intervalCount)._++;
2309
+ }
2310
+ };
2311
+ rollbackIntervalSlot_fn = function() {
2312
+ if (__privateGet(this, _strict)) {
2313
+ if (__privateGet(this, _strictTicks).length > __privateGet(this, _strictTicksStartIndex)) {
2314
+ __privateGet(this, _strictTicks).pop();
2315
+ }
2316
+ } else if (__privateGet(this, _intervalCount) > 0) {
2317
+ __privateWrapper(this, _intervalCount)._--;
2318
+ }
2319
+ };
2320
+ getActiveTicksCount_fn = function() {
2321
+ return __privateGet(this, _strictTicks).length - __privateGet(this, _strictTicksStartIndex);
2322
+ };
2323
+ doesIntervalAllowAnother_get = function() {
2324
+ if (__privateGet(this, _isIntervalIgnored)) {
2325
+ return true;
2326
+ }
2327
+ if (__privateGet(this, _strict)) {
2328
+ return __privateMethod(this, _PQueue_instances, getActiveTicksCount_fn).call(this) < __privateGet(this, _intervalCap);
2329
+ }
2330
+ return __privateGet(this, _intervalCount) < __privateGet(this, _intervalCap);
2331
+ };
2332
+ doesConcurrentAllowAnother_get = function() {
2333
+ return __privateGet(this, _pending) < __privateGet(this, _concurrency);
2334
+ };
2335
+ next_fn = function() {
2336
+ __privateWrapper(this, _pending)._--;
2337
+ if (__privateGet(this, _pending) === 0) {
2338
+ this.emit("pendingZero");
2339
+ }
2340
+ __privateMethod(this, _PQueue_instances, tryToStartAnother_fn).call(this);
2341
+ this.emit("next");
2342
+ };
2343
+ onResumeInterval_fn = function() {
2344
+ __privateSet(this, _timeoutId, void 0);
2345
+ __privateMethod(this, _PQueue_instances, onInterval_fn).call(this);
2346
+ __privateMethod(this, _PQueue_instances, initializeIntervalIfNeeded_fn).call(this);
2347
+ };
2348
+ isIntervalPausedAt_fn = function(now) {
2349
+ if (__privateGet(this, _strict)) {
2350
+ __privateMethod(this, _PQueue_instances, cleanupStrictTicks_fn).call(this, now);
2351
+ const activeTicksCount = __privateMethod(this, _PQueue_instances, getActiveTicksCount_fn).call(this);
2352
+ if (activeTicksCount >= __privateGet(this, _intervalCap)) {
2353
+ const oldestTick = __privateGet(this, _strictTicks)[__privateGet(this, _strictTicksStartIndex)];
2354
+ const delay = __privateGet(this, _interval) - (now - oldestTick);
2355
+ __privateMethod(this, _PQueue_instances, createIntervalTimeout_fn).call(this, delay);
2356
+ return true;
2357
+ }
2358
+ return false;
2359
+ }
2360
+ if (__privateGet(this, _intervalId) === void 0) {
2361
+ const delay = __privateGet(this, _intervalEnd) - now;
2362
+ if (delay < 0) {
2363
+ if (__privateGet(this, _lastExecutionTime) > 0) {
2364
+ const timeSinceLastExecution = now - __privateGet(this, _lastExecutionTime);
2365
+ if (timeSinceLastExecution < __privateGet(this, _interval)) {
2366
+ __privateMethod(this, _PQueue_instances, createIntervalTimeout_fn).call(this, __privateGet(this, _interval) - timeSinceLastExecution);
2367
+ return true;
2368
+ }
2369
+ }
2370
+ __privateSet(this, _intervalCount, __privateGet(this, _carryoverIntervalCount) ? __privateGet(this, _pending) : 0);
2371
+ } else {
2372
+ __privateMethod(this, _PQueue_instances, createIntervalTimeout_fn).call(this, delay);
2373
+ return true;
2374
+ }
2375
+ }
2376
+ return false;
2377
+ };
2378
+ createIntervalTimeout_fn = function(delay) {
2379
+ if (__privateGet(this, _timeoutId) !== void 0) {
2380
+ return;
2381
+ }
2382
+ __privateSet(this, _timeoutId, setTimeout(() => {
2383
+ __privateMethod(this, _PQueue_instances, onResumeInterval_fn).call(this);
2384
+ }, delay));
2385
+ };
2386
+ clearIntervalTimer_fn = function() {
2387
+ if (__privateGet(this, _intervalId)) {
2388
+ clearInterval(__privateGet(this, _intervalId));
2389
+ __privateSet(this, _intervalId, void 0);
2390
+ }
2391
+ };
2392
+ clearTimeoutTimer_fn = function() {
2393
+ if (__privateGet(this, _timeoutId)) {
2394
+ clearTimeout(__privateGet(this, _timeoutId));
2395
+ __privateSet(this, _timeoutId, void 0);
2396
+ }
2397
+ };
2398
+ tryToStartAnother_fn = function() {
2399
+ if (__privateGet(this, _queue2).size === 0) {
2400
+ __privateMethod(this, _PQueue_instances, clearIntervalTimer_fn).call(this);
2401
+ this.emit("empty");
2402
+ if (__privateGet(this, _pending) === 0) {
2403
+ __privateMethod(this, _PQueue_instances, clearTimeoutTimer_fn).call(this);
2404
+ if (__privateGet(this, _strict) && __privateGet(this, _strictTicksStartIndex) > 0) {
2405
+ const now = Date.now();
2406
+ __privateMethod(this, _PQueue_instances, cleanupStrictTicks_fn).call(this, now);
2407
+ }
2408
+ this.emit("idle");
2409
+ }
2410
+ return false;
2411
+ }
2412
+ let taskStarted = false;
2413
+ if (!__privateGet(this, _isPaused)) {
2414
+ const now = Date.now();
2415
+ const canInitializeInterval = !__privateMethod(this, _PQueue_instances, isIntervalPausedAt_fn).call(this, now);
2416
+ if (__privateGet(this, _PQueue_instances, doesIntervalAllowAnother_get) && __privateGet(this, _PQueue_instances, doesConcurrentAllowAnother_get)) {
2417
+ const job = __privateGet(this, _queue2).dequeue();
2418
+ if (!__privateGet(this, _isIntervalIgnored)) {
2419
+ __privateMethod(this, _PQueue_instances, consumeIntervalSlot_fn).call(this, now);
2420
+ __privateMethod(this, _PQueue_instances, scheduleRateLimitUpdate_fn).call(this);
2421
+ }
2422
+ this.emit("active");
2423
+ job();
2424
+ if (canInitializeInterval) {
2425
+ __privateMethod(this, _PQueue_instances, initializeIntervalIfNeeded_fn).call(this);
2426
+ }
2427
+ taskStarted = true;
2428
+ }
2429
+ }
2430
+ return taskStarted;
2431
+ };
2432
+ initializeIntervalIfNeeded_fn = function() {
2433
+ if (__privateGet(this, _isIntervalIgnored) || __privateGet(this, _intervalId) !== void 0) {
2434
+ return;
2435
+ }
2436
+ if (__privateGet(this, _strict)) {
2437
+ return;
2438
+ }
2439
+ __privateSet(this, _intervalId, setInterval(() => {
2440
+ __privateMethod(this, _PQueue_instances, onInterval_fn).call(this);
2441
+ }, __privateGet(this, _interval)));
2442
+ __privateSet(this, _intervalEnd, Date.now() + __privateGet(this, _interval));
2443
+ };
2444
+ onInterval_fn = function() {
2445
+ if (!__privateGet(this, _strict)) {
2446
+ if (__privateGet(this, _intervalCount) === 0 && __privateGet(this, _pending) === 0 && __privateGet(this, _intervalId)) {
2447
+ __privateMethod(this, _PQueue_instances, clearIntervalTimer_fn).call(this);
2448
+ }
2449
+ __privateSet(this, _intervalCount, __privateGet(this, _carryoverIntervalCount) ? __privateGet(this, _pending) : 0);
2450
+ }
2451
+ __privateMethod(this, _PQueue_instances, processQueue_fn).call(this);
2452
+ __privateMethod(this, _PQueue_instances, scheduleRateLimitUpdate_fn).call(this);
2453
+ };
2454
+ /**
2455
+ Executes all queued functions until it reaches the limit.
2456
+ */
2457
+ processQueue_fn = function() {
2458
+ while (__privateMethod(this, _PQueue_instances, tryToStartAnother_fn).call(this)) {
2459
+ }
2460
+ };
2461
+ onEvent_fn = async function(event, filter) {
2462
+ return new Promise((resolve) => {
2463
+ const listener = () => {
2464
+ if (filter && !filter()) {
2465
+ return;
2466
+ }
2467
+ this.off(event, listener);
2468
+ resolve();
2469
+ };
2470
+ this.on(event, listener);
2471
+ });
2472
+ };
2473
+ setupRateLimitTracking_fn = function() {
2474
+ if (__privateGet(this, _isIntervalIgnored)) {
2475
+ return;
2476
+ }
2477
+ this.on("add", () => {
2478
+ if (__privateGet(this, _queue2).size > 0) {
2479
+ __privateMethod(this, _PQueue_instances, scheduleRateLimitUpdate_fn).call(this);
2480
+ }
2481
+ });
2482
+ this.on("next", () => {
2483
+ __privateMethod(this, _PQueue_instances, scheduleRateLimitUpdate_fn).call(this);
2484
+ });
2485
+ };
2486
+ scheduleRateLimitUpdate_fn = function() {
2487
+ if (__privateGet(this, _isIntervalIgnored) || __privateGet(this, _rateLimitFlushScheduled)) {
2488
+ return;
2489
+ }
2490
+ __privateSet(this, _rateLimitFlushScheduled, true);
2491
+ queueMicrotask(() => {
2492
+ __privateSet(this, _rateLimitFlushScheduled, false);
2493
+ __privateMethod(this, _PQueue_instances, updateRateLimitState_fn).call(this);
2494
+ });
2495
+ };
2496
+ rollbackIntervalConsumption_fn = function() {
2497
+ if (__privateGet(this, _isIntervalIgnored)) {
2498
+ return;
2499
+ }
2500
+ __privateMethod(this, _PQueue_instances, rollbackIntervalSlot_fn).call(this);
2501
+ __privateMethod(this, _PQueue_instances, scheduleRateLimitUpdate_fn).call(this);
2502
+ };
2503
+ updateRateLimitState_fn = function() {
2504
+ const previous = __privateGet(this, _rateLimitedInInterval);
2505
+ if (__privateGet(this, _isIntervalIgnored) || __privateGet(this, _queue2).size === 0) {
2506
+ if (previous) {
2507
+ __privateSet(this, _rateLimitedInInterval, false);
2508
+ this.emit("rateLimitCleared");
2509
+ }
2510
+ return;
2511
+ }
2512
+ let count;
2513
+ if (__privateGet(this, _strict)) {
2514
+ const now = Date.now();
2515
+ __privateMethod(this, _PQueue_instances, cleanupStrictTicks_fn).call(this, now);
2516
+ count = __privateMethod(this, _PQueue_instances, getActiveTicksCount_fn).call(this);
2517
+ } else {
2518
+ count = __privateGet(this, _intervalCount);
2519
+ }
2520
+ const shouldBeRateLimited = count >= __privateGet(this, _intervalCap);
2521
+ if (shouldBeRateLimited !== previous) {
2522
+ __privateSet(this, _rateLimitedInInterval, shouldBeRateLimited);
2523
+ this.emit(shouldBeRateLimited ? "rateLimit" : "rateLimitCleared");
2524
+ }
2525
+ };
2526
+
2527
+ // src/core/persistence-manager.ts
2528
+ var _PersistenceManager = class _PersistenceManager {
2529
+ async saveQueueStates(states) {
2530
+ try {
2531
+ if (chrome.storage) {
2532
+ await chrome.storage.local.set({ [_PersistenceManager.STORAGE_KEY]: states });
2533
+ }
2534
+ } catch (e) {
2535
+ console.error("Failed to persist queue states:", e);
2536
+ }
2537
+ }
2538
+ async loadQueueStates() {
2539
+ try {
2540
+ if (chrome.storage) {
2541
+ const data = await chrome.storage.local.get(_PersistenceManager.STORAGE_KEY);
2542
+ const stored = data[_PersistenceManager.STORAGE_KEY];
2543
+ if (stored && typeof stored === "object") {
2544
+ return stored;
2545
+ }
2546
+ }
2547
+ } catch (e) {
2548
+ console.error("Failed to load queue states:", e);
2549
+ }
2550
+ return {};
2551
+ }
2552
+ };
2553
+ __publicField(_PersistenceManager, "STORAGE_KEY", "queue_manager_state");
2554
+ var PersistenceManager = _PersistenceManager;
2555
+ var persistenceManager = new PersistenceManager();
2556
+
2557
+ // src/core/engine-hub.ts
2558
+ var EngineHub = class {
2559
+ constructor() {
2560
+ __publicField(this, "engines", /* @__PURE__ */ new Map());
2561
+ }
2562
+ register(platformId, engine) {
2563
+ this.engines.set(platformId, engine);
2564
+ }
2565
+ get(platformId) {
2566
+ return this.engines.get(platformId);
2567
+ }
2568
+ getAll() {
2569
+ return this.engines;
2570
+ }
2571
+ };
2572
+ var engineHub = new EngineHub();
2573
+
2574
+ // src/core/helper.ts
2575
+ async function sleep(ms, signal) {
2576
+ if (signal?.aborted) {
2577
+ signal.throwIfAborted();
2578
+ }
2579
+ await new Promise((resolve, reject) => {
2580
+ const abortHandler = () => {
2581
+ reject(new DOMException("Sleep aborted", "AbortError"));
2582
+ };
2583
+ if (signal) {
2584
+ signal.addEventListener("abort", abortHandler, { once: true });
2585
+ }
2586
+ const timeoutId = setTimeout(() => {
2587
+ if (signal) {
2588
+ signal.removeEventListener("abort", abortHandler);
2589
+ }
2590
+ resolve(void 0);
2591
+ }, ms);
2592
+ if (signal) {
2593
+ signal.addEventListener(
2594
+ "abort",
2595
+ () => {
2596
+ clearTimeout(timeoutId);
2597
+ reject(new DOMException("Sleep aborted", "AbortError"));
2598
+ },
2599
+ { once: true }
2600
+ );
2601
+ }
2602
+ });
2603
+ }
2604
+
2605
+ // src/core/task-context.ts
2606
+ var TaskContext = class {
2607
+ constructor(task, signal) {
2608
+ __publicField(this, "task");
2609
+ __publicField(this, "signal");
2610
+ this.task = task;
2611
+ this.signal = signal;
2612
+ }
2613
+ /**
2614
+ * Helper to execute an async operation while respecting the cancellation signal.
2615
+ * Checks for abortion BEFORE and AFTER the operation.
2616
+ */
2617
+ async run(fn) {
2618
+ this.signal?.throwIfAborted();
2619
+ const result = await fn();
2620
+ this.signal?.throwIfAborted();
2621
+ return result;
2622
+ }
2623
+ /**
2624
+ * Signal-aware sleep utility.
2625
+ */
2626
+ async sleep(ms) {
2627
+ return sleep(ms, this.signal);
2628
+ }
2629
+ /**
2630
+ * Check if the task has been cancelled.
2631
+ */
2632
+ get aborted() {
2633
+ return this.signal?.aborted || false;
2634
+ }
2635
+ /**
2636
+ * Throw if the task has been cancelled.
2637
+ */
2638
+ throwIfAborted() {
2639
+ this.signal?.throwIfAborted();
2640
+ }
2641
+ };
2642
+
2643
+ // src/core/queue-manager.ts
2644
+ var QueueManager = class {
2645
+ constructor(options) {
2646
+ __publicField(this, "queues", /* @__PURE__ */ new Map());
2647
+ __publicField(this, "defaultOptions");
2648
+ __publicField(this, "platformOptions", /* @__PURE__ */ new Map());
2649
+ __publicField(this, "runningQueues", /* @__PURE__ */ new Set());
2650
+ __publicField(this, "concurrencyMap", /* @__PURE__ */ new Map());
2651
+ __publicField(this, "abortControllers", /* @__PURE__ */ new Map());
2652
+ this.defaultOptions = options;
2653
+ }
2654
+ logQueueState(keycard, identifier, action) {
2655
+ const key = this.getQueueKey(keycard, identifier);
2656
+ const entry = this.queues.get(key);
2657
+ if (!entry) {
2658
+ console.log(`[Queue] ${action} - Queue not found for key: ${key}`);
2659
+ return;
2660
+ }
2661
+ const taskSummary = entry.tasks.map((t) => `[${t.id}] ${t.status}${t.name ? ` (${t.name})` : ""}`).join(", ");
2662
+ console.log(
2663
+ `[Queue] ${action} | Key: ${key} | Tasks: ${entry.tasks.length} | Queue size: ${entry.queue.size} | Pending: ${entry.queue.pending} | isPaused: ${entry.queue.isPaused} | Tasks: ${taskSummary}`
2664
+ );
2665
+ }
2666
+ getQueueKey(keycard, identifier) {
2667
+ if (identifier) return `${keycard}__${identifier}`;
2668
+ return keycard;
2669
+ }
2670
+ registerOptions(keycard, options) {
2671
+ if (!this.platformOptions.has(keycard)) {
2672
+ this.platformOptions.set(keycard, []);
2673
+ }
2674
+ this.platformOptions.get(keycard).push(options);
2675
+ return () => this.unregisterOptions(keycard, options);
2676
+ }
2677
+ unregisterOptions(keycard, options) {
2678
+ const list = this.platformOptions.get(keycard);
2679
+ if (list) {
2680
+ const index = list.indexOf(options);
2681
+ if (index !== -1) {
2682
+ list.splice(index, 1);
2683
+ }
2684
+ if (list.length === 0) {
2685
+ this.platformOptions.delete(keycard);
2686
+ }
2687
+ }
2688
+ }
2689
+ getOptions(keycard) {
2690
+ const platformSpecific = this.platformOptions.get(keycard) || [];
2691
+ const global = this.platformOptions.get("*") || [];
2692
+ return [...platformSpecific, ...global];
2693
+ }
2694
+ getOrCreateQueue(keycard, identifier) {
2695
+ const key = this.getQueueKey(keycard, identifier);
2696
+ if (!this.queues.has(key)) {
2697
+ const concurrency = this.options.defaultConcurrency;
2698
+ const queue = new PQueue({
2699
+ concurrency,
2700
+ autoStart: false
2701
+ });
2702
+ const entry2 = {
2703
+ queue,
2704
+ tasks: [],
2705
+ queuedIds: /* @__PURE__ */ new Set(),
2706
+ consecutiveErrors: 0
2707
+ };
2708
+ queue.on("idle", () => {
2709
+ if (this.runningQueues.has(key)) {
2710
+ this.autoStopQueue(keycard, identifier);
2711
+ }
2712
+ });
2713
+ this.queues.set(key, entry2);
2714
+ }
2715
+ const entry = this.queues.get(key);
2716
+ const currentConcurrency = this.concurrencyMap.get(keycard) ?? this.options.defaultConcurrency ?? 1;
2717
+ if (entry.queue.concurrency !== currentConcurrency) {
2718
+ entry.queue.concurrency = currentConcurrency;
2719
+ }
2720
+ return entry;
2721
+ }
2722
+ // Getter for legacy/global options to avoid breaking things during refactor
2723
+ get options() {
2724
+ return this.defaultOptions;
2725
+ }
2726
+ setConcurrency(keycard, concurrency) {
2727
+ this.concurrencyMap.set(keycard, concurrency);
2728
+ for (const [key, entry] of this.queues.entries()) {
2729
+ if (key.startsWith(keycard)) {
2730
+ entry.queue.concurrency = concurrency;
2731
+ }
2732
+ }
2733
+ }
2734
+ registerEngine(keycard, engine) {
2735
+ engineHub.register(keycard, engine);
2736
+ }
2737
+ async add(keycard, identifier, task) {
2738
+ const entry = this.getOrCreateQueue(keycard, identifier);
2739
+ const { queue, tasks, queuedIds } = entry;
2740
+ const exists = tasks.find((t) => t.id === task.id);
2741
+ const updatedTask = { ...task };
2742
+ if (!exists) {
2743
+ tasks.push(updatedTask);
2744
+ } else {
2745
+ const idx = tasks.indexOf(exists);
2746
+ tasks[idx] = updatedTask;
2747
+ }
2748
+ if (updatedTask.status === "Waiting" && !queuedIds.has(updatedTask.id)) {
2749
+ updatedTask.isQueued = true;
2750
+ queuedIds.add(updatedTask.id);
2751
+ queue.add(() => this.processTask(keycard, identifier, updatedTask));
2752
+ }
2753
+ this.updateTasks(keycard, identifier, tasks);
2754
+ this.notifyStatusChange(keycard, identifier);
2755
+ this.logQueueState(keycard, identifier, "ADD");
2756
+ }
2757
+ async addMany(keycard, identifier, newTasks) {
2758
+ const entry = this.getOrCreateQueue(keycard, identifier);
2759
+ const { queue, tasks, queuedIds } = entry;
2760
+ for (const task of newTasks) {
2761
+ const exists = tasks.find((t) => t.id === task.id);
2762
+ const updatedTask = { ...task };
2763
+ if (!exists) {
2764
+ tasks.push(updatedTask);
2765
+ } else {
2766
+ const idx = tasks.indexOf(exists);
2767
+ tasks[idx] = updatedTask;
2768
+ }
2769
+ if (updatedTask.status === "Waiting" && !queuedIds.has(updatedTask.id)) {
2770
+ updatedTask.isQueued = true;
2771
+ queuedIds.add(updatedTask.id);
2772
+ queue.add(() => this.processTask(keycard, identifier, updatedTask));
2773
+ }
2774
+ }
2775
+ this.updateTasks(keycard, identifier, tasks);
2776
+ this.notifyStatusChange(keycard, identifier);
2777
+ this.logQueueState(keycard, identifier, "ADD_MANY");
2778
+ }
2779
+ async start(keycard, identifier) {
2780
+ const key = this.getQueueKey(keycard, identifier);
2781
+ const entry = this.queues.get(key);
2782
+ if (entry) {
2783
+ const { queue, tasks, queuedIds } = entry;
2784
+ let addedAny = false;
2785
+ for (const task of tasks) {
2786
+ if (task.status === "Waiting" && !queuedIds.has(task.id)) {
2787
+ task.isQueued = true;
2788
+ queuedIds.add(task.id);
2789
+ queue.add(() => this.processTask(keycard, identifier, task));
2790
+ addedAny = true;
2791
+ }
2792
+ }
2793
+ this.runningQueues.add(key);
2794
+ queue.start();
2795
+ if (addedAny) {
2796
+ this.updateTasks(keycard, identifier, tasks);
2797
+ }
2798
+ this.notifyStatusChange(keycard, identifier);
2799
+ this.logQueueState(keycard, identifier, "START");
2800
+ await this.persistState();
2801
+ }
2802
+ }
2803
+ async stop(keycard, identifier) {
2804
+ const key = this.getQueueKey(keycard, identifier);
2805
+ const entry = this.queues.get(key);
2806
+ if (entry) {
2807
+ entry.queue.pause();
2808
+ entry.queue.clear();
2809
+ entry.queuedIds.clear();
2810
+ entry.tasks.forEach((t) => {
2811
+ if (t.status === "Waiting") t.isQueued = false;
2812
+ });
2813
+ this.runningQueues.delete(key);
2814
+ const runningTasks = entry.tasks.filter((t) => t.status === "Running");
2815
+ for (const t of runningTasks) {
2816
+ await this.haltTask(keycard, identifier, t.id);
2817
+ }
2818
+ await this.persistState();
2819
+ this.notifyStatusChange(keycard, identifier);
2820
+ this.logQueueState(keycard, identifier, "STOP");
2821
+ }
2822
+ }
2823
+ async pause(keycard, identifier) {
2824
+ const key = this.getQueueKey(keycard, identifier);
2825
+ const entry = this.queues.get(key);
2826
+ if (entry) {
2827
+ entry.queue.pause();
2828
+ await this.persistState();
2829
+ this.logQueueState(keycard, identifier, "PAUSE");
2830
+ }
2831
+ }
2832
+ async resume(keycard, identifier) {
2833
+ const key = this.getQueueKey(keycard, identifier);
2834
+ const entry = this.queues.get(key);
2835
+ if (entry) {
2836
+ entry.queue.start();
2837
+ await this.persistState();
2838
+ this.logQueueState(keycard, identifier, "RESUME");
2839
+ }
2840
+ }
2841
+ async clear(keycard, identifier) {
2842
+ const key = this.getQueueKey(keycard, identifier);
2843
+ const entry = this.queues.get(key);
2844
+ if (entry) {
2845
+ entry.queue.clear();
2846
+ entry.tasks = [];
2847
+ entry.queuedIds.clear();
2848
+ this.updateTasks(keycard, identifier, []);
2849
+ }
2850
+ this.notifyStatusChange(keycard, identifier);
2851
+ }
2852
+ /**
2853
+ * Immediately halts the engine execution for a task and resets its status to Waiting.
2854
+ * Does NOT remove the task from the list.
2855
+ */
2856
+ async haltTask(keycard, identifier, taskId) {
2857
+ const controller = this.abortControllers.get(taskId);
2858
+ if (controller) {
2859
+ controller.abort();
2860
+ this.abortControllers.delete(taskId);
2861
+ }
2862
+ const key = this.getQueueKey(keycard, identifier);
2863
+ const entry = this.queues.get(key);
2864
+ if (entry) {
2865
+ const idx = entry.tasks.findIndex((t) => t.id === taskId);
2866
+ const currentTask = entry.tasks[idx];
2867
+ if (idx !== -1 && currentTask && currentTask.status === "Running") {
2868
+ entry.tasks[idx] = {
2869
+ ...currentTask,
2870
+ status: "Waiting",
2871
+ isQueued: false
2872
+ };
2873
+ entry.queuedIds.delete(taskId);
2874
+ this.updateTasks(keycard, identifier, entry.tasks);
2875
+ }
2876
+ }
2877
+ this.notifyStatusChange(keycard, identifier);
2878
+ }
2879
+ /**
2880
+ * Stops execution AND removes the task from the project entirely.
2881
+ */
2882
+ async cancelTask(keycard, identifier, taskId) {
2883
+ const controller = this.abortControllers.get(taskId);
2884
+ if (controller) {
2885
+ controller.abort();
2886
+ this.abortControllers.delete(taskId);
2887
+ }
2888
+ const key = this.getQueueKey(keycard, identifier);
2889
+ const entry = this.queues.get(key);
2890
+ if (entry) {
2891
+ entry.tasks = entry.tasks.filter((t) => t.id !== taskId);
2892
+ entry.queuedIds.delete(taskId);
2893
+ this.updateTasks(keycard, identifier, entry.tasks);
2894
+ }
2895
+ this.notifyStatusChange(keycard, identifier);
2896
+ }
2897
+ getStatus(keycard, identifier) {
2898
+ const key = this.getQueueKey(keycard, identifier);
2899
+ const entry = this.queues.get(key);
2900
+ const activeTasks = entry?.tasks || [];
2901
+ const size = activeTasks.filter((t) => t.status === "Waiting" && t.isQueued).length;
2902
+ const pending = activeTasks.filter((t) => t.status === "Running").length;
2903
+ return {
2904
+ size,
2905
+ pending,
2906
+ isPaused: entry?.queue.isPaused || false,
2907
+ isRunning: this.runningQueues.has(key)
2908
+ };
2909
+ }
2910
+ getTasks(keycard, identifier) {
2911
+ const key = this.getQueueKey(keycard, identifier);
2912
+ const entry = this.queues.get(key);
2913
+ return entry?.tasks || [];
2914
+ }
2915
+ updateTasks(keycard, identifier, tasks) {
2916
+ this.notifyTasksUpdate(keycard, identifier, tasks);
2917
+ }
2918
+ async processTask(keycard, identifier, task) {
2919
+ const engine = engineHub.get(keycard);
2920
+ const key = this.getQueueKey(keycard, identifier);
2921
+ const entry = this.queues.get(key);
2922
+ if (!engine) {
2923
+ console.warn(`No engine registered for platform: ${keycard}, skipping task: ${task.id}`);
2924
+ if (entry) {
2925
+ const taskIndex2 = entry.tasks.findIndex((t) => t.id === task.id);
2926
+ const taskEntry = entry.tasks[taskIndex2];
2927
+ if (taskIndex2 !== -1 && taskEntry) {
2928
+ entry.tasks[taskIndex2] = {
2929
+ ...taskEntry,
2930
+ status: "Error",
2931
+ errorMessage: "Platform not supported"
2932
+ };
2933
+ this.updateTasks(keycard, identifier, entry.tasks);
2934
+ }
2935
+ }
2936
+ this.notifyStatusChange(keycard, identifier);
2937
+ this.notifyTasksUpdate(keycard, identifier, entry?.tasks || []);
2938
+ return;
2939
+ }
2940
+ if (!entry) {
2941
+ console.error(`Queue entry not found for key: ${key}`);
2942
+ return;
2943
+ }
2944
+ if (task.isFlagged) {
2945
+ console.log(`[QueueManager] Task ${task.id} is flagged. Skipping.`);
2946
+ const taskIndex2 = entry.tasks.findIndex((t) => t.id === task.id);
2947
+ const taskEntry = entry.tasks[taskIndex2];
2948
+ if (taskIndex2 !== -1 && taskEntry) {
2949
+ entry.tasks[taskIndex2] = {
2950
+ ...taskEntry,
2951
+ status: "Skipped",
2952
+ isQueued: false
2953
+ };
2954
+ this.updateTasks(keycard, identifier, entry.tasks);
2955
+ }
2956
+ this.notifyStatusChange(keycard, identifier);
2957
+ return;
2958
+ }
2959
+ const taskIndex = entry.tasks.findIndex((t) => t.id === task.id);
2960
+ if (taskIndex === -1) {
2961
+ console.log(`[QueueManager] Task ${task.id} was removed. Skipping execution.`);
2962
+ return;
2963
+ }
2964
+ const currentTask = entry.tasks[taskIndex];
2965
+ entry.tasks[taskIndex] = {
2966
+ ...currentTask,
2967
+ status: "Running",
2968
+ isQueued: true
2969
+ };
2970
+ this.updateTasks(keycard, identifier, entry.tasks);
2971
+ await this.persistState();
2972
+ const { delayMin, delayMax } = entry.taskConfig || {
2973
+ delayMin: 0,
2974
+ delayMax: 0
2975
+ };
2976
+ if (delayMax > 0) {
2977
+ const delayMs = Math.floor(Math.random() * (delayMax - delayMin + 1) + delayMin) * 1e3;
2978
+ console.log(`[QueueManager] Delaying task ${task.id} for ${delayMs}ms...`);
2979
+ await sleep(delayMs, this.abortControllers.get(key)?.signal);
2980
+ }
2981
+ this.logQueueState(keycard, identifier, `PROCESS_START ${task.id}`);
2982
+ const opts = this.getOptions(keycard);
2983
+ opts.forEach((opt) => opt.onTaskStart?.(keycard, identifier, task.id));
2984
+ this.notifyTasksUpdate(keycard, identifier, entry.tasks);
2985
+ const controller = new AbortController();
2986
+ this.abortControllers.set(task.id, controller);
2987
+ const ctx = new TaskContext(task, controller.signal);
2988
+ try {
2989
+ const result = await Promise.race([
2990
+ engine.execute(ctx),
2991
+ new Promise((_, reject) => {
2992
+ if (ctx.signal?.aborted) {
2993
+ reject(new Error("CANCELLED"));
2994
+ }
2995
+ ctx.signal?.addEventListener(
2996
+ "abort",
2997
+ () => {
2998
+ reject(new Error("CANCELLED"));
2999
+ },
3000
+ { once: true }
3001
+ );
3002
+ })
3003
+ ]);
3004
+ const idx = entry.tasks.findIndex((t) => t.id === task.id);
3005
+ if (idx !== -1) {
3006
+ const finTask = entry.tasks[idx];
3007
+ if (!finTask) return;
3008
+ if (finTask.status !== "Running") {
3009
+ console.log(
3010
+ `Task ${task.id} finished but its status was already changed to ${finTask.status}. Bailing out.`
3011
+ );
3012
+ return;
3013
+ }
3014
+ if (result.error === "CANCELLED") {
3015
+ entry.tasks[idx] = {
3016
+ ...finTask,
3017
+ status: "Waiting",
3018
+ isQueued: false
3019
+ };
3020
+ } else {
3021
+ entry.tasks[idx] = {
3022
+ ...finTask,
3023
+ status: result.success ? "Completed" : "Error",
3024
+ output: result.output,
3025
+ errorMessage: result.error,
3026
+ progress: result.success ? 100 : 0,
3027
+ isQueued: false
3028
+ };
3029
+ if (result.success) {
3030
+ entry.consecutiveErrors = 0;
3031
+ } else {
3032
+ entry.consecutiveErrors = (entry.consecutiveErrors || 0) + 1;
3033
+ }
3034
+ }
3035
+ this.updateTasks(keycard, identifier, entry.tasks);
3036
+ }
3037
+ opts.forEach((opt) => opt.onTaskComplete?.(keycard, identifier, task.id, result));
3038
+ } catch (error) {
3039
+ const idx = entry.tasks.findIndex((t) => t.id === task.id);
3040
+ const errorTask = entry.tasks[idx];
3041
+ if (idx !== -1 && errorTask) {
3042
+ const isCancelled = error instanceof Error && (error.name === "AbortError" || error.message === "CANCELLED");
3043
+ if (isCancelled) {
3044
+ entry.tasks[idx] = {
3045
+ ...errorTask,
3046
+ status: "Waiting",
3047
+ isQueued: false
3048
+ };
3049
+ } else {
3050
+ entry.tasks[idx] = {
3051
+ ...errorTask,
3052
+ status: "Error",
3053
+ errorMessage: error instanceof Error ? error.message : String(error),
3054
+ isQueued: false
3055
+ };
3056
+ entry.consecutiveErrors = (entry.consecutiveErrors || 0) + 1;
3057
+ }
3058
+ this.updateTasks(keycard, identifier, entry.tasks);
3059
+ }
3060
+ opts.forEach(
3061
+ (opt) => opt.onTaskComplete?.(keycard, identifier, task.id, {
3062
+ success: false,
3063
+ error: String(error)
3064
+ })
3065
+ );
3066
+ } finally {
3067
+ this.abortControllers.delete(task.id);
3068
+ entry.queuedIds.delete(task.id);
3069
+ this.notifyStatusChange(keycard, identifier);
3070
+ this.notifyTasksUpdate(keycard, identifier, entry.tasks);
3071
+ const maxErrors = entry.taskConfig?.stopOnErrorCount || 0;
3072
+ if (maxErrors > 0 && (entry.consecutiveErrors || 0) >= maxErrors) {
3073
+ console.warn(
3074
+ `[QueueManager] Stopping queue due to ${entry.consecutiveErrors} consecutive errors.`
3075
+ );
3076
+ this.stop(keycard, identifier);
3077
+ entry.consecutiveErrors = 0;
3078
+ }
3079
+ }
3080
+ this.logQueueState(keycard, identifier, `PROCESS_END ${task.id}`);
3081
+ }
3082
+ async autoStopQueue(keycard, identifier) {
3083
+ const key = this.getQueueKey(keycard, identifier);
3084
+ const entry = this.queues.get(key);
3085
+ if (entry) {
3086
+ this.runningQueues.delete(key);
3087
+ entry.queue.pause();
3088
+ await this.persistState();
3089
+ this.notifyStatusChange(keycard, identifier);
3090
+ this.notifyTasksUpdate(keycard, identifier, entry.tasks);
3091
+ const opts = this.getOptions(keycard);
3092
+ opts.forEach((opt) => opt.onQueueEmpty?.(keycard, identifier));
3093
+ }
3094
+ }
3095
+ notifyStatusChange(keycard, identifier) {
3096
+ const key = this.getQueueKey(keycard, identifier);
3097
+ const entry = this.queues.get(key);
3098
+ const count = (entry?.queue.size || 0) + (entry?.queue.pending || 0);
3099
+ const opts = this.getOptions(keycard);
3100
+ opts.forEach((opt) => opt.onPendingCountChange?.(keycard, identifier, count));
3101
+ }
3102
+ notifyTasksUpdate(keycard, identifier, tasks) {
3103
+ const key = this.getQueueKey(keycard, identifier);
3104
+ const entry = this.queues.get(key);
3105
+ const status = {
3106
+ size: entry?.queue.size || 0,
3107
+ pending: entry?.queue.pending || 0,
3108
+ isPaused: entry?.queue.isPaused || false,
3109
+ isRunning: this.runningQueues.has(key)
3110
+ };
3111
+ const opts = this.getOptions(keycard);
3112
+ opts.forEach((opt) => opt.onTasksUpdate?.(keycard, identifier, tasks, status));
3113
+ }
3114
+ // --- PERSISTENCE & HYDRATION ---
3115
+ async persistState() {
3116
+ const states = {};
3117
+ for (const [key, entry] of this.queues.entries()) {
3118
+ states[key] = {
3119
+ isPaused: entry.queue.isPaused,
3120
+ isRunning: this.runningQueues.has(key)
3121
+ };
3122
+ }
3123
+ await persistenceManager.saveQueueStates(states);
3124
+ }
3125
+ updateTaskConfig(keycard, identifier, taskConfig) {
3126
+ const key = this.getQueueKey(keycard, identifier);
3127
+ const entry = this.queues.get(key);
3128
+ if (entry) {
3129
+ entry.taskConfig = taskConfig;
3130
+ entry.queue.concurrency = taskConfig.threads;
3131
+ console.log(`[QueueManager] Updated concurrency for ${key} to ${taskConfig.threads}`);
3132
+ }
3133
+ this.concurrencyMap.set(keycard, taskConfig.threads);
3134
+ }
3135
+ async hydrate() {
3136
+ const states = await persistenceManager.loadQueueStates();
3137
+ if (!states) return;
3138
+ for (const key in states) {
3139
+ const state = states[key];
3140
+ if (!state) continue;
3141
+ const [keycard, identifier] = key.split("__");
3142
+ if (!keycard || !identifier) continue;
3143
+ const entry = this.getOrCreateQueue(keycard, identifier);
3144
+ if (state.isPaused) {
3145
+ entry.queue.pause();
3146
+ } else {
3147
+ entry.queue.start();
3148
+ }
3149
+ if (state.isRunning) {
3150
+ this.runningQueues.add(key);
3151
+ }
3152
+ }
3153
+ }
3154
+ /**
3155
+ * Scans all hydrated queues and re-enqueues tasks that were in "Waiting" or "Running" status.
3156
+ * This ensures tasks resume after Service Worker restarts.
3157
+ */
3158
+ async rehydrateTasks() {
3159
+ for (const [key, entry] of this.queues.entries()) {
3160
+ const [keycard, identifier] = key.split("__");
3161
+ if (!keycard || !identifier) continue;
3162
+ const tasks = entry.tasks;
3163
+ if (!tasks || tasks.length === 0) continue;
3164
+ for (const task of tasks) {
3165
+ if (task.status === "Running") {
3166
+ task.status = "Waiting";
3167
+ }
3168
+ if (task.status === "Waiting" && task.id && !entry.queuedIds.has(task.id)) {
3169
+ task.isQueued = true;
3170
+ entry.queuedIds.add(task.id);
3171
+ entry.queue.add(() => this.processTask(keycard, identifier, task));
3172
+ }
3173
+ }
3174
+ this.updateTasks(keycard, identifier, tasks);
3175
+ }
3176
+ await this.persistState();
3177
+ }
3178
+ };
3179
+ var queueManagerInstance = null;
3180
+ function getQueueManager() {
3181
+ if (!queueManagerInstance) {
3182
+ queueManagerInstance = new QueueManager({
3183
+ defaultConcurrency: 1
3184
+ });
3185
+ }
3186
+ return queueManagerInstance;
3187
+ }
3188
+
3189
+ // src/core/commands.ts
3190
+ var QUEUE_COMMAND = {
3191
+ SYNC: "SYNC",
3192
+ CANCEL_TASK: "CANCEL_TASK",
3193
+ CANCEL_TASKS: "CANCEL_TASKS",
3194
+ ADD: "ADD",
3195
+ ADD_MANY: "ADD_MANY",
3196
+ START: "START",
3197
+ STOP: "STOP",
3198
+ PAUSE: "PAUSE",
3199
+ RESUME: "RESUME",
3200
+ CLEAR: "CLEAR",
3201
+ GET_STATUS: "GET_STATUS",
3202
+ GET_TASKS: "GET_TASKS",
3203
+ SET_TASK_CONFIG: "SET_TASK_CONFIG"
3204
+ };
3205
+
3206
+ // node_modules/zustand/esm/vanilla.mjs
3207
+ var createStoreImpl = (createState) => {
3208
+ let state;
3209
+ const listeners = /* @__PURE__ */ new Set();
3210
+ const setState = (partial, replace) => {
3211
+ const nextState = typeof partial === "function" ? partial(state) : partial;
3212
+ if (!Object.is(nextState, state)) {
3213
+ const previousState = state;
3214
+ state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
3215
+ listeners.forEach((listener) => listener(state, previousState));
3216
+ }
3217
+ };
3218
+ const getState = () => state;
3219
+ const getInitialState = () => initialState;
3220
+ const subscribe = (listener) => {
3221
+ listeners.add(listener);
3222
+ return () => listeners.delete(listener);
3223
+ };
3224
+ const api = { setState, getState, getInitialState, subscribe };
3225
+ const initialState = state = createState(setState, getState, api);
3226
+ return api;
3227
+ };
3228
+ var createStore = ((createState) => createState ? createStoreImpl(createState) : createStoreImpl);
3229
+
3230
+ // node_modules/zustand/esm/react.mjs
3231
+ var import_react = __toESM(require_react(), 1);
3232
+ var identity = (arg) => arg;
3233
+ function useStore(api, selector = identity) {
3234
+ const slice = import_react.default.useSyncExternalStore(
3235
+ api.subscribe,
3236
+ import_react.default.useCallback(() => selector(api.getState()), [api, selector]),
3237
+ import_react.default.useCallback(() => selector(api.getInitialState()), [api, selector])
3238
+ );
3239
+ import_react.default.useDebugValue(slice);
3240
+ return slice;
3241
+ }
3242
+ var createImpl = (createState) => {
3243
+ const api = createStore(createState);
3244
+ const useBoundStore = (selector) => useStore(api, selector);
3245
+ Object.assign(useBoundStore, api);
3246
+ return useBoundStore;
3247
+ };
3248
+ var create = ((createState) => createState ? createImpl(createState) : createImpl);
3249
+
3250
+ // node_modules/zustand/esm/middleware.mjs
3251
+ function createJSONStorage(getStorage, options) {
3252
+ let storage;
3253
+ try {
3254
+ storage = getStorage();
3255
+ } catch (e) {
3256
+ return;
3257
+ }
3258
+ const persistStorage = {
3259
+ getItem: (name) => {
3260
+ var _a;
3261
+ const parse = (str2) => {
3262
+ if (str2 === null) {
3263
+ return null;
3264
+ }
3265
+ return JSON.parse(str2, options == null ? void 0 : options.reviver);
3266
+ };
3267
+ const str = (_a = storage.getItem(name)) != null ? _a : null;
3268
+ if (str instanceof Promise) {
3269
+ return str.then(parse);
3270
+ }
3271
+ return parse(str);
3272
+ },
3273
+ setItem: (name, newValue) => storage.setItem(name, JSON.stringify(newValue, options == null ? void 0 : options.replacer)),
3274
+ removeItem: (name) => storage.removeItem(name)
3275
+ };
3276
+ return persistStorage;
3277
+ }
3278
+ var toThenable = (fn) => (input) => {
3279
+ try {
3280
+ const result = fn(input);
3281
+ if (result instanceof Promise) {
3282
+ return result;
3283
+ }
3284
+ return {
3285
+ then(onFulfilled) {
3286
+ return toThenable(onFulfilled)(result);
3287
+ },
3288
+ catch(_onRejected) {
3289
+ return this;
3290
+ }
3291
+ };
3292
+ } catch (e) {
3293
+ return {
3294
+ then(_onFulfilled) {
3295
+ return this;
3296
+ },
3297
+ catch(onRejected) {
3298
+ return toThenable(onRejected)(e);
3299
+ }
3300
+ };
3301
+ }
3302
+ };
3303
+ var persistImpl = (config, baseOptions) => (set, get, api) => {
3304
+ let options = {
3305
+ storage: createJSONStorage(() => window.localStorage),
3306
+ partialize: (state) => state,
3307
+ version: 0,
3308
+ merge: (persistedState, currentState) => ({
3309
+ ...currentState,
3310
+ ...persistedState
3311
+ }),
3312
+ ...baseOptions
3313
+ };
3314
+ let hasHydrated = false;
3315
+ let hydrationVersion = 0;
3316
+ const hydrationListeners = /* @__PURE__ */ new Set();
3317
+ const finishHydrationListeners = /* @__PURE__ */ new Set();
3318
+ let storage = options.storage;
3319
+ if (!storage) {
3320
+ return config(
3321
+ (...args) => {
3322
+ console.warn(
3323
+ `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`
3324
+ );
3325
+ set(...args);
3326
+ },
3327
+ get,
3328
+ api
3329
+ );
3330
+ }
3331
+ const setItem = () => {
3332
+ const state = options.partialize({ ...get() });
3333
+ return storage.setItem(options.name, {
3334
+ state,
3335
+ version: options.version
3336
+ });
3337
+ };
3338
+ const savedSetState = api.setState;
3339
+ api.setState = (state, replace) => {
3340
+ savedSetState(state, replace);
3341
+ return setItem();
3342
+ };
3343
+ const configResult = config(
3344
+ (...args) => {
3345
+ set(...args);
3346
+ return setItem();
3347
+ },
3348
+ get,
3349
+ api
3350
+ );
3351
+ api.getInitialState = () => configResult;
3352
+ let stateFromStorage;
3353
+ const hydrate = () => {
3354
+ var _a, _b;
3355
+ if (!storage) return;
3356
+ const currentVersion = ++hydrationVersion;
3357
+ hasHydrated = false;
3358
+ hydrationListeners.forEach((cb) => {
3359
+ var _a2;
3360
+ return cb((_a2 = get()) != null ? _a2 : configResult);
3361
+ });
3362
+ const postRehydrationCallback = ((_b = options.onRehydrateStorage) == null ? void 0 : _b.call(options, (_a = get()) != null ? _a : configResult)) || void 0;
3363
+ return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {
3364
+ if (deserializedStorageValue) {
3365
+ if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) {
3366
+ if (options.migrate) {
3367
+ const migration = options.migrate(
3368
+ deserializedStorageValue.state,
3369
+ deserializedStorageValue.version
3370
+ );
3371
+ if (migration instanceof Promise) {
3372
+ return migration.then((result) => [true, result]);
3373
+ }
3374
+ return [true, migration];
3375
+ }
3376
+ console.error(
3377
+ `State loaded from storage couldn't be migrated since no migrate function was provided`
3378
+ );
3379
+ } else {
3380
+ return [false, deserializedStorageValue.state];
3381
+ }
3382
+ }
3383
+ return [false, void 0];
3384
+ }).then((migrationResult) => {
3385
+ var _a2;
3386
+ if (currentVersion !== hydrationVersion) {
3387
+ return;
3388
+ }
3389
+ const [migrated, migratedState] = migrationResult;
3390
+ stateFromStorage = options.merge(
3391
+ migratedState,
3392
+ (_a2 = get()) != null ? _a2 : configResult
3393
+ );
3394
+ set(stateFromStorage, true);
3395
+ if (migrated) {
3396
+ return setItem();
3397
+ }
3398
+ }).then(() => {
3399
+ if (currentVersion !== hydrationVersion) {
3400
+ return;
3401
+ }
3402
+ postRehydrationCallback == null ? void 0 : postRehydrationCallback(get(), void 0);
3403
+ stateFromStorage = get();
3404
+ hasHydrated = true;
3405
+ finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
3406
+ }).catch((e) => {
3407
+ if (currentVersion !== hydrationVersion) {
3408
+ return;
3409
+ }
3410
+ postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);
3411
+ });
3412
+ };
3413
+ api.persist = {
3414
+ setOptions: (newOptions) => {
3415
+ options = {
3416
+ ...options,
3417
+ ...newOptions
3418
+ };
3419
+ if (newOptions.storage) {
3420
+ storage = newOptions.storage;
3421
+ }
3422
+ },
3423
+ clearStorage: () => {
3424
+ storage == null ? void 0 : storage.removeItem(options.name);
3425
+ },
3426
+ getOptions: () => options,
3427
+ rehydrate: () => hydrate(),
3428
+ hasHydrated: () => hasHydrated,
3429
+ onHydrate: (cb) => {
3430
+ hydrationListeners.add(cb);
3431
+ return () => {
3432
+ hydrationListeners.delete(cb);
3433
+ };
3434
+ },
3435
+ onFinishHydration: (cb) => {
3436
+ finishHydrationListeners.add(cb);
3437
+ return () => {
3438
+ finishHydrationListeners.delete(cb);
3439
+ };
3440
+ }
3441
+ };
3442
+ if (!options.skipHydration) {
3443
+ hydrate();
3444
+ }
3445
+ return stateFromStorage || configResult;
3446
+ };
3447
+ var persist = persistImpl;
3448
+
3449
+ // src/core/store/base-task.store.ts
3450
+ var createTaskStore = (options) => {
3451
+ const { name, storage, partialize, extend } = options;
3452
+ const baseState = {
3453
+ tasks: [],
3454
+ taskHistory: [],
3455
+ pendingCount: 0,
3456
+ isPaused: true,
3457
+ taskConfig: {
3458
+ threads: 1,
3459
+ delayMin: 1,
3460
+ delayMax: 15,
3461
+ stopOnErrorCount: 0
3462
+ }
3463
+ };
3464
+ if (storage) {
3465
+ return create()(
3466
+ persist(
3467
+ (set, get) => ({
3468
+ ...baseState,
3469
+ selectedIds: [],
3470
+ generating: false,
3471
+ getTasks: () => get().tasks,
3472
+ setTasks: (tasks) => {
3473
+ const uniqueTasks = Array.from(new Map(tasks.map((t) => [t.id, t])).values());
3474
+ set({ tasks: uniqueTasks });
3475
+ },
3476
+ setPendingCount: (count) => set({ pendingCount: count }),
3477
+ setIsPaused: (paused) => set({ isPaused: paused }),
3478
+ addTask: (task) => set((state) => {
3479
+ if (state.tasks.some((t) => t.id === task.id)) return state;
3480
+ const now = Date.now();
3481
+ const newTask = {
3482
+ ...task,
3483
+ createAt: task.createAt || now,
3484
+ updateAt: task.updateAt || now
3485
+ };
3486
+ return { tasks: [...state.tasks, newTask] };
3487
+ }),
3488
+ addTasks: (newTasks) => set((state) => {
3489
+ const existingIds = new Set(state.tasks.map((t) => t.id));
3490
+ const now = Date.now();
3491
+ const filteredNewTasks = newTasks.filter((t) => !existingIds.has(t.id)).map((t) => ({
3492
+ ...t,
3493
+ createAt: t.createAt || now,
3494
+ updateAt: t.updateAt || now
3495
+ }));
3496
+ if (filteredNewTasks.length === 0) return state;
3497
+ return { tasks: [...state.tasks, ...filteredNewTasks] };
3498
+ }),
3499
+ updateTask: (taskId, updates) => {
3500
+ set((state) => ({
3501
+ tasks: state.tasks.map(
3502
+ (t) => t.id === taskId ? { ...t, ...updates, updateAt: Date.now() } : t
3503
+ )
3504
+ }));
3505
+ },
3506
+ updateTasks: (updates) => set((state) => ({
3507
+ tasks: state.tasks.map(
3508
+ (t) => updates[t.id] ? { ...t, ...updates[t.id], updateAt: Date.now() } : t
3509
+ )
3510
+ })),
3511
+ deleteTasks: (taskIds) => set((state) => ({
3512
+ tasks: state.tasks.filter((t) => !taskIds.includes(t.id)).map((t, i) => ({ ...t, no: i + 1 })),
3513
+ selectedIds: state.selectedIds.filter((id) => !taskIds.includes(id))
3514
+ })),
3515
+ clearTasks: () => set({ tasks: [], selectedIds: [] }),
3516
+ addHistoryTask: (task) => set((state) => {
3517
+ const newHistory = [task, ...state.taskHistory || []];
3518
+ if (newHistory.length > 1e3) {
3519
+ newHistory.length = 1e3;
3520
+ }
3521
+ return { taskHistory: newHistory };
3522
+ }),
3523
+ clearHistory: () => set({ taskHistory: [] }),
3524
+ toggleSelect: (id) => set((state) => ({
3525
+ selectedIds: state.selectedIds.includes(id) ? state.selectedIds.filter((i) => i !== id) : [...state.selectedIds, id]
3526
+ })),
3527
+ toggleSelectAll: (ids) => set((state) => {
3528
+ const targetIds = ids || state.tasks.map((t) => t.id);
3529
+ const allTargetSelected = targetIds.length > 0 && targetIds.every((id) => state.selectedIds.includes(id));
3530
+ if (allTargetSelected) {
3531
+ return {
3532
+ selectedIds: state.selectedIds.filter((id) => !targetIds.includes(id))
3533
+ };
3534
+ } else {
3535
+ const newSelectedIds = Array.from(/* @__PURE__ */ new Set([...state.selectedIds, ...targetIds]));
3536
+ return { selectedIds: newSelectedIds };
3537
+ }
3538
+ }),
3539
+ setSelectedIds: (ids) => set({ selectedIds: ids }),
3540
+ clearSelected: () => set({ selectedIds: [] }),
3541
+ setGenerating: (generating) => set({ generating }),
3542
+ getIsPaused: () => get().isPaused,
3543
+ getGenerating: () => get().generating,
3544
+ getTaskConfig: () => get().taskConfig,
3545
+ updateTaskConfig: (updates) => set((state) => ({
3546
+ taskConfig: { ...state.taskConfig, ...updates }
3547
+ })),
3548
+ ...extend ? extend(set, get) : {}
3549
+ }),
3550
+ {
3551
+ name,
3552
+ storage: createJSONStorage(() => storage),
3553
+ partialize: (state) => {
3554
+ const basePersist = {
3555
+ tasks: state.tasks,
3556
+ taskHistory: state.taskHistory,
3557
+ selectedIds: state.selectedIds,
3558
+ taskConfig: state.taskConfig
3559
+ };
3560
+ const customPersist = partialize ? partialize(state) : {};
3561
+ return {
3562
+ ...basePersist,
3563
+ ...customPersist
3564
+ };
3565
+ }
3566
+ }
3567
+ )
3568
+ );
3569
+ }
3570
+ return create()((set, get) => ({
3571
+ ...baseState,
3572
+ selectedIds: [],
3573
+ generating: false,
3574
+ getTasks: () => get().tasks,
3575
+ setTasks: (tasks) => {
3576
+ const uniqueTasks = Array.from(new Map(tasks.map((t) => [t.id, t])).values());
3577
+ set({ tasks: uniqueTasks });
3578
+ },
3579
+ setPendingCount: (count) => set({ pendingCount: count }),
3580
+ setIsPaused: (paused) => set({ isPaused: paused }),
3581
+ addTask: (task) => set((state) => {
3582
+ if (state.tasks.some((t) => t.id === task.id)) return state;
3583
+ return { tasks: [...state.tasks, task] };
3584
+ }),
3585
+ addTasks: (newTasks) => set((state) => {
3586
+ const existingIds = new Set(state.tasks.map((t) => t.id));
3587
+ const filteredNewTasks = newTasks.filter((t) => !existingIds.has(t.id));
3588
+ if (filteredNewTasks.length === 0) return state;
3589
+ return { tasks: [...state.tasks, ...filteredNewTasks] };
3590
+ }),
3591
+ updateTask: (taskId, updates) => {
3592
+ set((state) => ({
3593
+ tasks: state.tasks.map((t) => t.id === taskId ? { ...t, ...updates } : t)
3594
+ }));
3595
+ },
3596
+ updateTasks: (updates) => set((state) => ({
3597
+ tasks: state.tasks.map((t) => updates[t.id] ? { ...t, ...updates[t.id] } : t)
3598
+ })),
3599
+ deleteTasks: (taskIds) => set((state) => ({
3600
+ tasks: state.tasks.filter((t) => !taskIds.includes(t.id)).map((t, i) => ({ ...t, no: i + 1 })),
3601
+ selectedIds: state.selectedIds.filter((id) => !taskIds.includes(id))
3602
+ })),
3603
+ clearTasks: () => set({ tasks: [], selectedIds: [] }),
3604
+ addHistoryTask: (task) => set((state) => {
3605
+ const newHistory = [task, ...state.taskHistory || []];
3606
+ if (newHistory.length > 1e3) {
3607
+ newHistory.length = 1e3;
3608
+ }
3609
+ return { taskHistory: newHistory };
3610
+ }),
3611
+ clearHistory: () => set({ taskHistory: [] }),
3612
+ toggleSelect: (id) => set((state) => ({
3613
+ selectedIds: state.selectedIds.includes(id) ? state.selectedIds.filter((i) => i !== id) : [...state.selectedIds, id]
3614
+ })),
3615
+ toggleSelectAll: (ids) => set((state) => {
3616
+ const targetIds = ids || state.tasks.map((t) => t.id);
3617
+ const allTargetSelected = targetIds.length > 0 && targetIds.every((id) => state.selectedIds.includes(id));
3618
+ if (allTargetSelected) {
3619
+ return {
3620
+ selectedIds: state.selectedIds.filter((id) => !targetIds.includes(id))
3621
+ };
3622
+ } else {
3623
+ const newSelectedIds = Array.from(/* @__PURE__ */ new Set([...state.selectedIds, ...targetIds]));
3624
+ return { selectedIds: newSelectedIds };
3625
+ }
3626
+ }),
3627
+ setSelectedIds: (ids) => set({ selectedIds: ids }),
3628
+ clearSelected: () => set({ selectedIds: [] }),
3629
+ setGenerating: (generating) => set({ generating }),
3630
+ getIsPaused: () => get().isPaused,
3631
+ getGenerating: () => get().generating,
3632
+ updateTaskConfig: (updates) => set((state) => ({
3633
+ taskConfig: { ...state.taskConfig, ...updates }
3634
+ })),
3635
+ ...extend ? extend(set, get) : {}
3636
+ }));
3637
+ };
3638
+
3639
+ // src/core/hooks/use-queue.ts
3640
+ var import_react2 = __toESM(require_react());
3641
+ function useQueue(config) {
3642
+ return function initQueue() {
3643
+ const { keycard, getIdentifier, funcs } = config;
3644
+ const safeSendMessage = (0, import_react2.useCallback)((msg, callback) => {
3645
+ try {
3646
+ if (!chrome.runtime?.id) {
3647
+ console.warn("Extension context invalidated.");
3648
+ return;
3649
+ }
3650
+ chrome.runtime.sendMessage(msg, (response) => {
3651
+ if (chrome.runtime.lastError) {
3652
+ console.warn("Message failed:", chrome.runtime.lastError.message);
3653
+ return;
3654
+ }
3655
+ callback?.(response);
3656
+ });
3657
+ } catch (e) {
3658
+ console.error("Critical messaging error:", e);
3659
+ }
3660
+ }, []);
3661
+ const lastInitializedRef = (0, import_react2.useRef)(void 0);
3662
+ const identifier = getIdentifier();
3663
+ (0, import_react2.useEffect)(() => {
3664
+ const currentId = identifier || "";
3665
+ const needsSync = lastInitializedRef.current !== currentId;
3666
+ if (needsSync) {
3667
+ lastInitializedRef.current = currentId;
3668
+ safeSendMessage(
3669
+ {
3670
+ type: "QUEUE_COMMAND",
3671
+ command: QUEUE_COMMAND.SYNC,
3672
+ keycard,
3673
+ identifier
3674
+ },
3675
+ (response) => {
3676
+ if (response) {
3677
+ if (response.tasks && response.tasks.length > 0) {
3678
+ funcs.setTasks(response.tasks);
3679
+ } else {
3680
+ const localTasks = funcs.getTasks();
3681
+ if (localTasks.length > 0) {
3682
+ safeSendMessage({
3683
+ type: "QUEUE_COMMAND",
3684
+ command: QUEUE_COMMAND.ADD_MANY,
3685
+ keycard,
3686
+ identifier,
3687
+ payload: { tasks: localTasks }
3688
+ });
3689
+ }
3690
+ }
3691
+ if (response.status) {
3692
+ funcs.setPendingCount(response.status.size + response.status.pending);
3693
+ funcs.setIsPaused(response.status.isPaused);
3694
+ }
3695
+ }
3696
+ }
3697
+ );
3698
+ }
3699
+ const handleMessage = (message) => {
3700
+ if (message.type === "QUEUE_EVENT") {
3701
+ const { event, keycard: pid, identifier: pjid, data } = message;
3702
+ const isPlatformMatch = pid === keycard || pid === "*";
3703
+ const isIdentifierMatch = (pjid || "") === (identifier || "") || pid === "*";
3704
+ if (!isPlatformMatch || !isIdentifierMatch) return;
3705
+ switch (event) {
3706
+ case "TASKS_UPDATED": {
3707
+ console.log("TASKS_UPDATED", data);
3708
+ const updates = {};
3709
+ data.tasks.forEach((t) => {
3710
+ updates[t.id] = t;
3711
+ });
3712
+ funcs.updateTasks(updates);
3713
+ funcs.setPendingCount(data.status.size + data.status.pending);
3714
+ funcs.setIsPaused(data.status.isPaused);
3715
+ break;
3716
+ }
3717
+ case "PENDING_COUNT_CHANGED":
3718
+ funcs.setPendingCount(data.count);
3719
+ break;
3720
+ case "HISTORY_ADDED":
3721
+ if (funcs.addHistoryTask) {
3722
+ funcs.addHistoryTask(data.task);
3723
+ }
3724
+ break;
3725
+ }
3726
+ }
3727
+ };
3728
+ chrome.runtime.onMessage.addListener(handleMessage);
3729
+ return () => {
3730
+ chrome.runtime.onMessage.removeListener(handleMessage);
3731
+ };
3732
+ }, [keycard, identifier, funcs, safeSendMessage]);
3733
+ const sendQueueCommand = (0, import_react2.useCallback)(
3734
+ async (command, payload) => {
3735
+ const identifier2 = getIdentifier();
3736
+ return new Promise((resolve) => {
3737
+ safeSendMessage(
3738
+ {
3739
+ type: "QUEUE_COMMAND",
3740
+ command,
3741
+ keycard,
3742
+ identifier: identifier2,
3743
+ payload
3744
+ },
3745
+ resolve
3746
+ );
3747
+ });
3748
+ },
3749
+ [keycard, getIdentifier, safeSendMessage]
3750
+ );
3751
+ const addTask = (0, import_react2.useCallback)(
3752
+ async (task) => {
3753
+ return sendQueueCommand(QUEUE_COMMAND.ADD, { task });
3754
+ },
3755
+ [sendQueueCommand, funcs]
3756
+ );
3757
+ const start = (0, import_react2.useCallback)(async () => {
3758
+ console.log(QUEUE_COMMAND.START);
3759
+ return sendQueueCommand(QUEUE_COMMAND.START);
3760
+ }, [sendQueueCommand, funcs]);
3761
+ const stop = (0, import_react2.useCallback)(async () => {
3762
+ console.log(QUEUE_COMMAND.STOP);
3763
+ return sendQueueCommand(QUEUE_COMMAND.STOP);
3764
+ }, [sendQueueCommand, funcs]);
3765
+ const pause = (0, import_react2.useCallback)(async () => {
3766
+ return sendQueueCommand(QUEUE_COMMAND.PAUSE);
3767
+ }, [sendQueueCommand]);
3768
+ const resume = (0, import_react2.useCallback)(async () => {
3769
+ return sendQueueCommand(QUEUE_COMMAND.RESUME);
3770
+ }, [sendQueueCommand]);
3771
+ const clear = (0, import_react2.useCallback)(async () => {
3772
+ return sendQueueCommand(QUEUE_COMMAND.CLEAR);
3773
+ }, [sendQueueCommand]);
3774
+ const getStatus = (0, import_react2.useCallback)(async () => {
3775
+ return sendQueueCommand(QUEUE_COMMAND.GET_STATUS);
3776
+ }, [sendQueueCommand]);
3777
+ const getTasks = (0, import_react2.useCallback)(async () => {
3778
+ return sendQueueCommand(QUEUE_COMMAND.GET_TASKS);
3779
+ }, [sendQueueCommand]);
3780
+ const cancelTask = (0, import_react2.useCallback)(
3781
+ async (taskId) => {
3782
+ return sendQueueCommand(QUEUE_COMMAND.CANCEL_TASK, { taskId });
3783
+ },
3784
+ [sendQueueCommand]
3785
+ );
3786
+ const cancelTasks = (0, import_react2.useCallback)(
3787
+ async (taskIds) => {
3788
+ return sendQueueCommand(QUEUE_COMMAND.CANCEL_TASKS, { taskIds });
3789
+ },
3790
+ [sendQueueCommand]
3791
+ );
3792
+ const setTaskConfig = (0, import_react2.useCallback)((taskConfig) => {
3793
+ return sendQueueCommand(QUEUE_COMMAND.SET_TASK_CONFIG, { taskConfig });
3794
+ }, []);
3795
+ const publishTasks = (0, import_react2.useCallback)(
3796
+ async (tasks) => {
3797
+ await sendQueueCommand(QUEUE_COMMAND.ADD_MANY, {
3798
+ tasks: tasks.map((t) => ({
3799
+ ...t,
3800
+ status: "Waiting",
3801
+ isQueued: true
3802
+ }))
3803
+ });
3804
+ },
3805
+ [funcs, sendQueueCommand]
3806
+ );
3807
+ const deleteTasks = (0, import_react2.useCallback)(
3808
+ async (taskIds) => {
3809
+ if (taskIds.length === 0) return;
3810
+ await sendQueueCommand(QUEUE_COMMAND.CANCEL_TASKS, { taskIds });
3811
+ funcs.deleteTasks(taskIds);
3812
+ },
3813
+ [funcs, sendQueueCommand]
3814
+ );
3815
+ const skipTaskIds = (0, import_react2.useCallback)(
3816
+ async (taskIds) => {
3817
+ if (taskIds.length === 0) return;
3818
+ await sendQueueCommand("CANCEL_TASKS", { taskIds });
3819
+ const updates = {};
3820
+ taskIds.forEach((id) => {
3821
+ updates[id] = { status: "Skipped", isQueued: false, isFlagged: true };
3822
+ });
3823
+ funcs.updateTasks(updates);
3824
+ },
3825
+ [funcs, sendQueueCommand]
3826
+ );
3827
+ const retryTasks = (0, import_react2.useCallback)(
3828
+ async (taskIds) => {
3829
+ const tasks = funcs.getTasks().filter((t) => taskIds.includes(t.id));
3830
+ if (tasks.length === 0) return;
3831
+ tasks.forEach((task) => {
3832
+ funcs.updateTask(task.id, {
3833
+ status: "Waiting",
3834
+ errorMessage: void 0,
3835
+ isQueued: true
3836
+ });
3837
+ });
3838
+ await sendQueueCommand(QUEUE_COMMAND.ADD_MANY, {
3839
+ tasks: tasks.map((t) => ({
3840
+ ...t,
3841
+ status: "Waiting",
3842
+ errorMessage: void 0,
3843
+ isQueued: true
3844
+ }))
3845
+ });
3846
+ },
3847
+ [funcs, sendQueueCommand]
3848
+ );
3849
+ return {
3850
+ addTask,
3851
+ start,
3852
+ stop,
3853
+ pause,
3854
+ resume,
3855
+ clear,
3856
+ getStatus,
3857
+ getTasks,
3858
+ cancelTask,
3859
+ cancelTasks,
3860
+ publishTasks,
3861
+ deleteTasks,
3862
+ retryTasks,
3863
+ skipTaskIds,
3864
+ setTaskConfig
3865
+ };
3866
+ };
3867
+ }
3868
+
3869
+ // src/core/registry.ts
3870
+ function registerAllEngines(platformEngines, queueManager) {
3871
+ Object.entries(platformEngines).forEach(([keycard, engine]) => {
3872
+ queueManager.registerEngine(keycard, engine);
3873
+ });
3874
+ }
3875
+
3876
+ // src/core/bootstrap.ts
3877
+ var setupBackgroundEngine = (engines) => {
3878
+ const queueManager = getQueueManager();
3879
+ registerAllEngines(engines, queueManager);
3880
+ const broadcast = (message) => {
3881
+ chrome.runtime.sendMessage(message).catch(() => {
3882
+ });
3883
+ };
3884
+ const handleHeartbeat = (count) => {
3885
+ if (count > 0) {
3886
+ chrome.alarms.create("heartbeat", { periodInMinutes: 0.5 });
3887
+ } else {
3888
+ chrome.alarms.clear("heartbeat");
3889
+ }
3890
+ };
3891
+ queueManager.registerOptions("*", {
3892
+ onTasksUpdate: (keycard, identifier, tasks, status) => {
3893
+ broadcast({
3894
+ type: "QUEUE_EVENT",
3895
+ event: "TASKS_UPDATED",
3896
+ keycard,
3897
+ identifier,
3898
+ data: { tasks, status }
3899
+ });
3900
+ },
3901
+ onTaskComplete: (keycard, identifier, _, result) => {
3902
+ const isCancelled = result.error === "CANCELLED" || result.error === "AbortError";
3903
+ if (!isCancelled) {
3904
+ broadcast({
3905
+ type: "QUEUE_EVENT",
3906
+ event: "HISTORY_ADDED",
3907
+ keycard,
3908
+ identifier,
3909
+ data: { task: [] }
3910
+ });
3911
+ }
3912
+ },
3913
+ onPendingCountChange: (keycard, identifier, count) => {
3914
+ broadcast({
3915
+ type: "QUEUE_EVENT",
3916
+ event: "PENDING_COUNT_CHANGED",
3917
+ keycard,
3918
+ identifier,
3919
+ data: { count }
3920
+ });
3921
+ handleHeartbeat(count);
3922
+ }
3923
+ });
3924
+ const bootstrap = async () => {
3925
+ try {
3926
+ console.log("\u{1F680} Bootstrapping Background Queue Manager...");
3927
+ await queueManager.hydrate();
3928
+ await queueManager.rehydrateTasks();
3929
+ console.log("\u2705 Background Queue Manager Ready.");
3930
+ } catch (error) {
3931
+ console.error("\u274C Bootstrap failed:", error);
3932
+ }
3933
+ };
3934
+ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
3935
+ if (message.type === "QUEUE_COMMAND") {
3936
+ const { command, keycard, identifier, payload } = message;
3937
+ const handleAsyncCommand = async (promise) => {
3938
+ await promise;
3939
+ sendResponse({ success: true });
3940
+ };
3941
+ switch (command) {
3942
+ case QUEUE_COMMAND.SYNC:
3943
+ sendResponse({
3944
+ tasks: queueManager.getTasks(keycard, identifier),
3945
+ status: queueManager.getStatus(keycard, identifier)
3946
+ });
3947
+ break;
3948
+ case QUEUE_COMMAND.CANCEL_TASK:
3949
+ handleAsyncCommand(queueManager.cancelTask(keycard, identifier, payload.taskId));
3950
+ return true;
3951
+ // Keep connection to send response later
3952
+ case QUEUE_COMMAND.CANCEL_TASKS:
3953
+ handleAsyncCommand(
3954
+ Promise.all(
3955
+ payload.taskIds.map((id) => queueManager.cancelTask(keycard, identifier, id))
3956
+ )
3957
+ );
3958
+ return true;
3959
+ case QUEUE_COMMAND.ADD:
3960
+ handleAsyncCommand(queueManager.add(keycard, identifier, payload.task));
3961
+ return true;
3962
+ case QUEUE_COMMAND.ADD_MANY:
3963
+ handleAsyncCommand(queueManager.addMany(keycard, identifier, payload.tasks));
3964
+ return true;
3965
+ case QUEUE_COMMAND.START:
3966
+ handleAsyncCommand(queueManager.start(keycard, identifier));
3967
+ return true;
3968
+ case QUEUE_COMMAND.STOP:
3969
+ handleAsyncCommand(queueManager.stop(keycard, identifier));
3970
+ return true;
3971
+ case QUEUE_COMMAND.PAUSE:
3972
+ handleAsyncCommand(queueManager.pause(keycard, identifier));
3973
+ return true;
3974
+ case QUEUE_COMMAND.RESUME:
3975
+ handleAsyncCommand(queueManager.resume(keycard, identifier));
3976
+ return true;
3977
+ case QUEUE_COMMAND.CLEAR:
3978
+ handleAsyncCommand(queueManager.clear(keycard, identifier));
3979
+ return true;
3980
+ case QUEUE_COMMAND.GET_STATUS:
3981
+ sendResponse(queueManager.getStatus(keycard, identifier));
3982
+ break;
3983
+ case QUEUE_COMMAND.GET_TASKS:
3984
+ sendResponse({ tasks: queueManager.getTasks(keycard, identifier) });
3985
+ break;
3986
+ case QUEUE_COMMAND.SET_TASK_CONFIG:
3987
+ queueManager.updateTaskConfig(keycard, identifier, payload.taskConfig);
3988
+ sendResponse({ success: true });
3989
+ break;
3990
+ default:
3991
+ console.warn(`[Queue] Unknown command: ${command}`);
3992
+ break;
3993
+ }
3994
+ }
3995
+ if (message.type === "PING") {
3996
+ sendResponse({ payload: "PONG from background" });
3997
+ }
3998
+ });
3999
+ chrome.alarms.onAlarm.addListener((alarm) => {
4000
+ if (alarm.name === "heartbeat") {
4001
+ console.debug("Service Worker Heartbeat...");
4002
+ }
4003
+ });
4004
+ chrome.runtime.onInstalled.addListener(() => {
4005
+ console.log("Auto Script Extension Installed");
4006
+ });
4007
+ chrome.commands.onCommand.addListener((command) => {
4008
+ if (command === "open-popup") {
4009
+ chrome.action.openPopup().catch((err) => console.error("Failed to open popup", err));
4010
+ }
4011
+ });
4012
+ bootstrap();
4013
+ };
4014
+ // Annotate the CommonJS export names for ESM import in node:
4015
+ 0 && (module.exports = {
4016
+ QUEUE_COMMAND,
4017
+ QueueManager,
4018
+ TaskContext,
4019
+ createTaskStore,
4020
+ engineHub,
4021
+ getQueueManager,
4022
+ persistenceManager,
4023
+ registerAllEngines,
4024
+ setupBackgroundEngine,
4025
+ sleep,
4026
+ useQueue
4027
+ });
4028
+ /*! Bundled license information:
4029
+
4030
+ react/cjs/react.production.js:
4031
+ (**
4032
+ * @license React
4033
+ * react.production.js
4034
+ *
4035
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
4036
+ *
4037
+ * This source code is licensed under the MIT license found in the
4038
+ * LICENSE file in the root directory of this source tree.
4039
+ *)
4040
+
4041
+ react/cjs/react.development.js:
4042
+ (**
4043
+ * @license React
4044
+ * react.development.js
4045
+ *
4046
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
4047
+ *
4048
+ * This source code is licensed under the MIT license found in the
4049
+ * LICENSE file in the root directory of this source tree.
4050
+ *)
4051
+ */