atom-effect-jquery 0.1.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.mjs ADDED
@@ -0,0 +1,1677 @@
1
+ var Ae = Object.defineProperty;
2
+ var Oe = (t, e, s) => e in t ? Ae(t, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : t[e] = s;
3
+ var W = (t, e, s) => Oe(t, typeof e != "symbol" ? e + "" : e, s);
4
+ import c from "jquery";
5
+ import { default as ot } from "jquery";
6
+ const we = {
7
+ /** One second in milliseconds */
8
+ ONE_SECOND_MS: 1e3
9
+ }, K = {
10
+ IDLE: "idle",
11
+ PENDING: "pending",
12
+ RESOLVED: "resolved",
13
+ REJECTED: "rejected"
14
+ }, Z = {
15
+ DISPOSED: 1,
16
+ // 0001 - Effect has been disposed
17
+ EXECUTING: 2
18
+ // 0010 - Effect is currently executing
19
+ }, _ = {
20
+ DIRTY: 1,
21
+ // 0001 - Needs recomputation
22
+ IDLE: 2,
23
+ // 0010 - Initial state, not computed yet
24
+ PENDING: 4,
25
+ // 0100 - Async computation in progress
26
+ RESOLVED: 8,
27
+ // 1000 - Successfully computed
28
+ REJECTED: 16,
29
+ // 10000 - Computation failed
30
+ RECOMPUTING: 32,
31
+ // 100000 - Currently recomputing
32
+ HAS_ERROR: 64
33
+ // 1000000 - Has error state
34
+ }, P = {
35
+ /** Maximum effect executions per second to detect infinite loops (Legacy/Fallback) */
36
+ MAX_EXECUTIONS_PER_SECOND: 1e3,
37
+ /**
38
+ * Maximum executions per effect within a single flush cycle
39
+ * Increased from 50 to 100
40
+ */
41
+ MAX_EXECUTIONS_PER_EFFECT: 100,
42
+ /**
43
+ * Maximum total executions across all effects in a single flush cycle
44
+ * Increased from 5000 to 10000
45
+ */
46
+ MAX_EXECUTIONS_PER_FLUSH: 1e4,
47
+ /** Maximum iterations for synchronous flush loop to prevent infinite loops */
48
+ MAX_FLUSH_ITERATIONS: 1e3,
49
+ /** Minimum allowed value for max flush iterations */
50
+ MIN_FLUSH_ITERATIONS: 10
51
+ }, fe = {
52
+ /** Maximum dependencies before warning about large dependency graphs */
53
+ MAX_DEPENDENCIES: 1e3,
54
+ /** Enable infinite loop detection warnings */
55
+ WARN_INFINITE_LOOP: !0
56
+ }, X = 1073741823, x = typeof process < "u" && process.env && process.env.NODE_ENV !== "production";
57
+ class O extends Error {
58
+ /**
59
+ * Creates a new AtomError
60
+ * @param message - Error message describing what went wrong
61
+ * @param cause - Original error that caused this error
62
+ * @param recoverable - Whether the operation can be retried
63
+ */
64
+ constructor(e, s = null, n = !0) {
65
+ super(e), this.name = "AtomError", this.cause = s, this.recoverable = n, this.timestamp = /* @__PURE__ */ new Date();
66
+ }
67
+ }
68
+ class q extends O {
69
+ /**
70
+ * Creates a new ComputedError
71
+ * @param message - Error message
72
+ * @param cause - Original error
73
+ */
74
+ constructor(e, s = null) {
75
+ super(e, s, !0), this.name = "ComputedError";
76
+ }
77
+ }
78
+ class w extends O {
79
+ /**
80
+ * Creates a new EffectError
81
+ * @param message - Error message
82
+ * @param cause - Original error
83
+ */
84
+ constructor(e, s = null) {
85
+ super(e, s, !1), this.name = "EffectError";
86
+ }
87
+ }
88
+ class ee extends O {
89
+ /**
90
+ * Creates a new SchedulerError
91
+ * @param message - Error message
92
+ * @param cause - Original error
93
+ */
94
+ constructor(e, s = null) {
95
+ super(e, s, !1), this.name = "SchedulerError";
96
+ }
97
+ }
98
+ const b = {
99
+ // ─────────────────────────────────────────────────────────────────
100
+ // Computed errors
101
+ // ─────────────────────────────────────────────────────────────────
102
+ /**
103
+ * Error thrown when computed() receives a non-function argument.
104
+ */
105
+ COMPUTED_MUST_BE_FUNCTION: "Computed function must be a function",
106
+ /**
107
+ * Error thrown when subscribe() receives an invalid listener.
108
+ */
109
+ COMPUTED_SUBSCRIBER_MUST_BE_FUNCTION: "Subscriber listener must be a function or Subscriber object",
110
+ /**
111
+ * Error thrown when accessing a pending async computed without a default value.
112
+ */
113
+ COMPUTED_ASYNC_PENDING_NO_DEFAULT: "Async computation is pending. No default value provided",
114
+ /**
115
+ * Error thrown when a synchronous computed computation fails.
116
+ */
117
+ COMPUTED_COMPUTATION_FAILED: "Computed computation failed",
118
+ /**
119
+ * Error thrown when an asynchronous computed computation fails.
120
+ */
121
+ COMPUTED_ASYNC_COMPUTATION_FAILED: "Async computed computation failed",
122
+ /**
123
+ * Error thrown when subscribing to a dependency fails.
124
+ */
125
+ COMPUTED_DEPENDENCY_SUBSCRIPTION_FAILED: "Failed to subscribe to dependency",
126
+ // ─────────────────────────────────────────────────────────────────
127
+ // Atom errors
128
+ // ─────────────────────────────────────────────────────────────────
129
+ /**
130
+ * Error thrown when atom.subscribe() receives an invalid listener.
131
+ */
132
+ ATOM_SUBSCRIBER_MUST_BE_FUNCTION: "Subscription listener must be a function or Subscriber object",
133
+ /**
134
+ * Error thrown when the atom subscriber notification process fails.
135
+ */
136
+ ATOM_SUBSCRIBER_EXECUTION_FAILED: "Error occurred while executing atom subscribers",
137
+ /**
138
+ * Error logged when an individual subscriber throws during notification.
139
+ * @remarks This error is caught and logged to prevent cascading failures.
140
+ */
141
+ ATOM_INDIVIDUAL_SUBSCRIBER_FAILED: "Error during individual atom subscriber execution",
142
+ // ─────────────────────────────────────────────────────────────────
143
+ // Effect errors
144
+ // ─────────────────────────────────────────────────────────────────
145
+ /**
146
+ * Error thrown when effect() receives a non-function argument.
147
+ */
148
+ EFFECT_MUST_BE_FUNCTION: "Effect function must be a function",
149
+ /**
150
+ * Error thrown when an effect's execution fails.
151
+ */
152
+ EFFECT_EXECUTION_FAILED: "Effect execution failed",
153
+ /**
154
+ * Error thrown when an effect's cleanup function fails.
155
+ */
156
+ EFFECT_CLEANUP_FAILED: "Effect cleanup function execution failed",
157
+ // ─────────────────────────────────────────────────────────────────
158
+ // Debug warnings
159
+ // ─────────────────────────────────────────────────────────────────
160
+ /**
161
+ * Warning message for large dependency graphs.
162
+ *
163
+ * @param count - The number of dependencies detected
164
+ * @returns Formatted warning message with dependency count
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * console.warn(ERROR_MESSAGES.LARGE_DEPENDENCY_GRAPH(150));
169
+ * // Output: "Large dependency graph detected: 150 dependencies"
170
+ * ```
171
+ */
172
+ LARGE_DEPENDENCY_GRAPH: (t) => `Large dependency graph detected: ${t} dependencies`,
173
+ /**
174
+ * Warning logged when attempting to unsubscribe a non-existent listener.
175
+ */
176
+ UNSUBSCRIBE_NON_EXISTENT: "Attempted to unsubscribe a non-existent listener",
177
+ /**
178
+ * Error logged when the onError callback itself throws an error.
179
+ * @remarks This prevents cascading failures from masking the original error.
180
+ */
181
+ CALLBACK_ERROR_IN_ERROR_HANDLER: "Error occurred during onError callback execution"
182
+ }, re = /* @__PURE__ */ Symbol("debugName"), Fe = /* @__PURE__ */ Symbol("id"), oe = /* @__PURE__ */ Symbol("type"), de = /* @__PURE__ */ Symbol("noDefaultValue");
183
+ function ke(t) {
184
+ return "dependencies" in t && Array.isArray(t.dependencies);
185
+ }
186
+ let _e = 0;
187
+ function Se(t, e, s) {
188
+ if (t._visitedEpoch !== s) {
189
+ if (t._visitedEpoch = s, t === e)
190
+ throw new q("Indirect circular dependency detected");
191
+ if (ke(t)) {
192
+ const n = t.dependencies;
193
+ for (let i = 0; i < n.length; i++) {
194
+ const r = n[i];
195
+ r && Se(r, e, s);
196
+ }
197
+ }
198
+ }
199
+ }
200
+ var me;
201
+ const U = {
202
+ enabled: typeof process < "u" && ((me = process.env) == null ? void 0 : me.NODE_ENV) === "development",
203
+ maxDependencies: fe.MAX_DEPENDENCIES,
204
+ warnInfiniteLoop: fe.WARN_INFINITE_LOOP,
205
+ warn(t, e) {
206
+ this.enabled && t && console.warn(`[Atom Effect] ${e}`);
207
+ },
208
+ /**
209
+ * Checks for circular dependencies.
210
+ * Direct check runs always; indirect check only in dev mode.
211
+ * @throws {ComputedError} When circular dependency detected
212
+ */
213
+ checkCircular(t, e) {
214
+ if (t === e)
215
+ throw new q("Direct circular dependency detected");
216
+ this.enabled && (_e++, Se(t, e, _e));
217
+ },
218
+ attachDebugInfo(t, e, s) {
219
+ if (!this.enabled)
220
+ return;
221
+ const n = t;
222
+ n[re] = `${e}_${s}`, n[Fe] = s, n[oe] = e;
223
+ },
224
+ getDebugName(t) {
225
+ if (t != null && re in t)
226
+ return t[re];
227
+ },
228
+ getDebugType(t) {
229
+ if (t != null && oe in t)
230
+ return t[oe];
231
+ }
232
+ };
233
+ let Me = 1;
234
+ const Pe = () => Me++;
235
+ class ye {
236
+ constructor() {
237
+ this.id = Pe() & X, this.flags = 0;
238
+ }
239
+ }
240
+ class De extends ye {
241
+ constructor() {
242
+ super(), this.version = 0, this._lastSeenEpoch = -1;
243
+ }
244
+ /**
245
+ * Subscribes a listener function or Subscriber object to value changes.
246
+ *
247
+ * @param listener - Function or Subscriber object to call when the value changes
248
+ * @returns An unsubscribe function
249
+ * @throws {AtomError} If listener is not a function or Subscriber
250
+ */
251
+ subscribe(e) {
252
+ if (typeof e == "object" && e !== null && "execute" in e)
253
+ return this._objectSubscribers.add(e);
254
+ if (typeof e != "function")
255
+ throw new O(b.ATOM_SUBSCRIBER_MUST_BE_FUNCTION);
256
+ return this._functionSubscribers.add(e);
257
+ }
258
+ /**
259
+ * Gets the total number of active subscribers.
260
+ */
261
+ subscriberCount() {
262
+ return this._functionSubscribers.size + this._objectSubscribers.size;
263
+ }
264
+ /**
265
+ * Notifies all subscribers of a change.
266
+ *
267
+ * @param newValue - The new value
268
+ * @param oldValue - The old value
269
+ */
270
+ _notifySubscribers(e, s) {
271
+ this._functionSubscribers.forEachSafe(
272
+ (n) => n(e, s),
273
+ (n) => console.error(new O(b.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED, n))
274
+ ), this._objectSubscribers.forEachSafe(
275
+ (n) => n.execute(),
276
+ (n) => console.error(new O(b.ATOM_INDIVIDUAL_SUBSCRIBER_FAILED, n))
277
+ );
278
+ }
279
+ }
280
+ let ce = 0;
281
+ function Ce() {
282
+ return ce = (ce + 1 | 0) & X, ce;
283
+ }
284
+ let se = 0, he = 0, ne = !1;
285
+ function pe() {
286
+ return ne ? (x && console.warn(
287
+ "Warning: startFlush() called during flush - ignored to prevent infinite loop detection bypass"
288
+ ), !1) : (ne = !0, se = se + 1 & X, he = 0, !0);
289
+ }
290
+ function be() {
291
+ ne = !1;
292
+ }
293
+ function Le() {
294
+ return ne ? ++he : 0;
295
+ }
296
+ class $e {
297
+ constructor() {
298
+ this.queueA = [], this.queueB = [], this.queue = this.queueA, this.queueSize = 0, this._epoch = 0, this.isProcessing = !1, this.isBatching = !1, this.batchDepth = 0, this.batchQueue = [], this.batchQueueSize = 0, this.isFlushingSync = !1, this.maxFlushIterations = P.MAX_FLUSH_ITERATIONS;
299
+ }
300
+ get phase() {
301
+ return this.isProcessing || this.isFlushingSync ? 2 : this.isBatching ? 1 : 0;
302
+ }
303
+ /**
304
+ * Schedules a task for execution.
305
+ * Tasks are deduplicated within the same flush cycle using epoch tracking.
306
+ * @param callback - The function to execute.
307
+ * @throws {SchedulerError} If the callback is not a function.
308
+ */
309
+ schedule(e) {
310
+ if (typeof e != "function")
311
+ throw new ee("Scheduler callback must be a function");
312
+ e._nextEpoch !== this._epoch && (e._nextEpoch = this._epoch, this.isBatching || this.isFlushingSync ? this.batchQueue[this.batchQueueSize++] = e : (this.queue[this.queueSize++] = e, this.isProcessing || this.flush()));
313
+ }
314
+ flush() {
315
+ if (this.isProcessing || this.queueSize === 0) return;
316
+ this.isProcessing = !0;
317
+ const e = this.queue, s = this.queueSize;
318
+ this.queue = this.queue === this.queueA ? this.queueB : this.queueA, this.queueSize = 0, this._epoch++, queueMicrotask(() => {
319
+ const n = pe();
320
+ this._processJobs(e, s), this.isProcessing = !1, n && be(), this.queueSize > 0 && !this.isBatching && this.flush();
321
+ });
322
+ }
323
+ flushSync() {
324
+ this.isFlushingSync = !0;
325
+ const e = pe();
326
+ try {
327
+ this._mergeBatchQueue(), this._drainQueue();
328
+ } finally {
329
+ this.isFlushingSync = !1, e && be();
330
+ }
331
+ }
332
+ _mergeBatchQueue() {
333
+ if (this._epoch++, this.batchQueueSize > 0) {
334
+ for (let e = 0; e < this.batchQueueSize; e++) {
335
+ const s = this.batchQueue[e];
336
+ s && s._nextEpoch !== this._epoch && (s._nextEpoch = this._epoch, this.queue[this.queueSize++] = s);
337
+ }
338
+ this.batchQueueSize = 0;
339
+ }
340
+ }
341
+ _drainQueue() {
342
+ let e = 0;
343
+ for (; this.queueSize > 0; ) {
344
+ if (++e > this.maxFlushIterations) {
345
+ this._handleFlushOverflow();
346
+ break;
347
+ }
348
+ this._processCurrentQueue(), this._mergeBatchQueue();
349
+ }
350
+ }
351
+ _processCurrentQueue() {
352
+ const e = this.queue, s = this.queueSize;
353
+ this.queue = this.queue === this.queueA ? this.queueB : this.queueA, this.queueSize = 0, this._epoch++, this._processJobs(e, s);
354
+ }
355
+ _handleFlushOverflow() {
356
+ console.error(
357
+ new ee(
358
+ `Maximum flush iterations (${this.maxFlushIterations}) exceeded. Possible infinite loop.`
359
+ )
360
+ ), this.queueSize = 0, this.queue.length = 0, this.batchQueueSize = 0;
361
+ }
362
+ _processJobs(e, s) {
363
+ var n;
364
+ for (let i = 0; i < s; i++)
365
+ try {
366
+ (n = e[i]) == null || n.call(e);
367
+ } catch (r) {
368
+ console.error(
369
+ new ee("Error occurred during scheduler execution", r)
370
+ );
371
+ }
372
+ e.length = 0;
373
+ }
374
+ /** Starts a new batch of updates. Updates will be deferred until endBatch is called. */
375
+ startBatch() {
376
+ this.batchDepth++, this.isBatching = !0;
377
+ }
378
+ /**
379
+ * Ends the current batch. If the batch depth reaches zero, all pending updates are flushed synchronously.
380
+ */
381
+ endBatch() {
382
+ this.batchDepth = Math.max(0, this.batchDepth - 1), this.batchDepth === 0 && (this.flushSync(), this.isBatching = !1);
383
+ }
384
+ /**
385
+ * Configures the maximum number of iterations allowed during a synchronous flush.
386
+ * Used to prevent infinite loops.
387
+ * @param max - Maximum iterations count.
388
+ */
389
+ setMaxFlushIterations(e) {
390
+ if (e < P.MIN_FLUSH_ITERATIONS)
391
+ throw new ee(
392
+ `Max flush iterations must be at least ${P.MIN_FLUSH_ITERATIONS}`
393
+ );
394
+ this.maxFlushIterations = e;
395
+ }
396
+ }
397
+ const H = new $e();
398
+ function A(t) {
399
+ if (typeof t != "function")
400
+ throw new O("Batch callback must be a function");
401
+ H.startBatch();
402
+ try {
403
+ return t();
404
+ } finally {
405
+ H.endBatch();
406
+ }
407
+ }
408
+ const V = {
409
+ current: null,
410
+ run(t, e) {
411
+ const s = this.current;
412
+ this.current = t;
413
+ try {
414
+ return e();
415
+ } finally {
416
+ this.current = s;
417
+ }
418
+ },
419
+ getCurrent() {
420
+ return this.current;
421
+ }
422
+ };
423
+ function xe(t) {
424
+ if (typeof t != "function")
425
+ throw new O("Untracked callback must be a function");
426
+ const e = V.current;
427
+ V.current = null;
428
+ try {
429
+ return t();
430
+ } finally {
431
+ V.current = e;
432
+ }
433
+ }
434
+ class ie {
435
+ constructor() {
436
+ this.subscribers = null;
437
+ }
438
+ /** Adds subscriber and returns unsubscribe function (idempotent) */
439
+ add(e) {
440
+ if (this.subscribers || (this.subscribers = []), this.subscribers.indexOf(e) !== -1)
441
+ return () => {
442
+ };
443
+ this.subscribers.push(e);
444
+ let s = !1;
445
+ return () => {
446
+ s || (s = !0, this.remove(e));
447
+ };
448
+ }
449
+ /** Removes subscriber using swap-and-pop */
450
+ remove(e) {
451
+ if (!this.subscribers)
452
+ return !1;
453
+ const s = this.subscribers.indexOf(e);
454
+ if (s === -1)
455
+ return !1;
456
+ const n = this.subscribers.length - 1;
457
+ return s !== n && (this.subscribers[s] = this.subscribers[n]), this.subscribers.pop(), !0;
458
+ }
459
+ has(e) {
460
+ return this.subscribers ? this.subscribers.indexOf(e) !== -1 : !1;
461
+ }
462
+ forEach(e) {
463
+ if (this.subscribers)
464
+ for (let s = 0; s < this.subscribers.length; s++)
465
+ e(this.subscribers[s], s);
466
+ }
467
+ /** Iterates with error handling to prevent one failure from breaking the chain */
468
+ forEachSafe(e, s) {
469
+ if (this.subscribers)
470
+ for (let n = 0; n < this.subscribers.length; n++)
471
+ try {
472
+ e(this.subscribers[n], n);
473
+ } catch (i) {
474
+ s ? s(i) : console.error("[SubscriberManager] Error in subscriber callback:", i);
475
+ }
476
+ }
477
+ get size() {
478
+ var e;
479
+ return ((e = this.subscribers) == null ? void 0 : e.length) ?? 0;
480
+ }
481
+ get hasSubscribers() {
482
+ return this.subscribers !== null && this.subscribers.length > 0;
483
+ }
484
+ clear() {
485
+ this.subscribers = null;
486
+ }
487
+ toArray() {
488
+ return this.subscribers ? [...this.subscribers] : [];
489
+ }
490
+ }
491
+ function ue(t) {
492
+ return t !== null && typeof t == "object" && "value" in t && "subscribe" in t && typeof t.subscribe == "function";
493
+ }
494
+ function Ee(t) {
495
+ if (U.enabled && (t == null || typeof t == "object")) {
496
+ const e = U.getDebugType(t);
497
+ if (e)
498
+ return e === "computed";
499
+ }
500
+ return ue(t) && "invalidate" in t && typeof t.invalidate == "function";
501
+ }
502
+ function Ie(t) {
503
+ return t != null && typeof t.then == "function";
504
+ }
505
+ function Ve(t) {
506
+ return typeof t == "object" && t !== null;
507
+ }
508
+ function ve(t) {
509
+ return (typeof t == "object" || typeof t == "function") && t !== null && typeof t.addDependency == "function";
510
+ }
511
+ function Ne(t) {
512
+ return typeof t == "function" && typeof t.addDependency != "function";
513
+ }
514
+ function Ue(t) {
515
+ return Ve(t) && typeof t.execute == "function";
516
+ }
517
+ class je extends De {
518
+ constructor(e, s) {
519
+ super(), this._isNotificationScheduled = !1, this._value = e, this._functionSubscribersStore = new ie(), this._objectSubscribersStore = new ie(), this._sync = s, this._notifyTask = this._flushNotifications.bind(this), U.attachDebugInfo(this, "atom", this.id);
520
+ }
521
+ /** Gets the manager for function-based subscribers. */
522
+ get _functionSubscribers() {
523
+ return this._functionSubscribersStore;
524
+ }
525
+ /** Gets the manager for object-based subscribers. */
526
+ get _objectSubscribers() {
527
+ return this._objectSubscribersStore;
528
+ }
529
+ /**
530
+ * Returns the current value and registers the atom as a dependency in the current tracking context.
531
+ */
532
+ get value() {
533
+ const e = V.getCurrent();
534
+ return e && this._track(e), this._value;
535
+ }
536
+ /**
537
+ * Sets a new value and schedules notifications if the value has changed.
538
+ * Uses `Object.is` for comparison.
539
+ */
540
+ set value(e) {
541
+ if (Object.is(this._value, e)) return;
542
+ const s = this._value;
543
+ this.version = this.version + 1 & X, this._value = e, !(!this._functionSubscribersStore.hasSubscribers && !this._objectSubscribersStore.hasSubscribers) && this._scheduleNotification(s);
544
+ }
545
+ _track(e) {
546
+ if (ve(e)) {
547
+ e.addDependency(this);
548
+ return;
549
+ }
550
+ if (Ne(e)) {
551
+ this._functionSubscribersStore.add(e);
552
+ return;
553
+ }
554
+ Ue(e) && this._objectSubscribersStore.add(e);
555
+ }
556
+ _scheduleNotification(e) {
557
+ this._isNotificationScheduled || (this._pendingOldValue = e, this._isNotificationScheduled = !0), this._sync && !H.isBatching ? this._flushNotifications() : H.schedule(this._notifyTask);
558
+ }
559
+ _flushNotifications() {
560
+ if (!this._isNotificationScheduled) return;
561
+ const e = this._pendingOldValue, s = this._value;
562
+ this._pendingOldValue = void 0, this._isNotificationScheduled = !1, this._notifySubscribers(s, e);
563
+ }
564
+ /**
565
+ * Returns the current value without registering as a dependency in the tracking context.
566
+ */
567
+ peek() {
568
+ return this._value;
569
+ }
570
+ /**
571
+ * Disposes of the atom, clearing all subscribers and resetting the value.
572
+ */
573
+ dispose() {
574
+ this._functionSubscribersStore.clear(), this._objectSubscribersStore.clear(), this._value = void 0;
575
+ }
576
+ }
577
+ function Be(t, e = {}) {
578
+ return new je(t, e.sync ?? !1);
579
+ }
580
+ class ae {
581
+ constructor() {
582
+ this.pool = [], this.maxPoolSize = 50, this.maxReusableCapacity = 256, this.stats = x ? {
583
+ acquired: 0,
584
+ released: 0,
585
+ rejected: { frozen: 0, tooLarge: 0, poolFull: 0 }
586
+ } : null;
587
+ }
588
+ /** Acquires an array from the pool or creates a new one if the pool is empty. */
589
+ acquire() {
590
+ return x && this.stats && this.stats.acquired++, this.pool.pop() ?? [];
591
+ }
592
+ /**
593
+ * Releases an array back to the pool.
594
+ * Clears the array before storing it.
595
+ * @param arr - The array to release.
596
+ * @param emptyConst - Optional reference to a constant empty array to skip.
597
+ */
598
+ release(e, s) {
599
+ if (!(s && e === s)) {
600
+ if (Object.isFrozen(e)) {
601
+ x && this.stats && this.stats.rejected.frozen++;
602
+ return;
603
+ }
604
+ if (e.length > this.maxReusableCapacity) {
605
+ x && this.stats && this.stats.rejected.tooLarge++;
606
+ return;
607
+ }
608
+ if (this.pool.length >= this.maxPoolSize) {
609
+ x && this.stats && this.stats.rejected.poolFull++;
610
+ return;
611
+ }
612
+ e.length = 0, this.pool.push(e), x && this.stats && this.stats.released++;
613
+ }
614
+ }
615
+ /** Returns current stats for the pool (dev mode only). */
616
+ getStats() {
617
+ if (!x || !this.stats) return null;
618
+ const { acquired: e, released: s, rejected: n } = this.stats, i = n.frozen + n.tooLarge + n.poolFull;
619
+ return {
620
+ acquired: e,
621
+ released: s,
622
+ rejected: n,
623
+ leaked: e - s - i,
624
+ poolSize: this.pool.length
625
+ };
626
+ }
627
+ /** Resets the pool and its stats. */
628
+ reset() {
629
+ this.pool.length = 0, x && this.stats && (this.stats.acquired = 0, this.stats.released = 0, this.stats.rejected = { frozen: 0, tooLarge: 0, poolFull: 0 });
630
+ }
631
+ }
632
+ const g = Object.freeze([]), v = Object.freeze([]), m = Object.freeze([]), F = new ae(), L = new ae(), N = new ae();
633
+ function qe(t, e, s, n) {
634
+ if (e !== g && s !== v)
635
+ for (let r = 0; r < e.length; r++) {
636
+ const o = e[r];
637
+ o && (o._tempUnsub = s[r]);
638
+ }
639
+ const i = L.acquire();
640
+ i.length = t.length;
641
+ for (let r = 0; r < t.length; r++) {
642
+ const o = t[r];
643
+ o && (o._tempUnsub ? (i[r] = o._tempUnsub, o._tempUnsub = void 0) : (U.checkCircular(o, n), i[r] = o.subscribe(n)));
644
+ }
645
+ if (e !== g)
646
+ for (let r = 0; r < e.length; r++) {
647
+ const o = e[r];
648
+ o != null && o._tempUnsub && (o._tempUnsub(), o._tempUnsub = void 0);
649
+ }
650
+ return s !== v && L.release(s), i;
651
+ }
652
+ function z(t, e, s) {
653
+ if (t instanceof TypeError)
654
+ return new e(`Type error (${s}): ${t.message}`, t);
655
+ if (t instanceof ReferenceError)
656
+ return new e(`Reference error (${s}): ${t.message}`, t);
657
+ if (t instanceof O)
658
+ return t;
659
+ const n = t instanceof Error ? t.message : String(t), i = t instanceof Error ? t : null;
660
+ return new e(`Unexpected error (${s}): ${n}`, i);
661
+ }
662
+ class Re extends De {
663
+ constructor(e, s = {}) {
664
+ if (typeof e != "function")
665
+ throw new q(b.COMPUTED_MUST_BE_FUNCTION);
666
+ if (super(), this._value = void 0, this.flags = _.DIRTY | _.IDLE, this._error = null, this._promiseId = 0, this._equal = s.equal ?? Object.is, this._fn = e, this._defaultValue = "defaultValue" in s ? s.defaultValue : de, this._hasDefaultValue = this._defaultValue !== de, this._onError = s.onError ?? null, this.MAX_PROMISE_ID = Number.MAX_SAFE_INTEGER - 1, this._functionSubscribersStore = new ie(), this._objectSubscribersStore = new ie(), this._dependencies = g, this._dependencyVersions = m, this._unsubscribes = v, this._notifyJob = () => {
667
+ this._functionSubscribersStore.forEachSafe(
668
+ (n) => n(),
669
+ (n) => console.error(n)
670
+ ), this._objectSubscribersStore.forEachSafe(
671
+ (n) => n.execute(),
672
+ (n) => console.error(n)
673
+ );
674
+ }, this._trackable = Object.assign(() => this._markDirty(), {
675
+ addDependency: (n) => {
676
+ }
677
+ }), U.attachDebugInfo(this, "computed", this.id), U.enabled) {
678
+ const n = this;
679
+ n.subscriberCount = () => this._functionSubscribersStore.size + this._objectSubscribersStore.size, n.isDirty = () => this._isDirty(), n.dependencies = this._dependencies, n.stateFlags = this._getFlagsAsString();
680
+ }
681
+ if (s.lazy === !1)
682
+ try {
683
+ this._recompute();
684
+ } catch {
685
+ }
686
+ }
687
+ get _functionSubscribers() {
688
+ return this._functionSubscribersStore;
689
+ }
690
+ get _objectSubscribers() {
691
+ return this._objectSubscribersStore;
692
+ }
693
+ get value() {
694
+ const e = this._computeValue();
695
+ return this._registerTracking(), e;
696
+ }
697
+ peek() {
698
+ return this._value;
699
+ }
700
+ get state() {
701
+ return this._getAsyncState();
702
+ }
703
+ get hasError() {
704
+ return this._isRejected();
705
+ }
706
+ get lastError() {
707
+ return this._error;
708
+ }
709
+ get isPending() {
710
+ return this._isPending();
711
+ }
712
+ get isResolved() {
713
+ return this._isResolved();
714
+ }
715
+ invalidate() {
716
+ this._markDirty(), this._dependencyVersions !== m && (N.release(this._dependencyVersions), this._dependencyVersions = m);
717
+ }
718
+ dispose() {
719
+ if (this._unsubscribes !== v) {
720
+ for (let e = 0; e < this._unsubscribes.length; e++) {
721
+ const s = this._unsubscribes[e];
722
+ s && s();
723
+ }
724
+ L.release(this._unsubscribes), this._unsubscribes = v;
725
+ }
726
+ this._dependencies !== g && (F.release(this._dependencies), this._dependencies = g), this._dependencyVersions !== m && (N.release(this._dependencyVersions), this._dependencyVersions = m), this._functionSubscribersStore.clear(), this._objectSubscribersStore.clear(), this.flags = _.DIRTY | _.IDLE, this._error = null, this._value = void 0, this._promiseId = (this._promiseId + 1) % this.MAX_PROMISE_ID;
727
+ }
728
+ // State flag operations
729
+ _isDirty() {
730
+ return (this.flags & _.DIRTY) !== 0;
731
+ }
732
+ _setDirty() {
733
+ this.flags |= _.DIRTY;
734
+ }
735
+ _clearDirty() {
736
+ this.flags &= -2;
737
+ }
738
+ _isIdle() {
739
+ return (this.flags & _.IDLE) !== 0;
740
+ }
741
+ _setIdle() {
742
+ this.flags |= _.IDLE, this.flags &= -29;
743
+ }
744
+ _isPending() {
745
+ return (this.flags & _.PENDING) !== 0;
746
+ }
747
+ _setPending() {
748
+ this.flags |= _.PENDING, this.flags &= -27;
749
+ }
750
+ _isResolved() {
751
+ return (this.flags & _.RESOLVED) !== 0;
752
+ }
753
+ _setResolved() {
754
+ this.flags |= _.RESOLVED, this.flags &= -87;
755
+ }
756
+ _isRejected() {
757
+ return (this.flags & _.REJECTED) !== 0;
758
+ }
759
+ _setRejected() {
760
+ this.flags |= _.REJECTED | _.HAS_ERROR, this.flags &= -15;
761
+ }
762
+ _isRecomputing() {
763
+ return (this.flags & _.RECOMPUTING) !== 0;
764
+ }
765
+ _setRecomputing(e) {
766
+ const s = _.RECOMPUTING;
767
+ this.flags = this.flags & ~s | -Number(e) & s;
768
+ }
769
+ _getAsyncState() {
770
+ return this._isResolved() ? K.RESOLVED : this._isPending() ? K.PENDING : this._isRejected() ? K.REJECTED : K.IDLE;
771
+ }
772
+ _getFlagsAsString() {
773
+ const e = [];
774
+ return this._isDirty() && e.push("DIRTY"), this._isIdle() && e.push("IDLE"), this._isPending() && e.push("PENDING"), this._isResolved() && e.push("RESOLVED"), this._isRejected() && e.push("REJECTED"), this._isRecomputing() && e.push("RECOMPUTING"), e.join(" | ");
775
+ }
776
+ _computeValue() {
777
+ return this._isRecomputing() ? this._value : ((this._isDirty() || this._isIdle()) && this._recompute(), this._isPending() ? this._handlePending() : this._isRejected() ? this._handleRejected() : this._value);
778
+ }
779
+ _recompute() {
780
+ if (this._isRecomputing()) return;
781
+ this._setRecomputing(!0);
782
+ const e = this._prepareComputationContext();
783
+ let s = !1;
784
+ try {
785
+ const n = V.run(this._trackable, this._fn);
786
+ Ie(n) ? (this._commitDependencies(e), s = !0, this._handleAsyncComputation(n)) : (this._commitDependencies(e), s = !0, this._handleSyncResult(n));
787
+ } catch (n) {
788
+ this._commitDependencies(e), s = !0, this._handleComputationError(n);
789
+ } finally {
790
+ this._cleanupContext(e, s), this._setRecomputing(!1);
791
+ }
792
+ }
793
+ _prepareComputationContext() {
794
+ const e = this._dependencies, s = this._dependencyVersions, n = F.acquire(), i = N.acquire(), r = Ce(), o = { depCount: 0 }, a = (l) => {
795
+ l._lastSeenEpoch !== r && (l._lastSeenEpoch = r, o.depCount < n.length ? (n[o.depCount] = l, i[o.depCount] = l.version) : (n.push(l), i.push(l.version)), o.depCount++);
796
+ }, f = this._trackable.addDependency;
797
+ return this._trackable.addDependency = a, { prevDeps: e, prevVersions: s, nextDeps: n, nextVersions: i, originalAdd: f, state: o };
798
+ }
799
+ _commitDependencies(e) {
800
+ const { nextDeps: s, nextVersions: n, state: i, prevDeps: r } = e;
801
+ s.length = i.depCount, n.length = i.depCount, this._unsubscribes = qe(s, r, this._unsubscribes, this), this._dependencies = s, this._dependencyVersions = n;
802
+ }
803
+ _cleanupContext(e, s) {
804
+ this._trackable.addDependency = e.originalAdd, s ? (e.prevDeps !== g && F.release(e.prevDeps), e.prevVersions !== m && N.release(e.prevVersions)) : (F.release(e.nextDeps), N.release(e.nextVersions));
805
+ }
806
+ _handleSyncResult(e) {
807
+ (!this._isResolved() || !this._equal(this._value, e)) && (this.version = this.version + 1 & X), this._value = e, this._clearDirty(), this._setResolved(), this._error = null, this._setRecomputing(!1);
808
+ }
809
+ _handleAsyncComputation(e) {
810
+ this._setPending(), this._clearDirty(), this._promiseId = this._promiseId >= this.MAX_PROMISE_ID ? 1 : this._promiseId + 1;
811
+ const s = this._promiseId;
812
+ e.then((n) => {
813
+ s === this._promiseId && this._handleAsyncResolution(n);
814
+ }).catch((n) => {
815
+ s === this._promiseId && this._handleAsyncRejection(n);
816
+ });
817
+ }
818
+ _handleAsyncResolution(e) {
819
+ (!this._isResolved() || !this._equal(this._value, e)) && (this.version = this.version + 1 & X), this._value = e, this._clearDirty(), this._setResolved(), this._error = null, this._setRecomputing(!1);
820
+ }
821
+ _handleAsyncRejection(e) {
822
+ const s = z(e, q, b.COMPUTED_ASYNC_COMPUTATION_FAILED);
823
+ if (this._error = s, this._setRejected(), this._clearDirty(), this._setRecomputing(!1), this._onError)
824
+ try {
825
+ this._onError(s);
826
+ } catch (n) {
827
+ console.error(b.CALLBACK_ERROR_IN_ERROR_HANDLER, n);
828
+ }
829
+ this._notifySubscribers(void 0, void 0);
830
+ }
831
+ _handleComputationError(e) {
832
+ const s = z(e, q, b.COMPUTED_COMPUTATION_FAILED);
833
+ if (this._error = s, this._setRejected(), this._clearDirty(), this._setRecomputing(!1), this._onError)
834
+ try {
835
+ this._onError(s);
836
+ } catch (n) {
837
+ console.error(b.CALLBACK_ERROR_IN_ERROR_HANDLER, n);
838
+ }
839
+ throw s;
840
+ }
841
+ _handlePending() {
842
+ if (this._hasDefaultValue)
843
+ return this._defaultValue;
844
+ throw new q(b.COMPUTED_ASYNC_PENDING_NO_DEFAULT);
845
+ }
846
+ _handleRejected() {
847
+ var e;
848
+ if ((e = this._error) != null && e.recoverable && this._hasDefaultValue)
849
+ return this._defaultValue;
850
+ throw this._error;
851
+ }
852
+ /** Subscriber interface - marks dirty on dependency change */
853
+ execute() {
854
+ this._markDirty();
855
+ }
856
+ _markDirty() {
857
+ this._isRecomputing() || this._isDirty() || (this._setDirty(), this._notifyJob());
858
+ }
859
+ _registerTracking() {
860
+ const e = V.getCurrent();
861
+ if (e) {
862
+ if (ve(e)) {
863
+ e.addDependency(this);
864
+ return;
865
+ }
866
+ if (Ne(e)) {
867
+ this._functionSubscribersStore.add(e);
868
+ return;
869
+ }
870
+ Ue(e) && this._objectSubscribersStore.add(e);
871
+ }
872
+ }
873
+ }
874
+ Object.freeze(Re.prototype);
875
+ function ze(t, e = {}) {
876
+ return new Re(t, e);
877
+ }
878
+ class Xe extends ye {
879
+ /**
880
+ * Creates a new EffectImpl instance.
881
+ * @param fn - The effect function to run.
882
+ * @param options - Configuration options for the effect.
883
+ */
884
+ constructor(e, s = {}) {
885
+ super(), this.run = () => {
886
+ if (this.isDisposed)
887
+ throw new w(b.EFFECT_MUST_BE_FUNCTION);
888
+ this._dependencyVersions !== m && (N.release(this._dependencyVersions), this._dependencyVersions = m), this.execute();
889
+ }, this.dispose = () => {
890
+ if (!this.isDisposed) {
891
+ if (this._setDisposed(), this._safeCleanup(), this._unsubscribes !== v) {
892
+ for (let n = 0; n < this._unsubscribes.length; n++) {
893
+ const i = this._unsubscribes[n];
894
+ i && i();
895
+ }
896
+ L.release(this._unsubscribes), this._unsubscribes = v;
897
+ }
898
+ this._dependencies !== g && (F.release(this._dependencies), this._dependencies = g), this._dependencyVersions !== m && (N.release(this._dependencyVersions), this._dependencyVersions = m);
899
+ }
900
+ }, this.addDependency = (n) => {
901
+ if (this.isExecuting && this._nextDeps && this._nextUnsubs && this._nextVersions) {
902
+ const i = this._currentEpoch;
903
+ if (n._lastSeenEpoch === i) return;
904
+ n._lastSeenEpoch = i, this._nextDeps.push(n), this._nextVersions.push(n.version), n._tempUnsub ? (this._nextUnsubs.push(n._tempUnsub), n._tempUnsub = void 0) : this._subscribeTo(n);
905
+ }
906
+ }, this.execute = () => {
907
+ if (this.isDisposed || this.isExecuting || !this._shouldExecute()) return;
908
+ this._checkInfiniteLoop(), this._setExecuting(!0), this._safeCleanup();
909
+ const n = this._prepareEffectContext();
910
+ let i = !1;
911
+ try {
912
+ const r = V.run(this, this._fn);
913
+ this._commitEffect(n), i = !0, this._checkLoopWarnings(), Ie(r) ? r.then((o) => {
914
+ !this.isDisposed && typeof o == "function" && (this._cleanup = o);
915
+ }).catch((o) => {
916
+ console.error(z(o, w, b.EFFECT_EXECUTION_FAILED));
917
+ }) : this._cleanup = typeof r == "function" ? r : null;
918
+ } catch (r) {
919
+ i = !0, console.error(z(r, w, b.EFFECT_EXECUTION_FAILED)), this._cleanup = null;
920
+ } finally {
921
+ this._cleanupEffect(n, i), this._setExecuting(!1);
922
+ }
923
+ }, this._currentEpoch = -1, this._lastFlushEpoch = -1, this._executionsInEpoch = 0, this._fn = e, this._sync = s.sync ?? !1, this._maxExecutions = s.maxExecutionsPerSecond ?? P.MAX_EXECUTIONS_PER_SECOND, this._maxExecutionsPerFlush = s.maxExecutionsPerFlush ?? P.MAX_EXECUTIONS_PER_EFFECT, this._trackModifications = s.trackModifications ?? !1, this._cleanup = null, this._dependencies = g, this._dependencyVersions = m, this._unsubscribes = v, this._nextDeps = null, this._nextVersions = null, this._nextUnsubs = null, this._history = x ? [] : null, this._executionCount = 0, U.attachDebugInfo(this, "effect", this.id);
924
+ }
925
+ /**
926
+ * Prepares the execution context by acquiring pools and setting up epoch.
927
+ * @returns The prepared EffectContext.
928
+ */
929
+ _prepareEffectContext() {
930
+ const e = this._dependencies, s = this._dependencyVersions, n = this._unsubscribes, i = F.acquire(), r = N.acquire(), o = L.acquire(), a = Ce();
931
+ if (e !== g && n !== v)
932
+ for (let f = 0; f < e.length; f++) {
933
+ const l = e[f];
934
+ l && (l._tempUnsub = n[f]);
935
+ }
936
+ return this._nextDeps = i, this._nextVersions = r, this._nextUnsubs = o, this._currentEpoch = a, { prevDeps: e, prevVersions: s, prevUnsubs: n, nextDeps: i, nextVersions: r, nextUnsubs: o };
937
+ }
938
+ /**
939
+ * Commits the tracked dependencies as the current active dependencies.
940
+ * @param ctx - The current effect context.
941
+ */
942
+ _commitEffect(e) {
943
+ const s = e.nextDeps.length;
944
+ e.nextDeps.length = s, e.nextVersions.length = s, this._dependencies = e.nextDeps, this._dependencyVersions = e.nextVersions, this._unsubscribes = e.nextUnsubs;
945
+ }
946
+ /**
947
+ * Cleans up the effect execution context, releasing resources back to pools.
948
+ * @param ctx - The effect context to clean up.
949
+ * @param committed - Whether the changes were committed to the effect.
950
+ */
951
+ _cleanupEffect(e, s) {
952
+ var n, i;
953
+ if (this._nextDeps = null, this._nextVersions = null, this._nextUnsubs = null, s) {
954
+ if (e.prevDeps !== g) {
955
+ for (let r = 0; r < e.prevDeps.length; r++) {
956
+ const o = e.prevDeps[r];
957
+ o != null && o._tempUnsub && (o._tempUnsub(), o._tempUnsub = void 0);
958
+ }
959
+ F.release(e.prevDeps);
960
+ }
961
+ e.prevUnsubs !== v && L.release(e.prevUnsubs), e.prevVersions !== m && N.release(e.prevVersions);
962
+ } else {
963
+ F.release(e.nextDeps), N.release(e.nextVersions);
964
+ for (let r = 0; r < e.nextUnsubs.length; r++)
965
+ (i = (n = e.nextUnsubs)[r]) == null || i.call(n);
966
+ if (L.release(e.nextUnsubs), e.prevDeps !== g)
967
+ for (let r = 0; r < e.prevDeps.length; r++) {
968
+ const o = e.prevDeps[r];
969
+ o && (o._tempUnsub = void 0);
970
+ }
971
+ }
972
+ }
973
+ /**
974
+ * Subscribes to a dependency's changes.
975
+ * @param dep - The dependency to subscribe to.
976
+ */
977
+ _subscribeTo(e) {
978
+ try {
979
+ const s = e.subscribe(() => {
980
+ this._trackModifications && this.isExecuting && (e._modifiedAtEpoch = this._currentEpoch), this._sync ? this.execute() : H.schedule(this.execute);
981
+ });
982
+ this._nextUnsubs && this._nextUnsubs.push(s);
983
+ } catch (s) {
984
+ console.error(z(s, w, b.EFFECT_EXECUTION_FAILED)), this._nextUnsubs && this._nextUnsubs.push(() => {
985
+ });
986
+ }
987
+ }
988
+ /**
989
+ * Whether the effect has been disposed.
990
+ */
991
+ get isDisposed() {
992
+ return (this.flags & Z.DISPOSED) !== 0;
993
+ }
994
+ /**
995
+ * Total number of times this effect has executed.
996
+ */
997
+ get executionCount() {
998
+ return this._executionCount;
999
+ }
1000
+ /**
1001
+ * Whether the effect is currently executing.
1002
+ */
1003
+ get isExecuting() {
1004
+ return (this.flags & Z.EXECUTING) !== 0;
1005
+ }
1006
+ _setDisposed() {
1007
+ this.flags |= Z.DISPOSED;
1008
+ }
1009
+ _setExecuting(e) {
1010
+ const s = Z.EXECUTING;
1011
+ this.flags = this.flags & ~s | -Number(e) & s;
1012
+ }
1013
+ /**
1014
+ * Executes the cleanup function if it exists.
1015
+ */
1016
+ _safeCleanup() {
1017
+ if (this._cleanup) {
1018
+ try {
1019
+ this._cleanup();
1020
+ } catch (e) {
1021
+ console.error(z(e, w, b.EFFECT_CLEANUP_FAILED));
1022
+ }
1023
+ this._cleanup = null;
1024
+ }
1025
+ }
1026
+ /**
1027
+ * Checks for infinite loops by tracking execution counts within a flush and time period.
1028
+ * @throws {EffectError} If an infinite loop is detected.
1029
+ */
1030
+ _checkInfiniteLoop() {
1031
+ if (this._lastFlushEpoch !== se && (this._lastFlushEpoch = se, this._executionsInEpoch = 0), this._executionsInEpoch++, this._executionsInEpoch > this._maxExecutionsPerFlush && this._throwInfiniteLoopError("per-effect"), Le() > P.MAX_EXECUTIONS_PER_FLUSH && this._throwInfiniteLoopError("global"), this._executionCount++, this._history) {
1032
+ const e = Date.now();
1033
+ this._history.push(e), this._history.length > P.MAX_EXECUTIONS_PER_SECOND + 10 && this._history.shift(), this._checkTimestampLoop(e);
1034
+ }
1035
+ }
1036
+ _checkTimestampLoop(e) {
1037
+ const s = this._history;
1038
+ if (!s || this._maxExecutions <= 0) return;
1039
+ const n = e - we.ONE_SECOND_MS;
1040
+ let i = 0;
1041
+ for (let r = s.length - 1; r >= 0 && !(s[r] < n); r--)
1042
+ i++;
1043
+ if (i > this._maxExecutions) {
1044
+ const r = new w(
1045
+ `Effect executed ${i} times within 1 second. Infinite loop suspected`
1046
+ );
1047
+ if (this.dispose(), console.error(r), x)
1048
+ throw r;
1049
+ }
1050
+ }
1051
+ _throwInfiniteLoopError(e) {
1052
+ const s = new w(
1053
+ `Infinite loop detected (${e}): effect executed ${this._executionsInEpoch} times in current flush. Total executions in flush: ${he}`
1054
+ );
1055
+ throw this.dispose(), console.error(s), s;
1056
+ }
1057
+ /**
1058
+ * Determines if the effect should execute based on dependency versions.
1059
+ * @returns true if any dependency has changed or if it's the first run.
1060
+ */
1061
+ _shouldExecute() {
1062
+ if (this._dependencies === g || this._dependencyVersions === m)
1063
+ return !0;
1064
+ for (let e = 0; e < this._dependencies.length; e++) {
1065
+ const s = this._dependencies[e];
1066
+ if (s) {
1067
+ if ("value" in s)
1068
+ try {
1069
+ xe(() => s.value);
1070
+ } catch {
1071
+ return !0;
1072
+ }
1073
+ if (s.version !== this._dependencyVersions[e])
1074
+ return !0;
1075
+ }
1076
+ }
1077
+ return !1;
1078
+ }
1079
+ /**
1080
+ * Checks for potential infinite loops where an effect modifies its own dependencies.
1081
+ * Only active if trackModifications is enabled and debug is on.
1082
+ */
1083
+ _checkLoopWarnings() {
1084
+ if (this._trackModifications && U.enabled) {
1085
+ const e = this._dependencies;
1086
+ for (let s = 0; s < e.length; s++) {
1087
+ const n = e[s];
1088
+ n && n._modifiedAtEpoch === this._currentEpoch && U.warn(
1089
+ !0,
1090
+ `Effect is reading a dependency (${U.getDebugName(n) || "unknown"}) that it just modified. Infinite loop may occur`
1091
+ );
1092
+ }
1093
+ }
1094
+ }
1095
+ }
1096
+ function S(t, e = {}) {
1097
+ if (typeof t != "function")
1098
+ throw new w(b.EFFECT_MUST_BE_FUNCTION);
1099
+ const s = new Xe(t, e);
1100
+ return s.execute(), s;
1101
+ }
1102
+ function Ge() {
1103
+ if (typeof window < "u") {
1104
+ const t = window.__ATOM_DEBUG__;
1105
+ if (typeof t == "boolean")
1106
+ return t;
1107
+ }
1108
+ try {
1109
+ if (typeof process < "u" && process.env && process.env.NODE_ENV === "development")
1110
+ return !0;
1111
+ } catch {
1112
+ }
1113
+ return !1;
1114
+ }
1115
+ let M = Ge();
1116
+ const u = {
1117
+ get enabled() {
1118
+ return M;
1119
+ },
1120
+ set enabled(t) {
1121
+ M = t;
1122
+ },
1123
+ log(t, ...e) {
1124
+ M && console.log(`[atom-effect-jquery] ${t}:`, ...e);
1125
+ },
1126
+ atomChanged(t, e, s) {
1127
+ M && console.log(
1128
+ `[atom-effect-jquery] Atom "${t || "anonymous"}" changed:`,
1129
+ e,
1130
+ "→",
1131
+ s
1132
+ );
1133
+ },
1134
+ /**
1135
+ * Logs DOM updates and triggers visual highlight.
1136
+ */
1137
+ domUpdated(t, e, s) {
1138
+ if (!M) return;
1139
+ const n = Qe(t);
1140
+ console.log(
1141
+ `[atom-effect-jquery] DOM updated: ${n}.${e} =`,
1142
+ s
1143
+ ), He(t);
1144
+ },
1145
+ cleanup(t) {
1146
+ M && console.log(`[atom-effect-jquery] Cleanup: ${t}`);
1147
+ },
1148
+ warn(...t) {
1149
+ M && console.warn("[atom-effect-jquery]", ...t);
1150
+ }
1151
+ };
1152
+ function Qe(t) {
1153
+ const e = t[0];
1154
+ if (!e) return "unknown";
1155
+ if (e.id) return `#${e.id}`;
1156
+ if (e.className) {
1157
+ const s = String(e.className).split(" ").filter(Boolean).join(".");
1158
+ return `${e.tagName.toLowerCase()}.${s}`;
1159
+ }
1160
+ return e.tagName.toLowerCase();
1161
+ }
1162
+ function He(t) {
1163
+ const e = t.css("outline"), s = t.css("transition");
1164
+ t.css({
1165
+ outline: "2px solid #ff4444",
1166
+ "outline-offset": "1px",
1167
+ transition: "outline 0.1s ease-out"
1168
+ }), setTimeout(() => {
1169
+ t.css({
1170
+ outline: e || "",
1171
+ "outline-offset": "",
1172
+ transition: s || ""
1173
+ });
1174
+ }, 200);
1175
+ }
1176
+ const Ye = /* @__PURE__ */ new WeakMap();
1177
+ function Te(t, e = {}) {
1178
+ const s = Be(t, e);
1179
+ return e.name && Ye.set(s, { name: e.name }), s;
1180
+ }
1181
+ Object.defineProperty(Te, "debug", {
1182
+ get() {
1183
+ return u.enabled;
1184
+ },
1185
+ set(t) {
1186
+ u.enabled = t;
1187
+ }
1188
+ });
1189
+ function Je() {
1190
+ return new Promise((t) => setTimeout(t, 0));
1191
+ }
1192
+ c.extend({
1193
+ atom: Te,
1194
+ computed: ze,
1195
+ effect: S,
1196
+ batch: A,
1197
+ untracked: xe,
1198
+ isAtom: ue,
1199
+ isComputed: Ee,
1200
+ isReactive: (t) => ue(t) || Ee(t),
1201
+ nextTick: Je
1202
+ });
1203
+ function d(t) {
1204
+ return t !== null && typeof t == "object" && "value" in t && "subscribe" in t;
1205
+ }
1206
+ function p(t) {
1207
+ return d(t) ? t.value : t;
1208
+ }
1209
+ function le(t) {
1210
+ if (t.id) return `#${t.id}`;
1211
+ if (t.className) {
1212
+ const e = String(t.className).split(/\s+/).filter(Boolean).join(".");
1213
+ return e ? `${t.tagName.toLowerCase()}.${e}` : t.tagName.toLowerCase();
1214
+ }
1215
+ return t.tagName.toLowerCase();
1216
+ }
1217
+ class We {
1218
+ constructor() {
1219
+ // DOM Element -> Effect Array (for disposal)
1220
+ W(this, "effects", /* @__PURE__ */ new WeakMap());
1221
+ // DOM Element -> Custom Cleanup Function Array
1222
+ W(this, "cleanups", /* @__PURE__ */ new WeakMap());
1223
+ // Track bound elements (Performance optimization)
1224
+ W(this, "boundElements", /* @__PURE__ */ new WeakSet());
1225
+ }
1226
+ /**
1227
+ * Registers an Effect to be disposed later.
1228
+ */
1229
+ trackEffect(e, s) {
1230
+ const n = this.effects.get(e) || [];
1231
+ n.push(s), this.effects.set(e, n), this.boundElements.add(e);
1232
+ }
1233
+ /**
1234
+ * Registers a custom cleanup function (e.g., event listener removal).
1235
+ */
1236
+ trackCleanup(e, s) {
1237
+ const n = this.cleanups.get(e) || [];
1238
+ n.push(s), this.cleanups.set(e, n), this.boundElements.add(e);
1239
+ }
1240
+ /**
1241
+ * Checks if an element has bindings (Fast check).
1242
+ */
1243
+ hasBind(e) {
1244
+ return this.boundElements.has(e);
1245
+ }
1246
+ /**
1247
+ * Cleans up a single element.
1248
+ * - Disposes all Effects (severs connection with Atom).
1249
+ * - Executes all custom cleanups.
1250
+ */
1251
+ cleanup(e) {
1252
+ if (!this.boundElements.has(e)) return;
1253
+ u.cleanup(le(e));
1254
+ const s = this.effects.get(e);
1255
+ s && (this.effects.delete(e), s.forEach((i) => {
1256
+ try {
1257
+ i.dispose();
1258
+ } catch (r) {
1259
+ u.warn("Effect dispose error:", r);
1260
+ }
1261
+ }));
1262
+ const n = this.cleanups.get(e);
1263
+ n && (this.cleanups.delete(e), n.forEach((i) => {
1264
+ try {
1265
+ i();
1266
+ } catch (r) {
1267
+ u.warn("Cleanup error:", r);
1268
+ }
1269
+ })), this.boundElements.delete(e);
1270
+ }
1271
+ /**
1272
+ * Cleans up the element and all its descendants (Recursive).
1273
+ * - Essential for deep removal (empty(), remove(), etc.).
1274
+ */
1275
+ cleanupTree(e) {
1276
+ e.querySelectorAll("*").forEach((n) => {
1277
+ this.boundElements.has(n) && this.cleanup(n);
1278
+ }), this.cleanup(e);
1279
+ }
1280
+ }
1281
+ const h = new We();
1282
+ let $ = null;
1283
+ function Ke(t = document.body) {
1284
+ $ || ($ = new MutationObserver((e) => {
1285
+ for (const s of e)
1286
+ s.removedNodes.forEach((n) => {
1287
+ n instanceof Element && h.cleanupTree(n);
1288
+ });
1289
+ }), $.observe(t, { childList: !0, subtree: !0 }));
1290
+ }
1291
+ function st() {
1292
+ $ == null || $.disconnect(), $ = null;
1293
+ }
1294
+ c.fn.atomText = function(t, e) {
1295
+ return this.each(function() {
1296
+ const s = c(this);
1297
+ if (d(t)) {
1298
+ const n = S(() => {
1299
+ const i = p(t), r = e ? e(i) : String(i ?? "");
1300
+ s.text(r), u.domUpdated(s, "text", r);
1301
+ });
1302
+ h.trackEffect(this, n);
1303
+ } else {
1304
+ const n = e ? e(t) : String(t ?? "");
1305
+ s.text(n);
1306
+ }
1307
+ });
1308
+ };
1309
+ c.fn.atomHtml = function(t) {
1310
+ return this.each(function() {
1311
+ const e = c(this);
1312
+ if (d(t)) {
1313
+ const s = S(() => {
1314
+ const n = String(p(t) ?? "");
1315
+ e.html(n), u.domUpdated(e, "html", n);
1316
+ });
1317
+ h.trackEffect(this, s);
1318
+ } else
1319
+ e.html(String(t ?? ""));
1320
+ });
1321
+ };
1322
+ c.fn.atomClass = function(t, e) {
1323
+ return this.each(function() {
1324
+ const s = c(this);
1325
+ if (d(e)) {
1326
+ const n = S(() => {
1327
+ const i = !!p(e);
1328
+ s.toggleClass(t, i), u.domUpdated(s, `class.${t}`, i);
1329
+ });
1330
+ h.trackEffect(this, n);
1331
+ } else
1332
+ s.toggleClass(t, !!e);
1333
+ });
1334
+ };
1335
+ c.fn.atomCss = function(t, e, s) {
1336
+ return this.each(function() {
1337
+ const n = c(this);
1338
+ if (d(e)) {
1339
+ const i = S(() => {
1340
+ const r = p(e), o = s ? `${r}${s}` : r;
1341
+ n.css(t, o), u.domUpdated(n, `css.${t}`, o);
1342
+ });
1343
+ h.trackEffect(this, i);
1344
+ } else
1345
+ n.css(t, s ? `${e}${s}` : e);
1346
+ });
1347
+ };
1348
+ c.fn.atomAttr = function(t, e) {
1349
+ return this.each(function() {
1350
+ const s = c(this), n = (i) => {
1351
+ i == null || i === !1 ? s.removeAttr(t) : i === !0 ? s.attr(t, t) : s.attr(t, String(i)), u.domUpdated(s, `attr.${t}`, i);
1352
+ };
1353
+ if (d(e)) {
1354
+ const i = S(() => n(p(e)));
1355
+ h.trackEffect(this, i);
1356
+ } else
1357
+ n(e);
1358
+ });
1359
+ };
1360
+ c.fn.atomProp = function(t, e) {
1361
+ return this.each(function() {
1362
+ const s = c(this);
1363
+ if (d(e)) {
1364
+ const n = S(() => {
1365
+ const i = p(e);
1366
+ s.prop(t, i), u.domUpdated(s, `prop.${t}`, i);
1367
+ });
1368
+ h.trackEffect(this, n);
1369
+ } else
1370
+ s.prop(t, e);
1371
+ });
1372
+ };
1373
+ c.fn.atomShow = function(t) {
1374
+ return this.each(function() {
1375
+ const e = c(this);
1376
+ if (d(t)) {
1377
+ const s = S(() => {
1378
+ const n = !!p(t);
1379
+ e.toggle(n), u.domUpdated(e, "show", n);
1380
+ });
1381
+ h.trackEffect(this, s);
1382
+ } else
1383
+ e.toggle(!!t);
1384
+ });
1385
+ };
1386
+ c.fn.atomHide = function(t) {
1387
+ return this.each(function() {
1388
+ const e = c(this);
1389
+ if (d(t)) {
1390
+ const s = S(() => {
1391
+ const n = !p(t);
1392
+ e.toggle(n), u.domUpdated(e, "hide", !n);
1393
+ });
1394
+ h.trackEffect(this, s);
1395
+ } else
1396
+ e.toggle(!t);
1397
+ });
1398
+ };
1399
+ c.fn.atomVal = function(t, e = {}) {
1400
+ const {
1401
+ debounce: s,
1402
+ event: n = "input",
1403
+ parse: i = (o) => o,
1404
+ format: r = (o) => String(o ?? "")
1405
+ } = e;
1406
+ return this.each(function() {
1407
+ const o = c(this);
1408
+ let a = null, f = !1, l = !1, j = !1;
1409
+ const I = () => {
1410
+ l = !0;
1411
+ }, y = () => {
1412
+ l = !1, G();
1413
+ };
1414
+ o.on("compositionstart", I), o.on("compositionend", y);
1415
+ const G = () => {
1416
+ f || j || A(() => {
1417
+ t.value = i(o.val());
1418
+ });
1419
+ }, C = () => {
1420
+ l || j || f || (s ? (a && clearTimeout(a), a = window.setTimeout(G, s)) : G());
1421
+ };
1422
+ o.on(n, C), o.on("change", C);
1423
+ const Y = S(() => {
1424
+ const D = r(t.value);
1425
+ o.val() !== D && (f = !0, j = !0, o.val(D), u.domUpdated(o, "val", D), j = !1, f = !1);
1426
+ });
1427
+ h.trackEffect(this, Y), h.trackCleanup(this, () => {
1428
+ o.off(n, C), o.off("change", C), o.off("compositionstart", I), o.off("compositionend", y), a && clearTimeout(a);
1429
+ });
1430
+ });
1431
+ };
1432
+ c.fn.atomChecked = function(t) {
1433
+ return this.each(function() {
1434
+ const e = c(this);
1435
+ let s = !1;
1436
+ const n = () => {
1437
+ s || A(() => {
1438
+ t.value = e.prop("checked");
1439
+ });
1440
+ };
1441
+ e.on("change", n), h.trackCleanup(this, () => e.off("change", n));
1442
+ const i = S(() => {
1443
+ s = !0, e.prop("checked", t.value), u.domUpdated(e, "checked", t.value), s = !1;
1444
+ });
1445
+ h.trackEffect(this, i);
1446
+ });
1447
+ };
1448
+ c.fn.atomOn = function(t, e) {
1449
+ return this.each(function() {
1450
+ const s = c(this), n = function(i) {
1451
+ A(() => e.call(this, i));
1452
+ };
1453
+ s.on(t, n), h.trackCleanup(this, () => s.off(t, n));
1454
+ });
1455
+ };
1456
+ c.fn.atomUnbind = function() {
1457
+ return this.each(function() {
1458
+ h.cleanupTree(this);
1459
+ });
1460
+ };
1461
+ c.fn.atomBind = function(t) {
1462
+ return this.each(function() {
1463
+ const e = c(this), s = [];
1464
+ if (t.text !== void 0 && (d(t.text) ? s.push(() => {
1465
+ const n = String(p(t.text) ?? "");
1466
+ e.text(n), u.domUpdated(e, "text", n);
1467
+ }) : e.text(String(t.text ?? ""))), t.html !== void 0 && (d(t.html) ? s.push(() => {
1468
+ const n = String(p(t.html) ?? "");
1469
+ e.html(n), u.domUpdated(e, "html", n);
1470
+ }) : e.html(String(t.html ?? ""))), t.class)
1471
+ for (const [n, i] of Object.entries(t.class))
1472
+ d(i) ? s.push(() => {
1473
+ const r = !!p(i);
1474
+ e.toggleClass(n, r), u.domUpdated(e, `class.${n}`, r);
1475
+ }) : e.toggleClass(n, !!i);
1476
+ if (t.css)
1477
+ for (const [n, i] of Object.entries(t.css))
1478
+ if (Array.isArray(i)) {
1479
+ const [r, o] = i;
1480
+ d(r) ? s.push(() => {
1481
+ const a = `${p(r)}${o}`;
1482
+ e.css(n, a), u.domUpdated(e, `css.${n}`, a);
1483
+ }) : e.css(n, `${r}${o}`);
1484
+ } else d(i) ? s.push(() => {
1485
+ const r = p(i);
1486
+ e.css(n, r), u.domUpdated(e, `css.${n}`, r);
1487
+ }) : e.css(n, i);
1488
+ if (t.attr)
1489
+ for (const [n, i] of Object.entries(t.attr)) {
1490
+ const r = (o) => {
1491
+ o == null || o === !1 ? e.removeAttr(n) : o === !0 ? e.attr(n, n) : e.attr(n, String(o)), u.domUpdated(e, `attr.${n}`, o);
1492
+ };
1493
+ d(i) ? s.push(() => r(p(i))) : r(i);
1494
+ }
1495
+ if (t.prop)
1496
+ for (const [n, i] of Object.entries(t.prop))
1497
+ d(i) ? s.push(() => {
1498
+ const r = p(i);
1499
+ e.prop(n, r), u.domUpdated(e, `prop.${n}`, r);
1500
+ }) : e.prop(n, i);
1501
+ if (t.show !== void 0 && (d(t.show) ? s.push(() => {
1502
+ const n = !!p(t.show);
1503
+ e.toggle(n), u.domUpdated(e, "show", n);
1504
+ }) : e.toggle(!!t.show)), t.hide !== void 0 && (d(t.hide) ? s.push(() => {
1505
+ const n = !p(t.hide);
1506
+ e.toggle(n), u.domUpdated(e, "hide", !n);
1507
+ }) : e.toggle(!t.hide)), t.val !== void 0) {
1508
+ const n = t.val;
1509
+ let i = !1, r = !1;
1510
+ const o = () => {
1511
+ r = !0;
1512
+ }, a = () => {
1513
+ r = !1, i || A(() => {
1514
+ n.value = e.val();
1515
+ });
1516
+ };
1517
+ e.on("compositionstart", o), e.on("compositionend", a);
1518
+ const f = () => {
1519
+ r || i || A(() => {
1520
+ n.value = e.val();
1521
+ });
1522
+ };
1523
+ e.on("input change", f), h.trackCleanup(this, () => {
1524
+ e.off("input change", f), e.off("compositionstart", o), e.off("compositionend", a);
1525
+ }), s.push(() => {
1526
+ const l = String(n.value ?? "");
1527
+ e.val() !== l && (i = !0, e.val(l), u.domUpdated(e, "val", l), i = !1);
1528
+ });
1529
+ }
1530
+ if (t.checked !== void 0) {
1531
+ const n = t.checked;
1532
+ let i = !1;
1533
+ const r = () => {
1534
+ i || A(() => {
1535
+ n.value = e.prop("checked");
1536
+ });
1537
+ };
1538
+ e.on("change", r), h.trackCleanup(this, () => e.off("change", r)), s.push(() => {
1539
+ i = !0, e.prop("checked", n.value), u.domUpdated(e, "checked", n.value), i = !1;
1540
+ });
1541
+ }
1542
+ if (t.on)
1543
+ for (const [n, i] of Object.entries(t.on)) {
1544
+ const r = function(o) {
1545
+ A(() => i.call(this, o));
1546
+ };
1547
+ e.on(n, r), h.trackCleanup(this, () => e.off(n, r));
1548
+ }
1549
+ s.forEach((n) => {
1550
+ const i = S(n);
1551
+ h.trackEffect(this, i);
1552
+ });
1553
+ });
1554
+ };
1555
+ c.fn.atomList = function(t, e) {
1556
+ return this.each(function() {
1557
+ const s = c(this), n = le(this), { key: i, render: r, bind: o, onAdd: a, onRemove: f, empty: l } = e, j = typeof i == "function" ? i : (C) => C[i], I = /* @__PURE__ */ new Map();
1558
+ let y = null;
1559
+ const G = S(() => {
1560
+ const C = t.value, Y = /* @__PURE__ */ new Set();
1561
+ if (u.log("list", `${n} updating with ${C.length} items`), C.length === 0 && l) {
1562
+ y || (y = c(l), s.append(y));
1563
+ for (const [, E] of I)
1564
+ E.$el.remove(), h.cleanup(E.$el[0]);
1565
+ I.clear();
1566
+ return;
1567
+ } else y && (y.remove(), y = null);
1568
+ let D = null;
1569
+ for (let E = 0; E < C.length; E++) {
1570
+ const R = C[E], k = j(R, E);
1571
+ Y.add(k);
1572
+ const B = I.get(k);
1573
+ if (B) {
1574
+ const J = B.$el[0], T = D ? D[0] : null;
1575
+ (T ? J.previousSibling === T : J === s[0].firstChild) || (D ? D.after(B.$el) : s.prepend(B.$el)), B.item = R, D = B.$el;
1576
+ } else {
1577
+ const J = r(R, E), T = c(J);
1578
+ D ? D.after(T) : s.prepend(T), I.set(k, { $el: T, item: R }), o && o(T, R, E), a && a(T), u.log("list", `${n} added item:`, k), D = T;
1579
+ }
1580
+ }
1581
+ for (const [E, R] of I)
1582
+ if (!Y.has(E)) {
1583
+ const k = () => {
1584
+ R.$el.remove(), h.cleanup(R.$el[0]), I.delete(E), u.log("list", `${n} removed item:`, E);
1585
+ };
1586
+ f ? Promise.resolve(f(R.$el)).then(k) : k();
1587
+ }
1588
+ });
1589
+ h.trackEffect(this, G), h.trackCleanup(this, () => {
1590
+ I.clear(), y == null || y.remove();
1591
+ });
1592
+ });
1593
+ };
1594
+ const te = /* @__PURE__ */ new WeakMap();
1595
+ c.fn.atomMount = function(t, e = {}) {
1596
+ return this.each(function() {
1597
+ const s = c(this), n = le(this), i = te.get(this);
1598
+ i && (u.log("mount", `${n} unmounting existing component`), i()), u.log("mount", `${n} mounting component`);
1599
+ let r;
1600
+ try {
1601
+ r = t(s, e);
1602
+ } catch (f) {
1603
+ console.error("[atom-effect-jquery] Mount error:", f);
1604
+ return;
1605
+ }
1606
+ let o = !1;
1607
+ const a = () => {
1608
+ if (!o) {
1609
+ if (o = !0, u.log("mount", `${n} full cleanup`), typeof r == "function")
1610
+ try {
1611
+ r();
1612
+ } catch {
1613
+ }
1614
+ h.cleanupTree(this), te.delete(this);
1615
+ }
1616
+ };
1617
+ te.set(this, a), h.trackCleanup(this, a);
1618
+ });
1619
+ };
1620
+ c.fn.atomUnmount = function() {
1621
+ return this.each(function() {
1622
+ var t;
1623
+ (t = te.get(this)) == null || t();
1624
+ });
1625
+ };
1626
+ const Q = /* @__PURE__ */ new WeakMap();
1627
+ let ge = !1;
1628
+ function nt() {
1629
+ if (ge) return;
1630
+ ge = !0;
1631
+ const t = c.fn.on, e = c.fn.off;
1632
+ c.fn.on = function(...s) {
1633
+ let n = -1;
1634
+ for (let i = s.length - 1; i >= 0; i--)
1635
+ if (typeof s[i] == "function") {
1636
+ n = i;
1637
+ break;
1638
+ }
1639
+ if (n !== -1) {
1640
+ const i = s[n];
1641
+ let r;
1642
+ Q.has(i) ? r = Q.get(i) : (r = function(...o) {
1643
+ let a;
1644
+ return A(() => {
1645
+ a = i.apply(this, o);
1646
+ }), a;
1647
+ }, Q.set(i, r)), s[n] = r;
1648
+ }
1649
+ return t.apply(this, s);
1650
+ }, c.fn.off = function(...s) {
1651
+ let n = -1;
1652
+ for (let i = s.length - 1; i >= 0; i--)
1653
+ if (typeof s[i] == "function") {
1654
+ n = i;
1655
+ break;
1656
+ }
1657
+ if (n !== -1) {
1658
+ const i = s[n];
1659
+ Q.has(i) && (s[n] = Q.get(i));
1660
+ }
1661
+ return e.apply(this, s);
1662
+ };
1663
+ }
1664
+ c(() => Ke(document.body));
1665
+ export {
1666
+ Be as atom,
1667
+ A as batch,
1668
+ ze as computed,
1669
+ ot as default,
1670
+ st as disableAutoCleanup,
1671
+ S as effect,
1672
+ Ke as enableAutoCleanup,
1673
+ nt as enablejQueryBatching,
1674
+ h as registry,
1675
+ xe as untracked
1676
+ };
1677
+ //# sourceMappingURL=index.mjs.map