mutts 1.0.1 → 1.0.3

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.
Files changed (111) hide show
  1. package/README.md +36 -6
  2. package/dist/chunks/_tslib-BgjropY9.js +81 -0
  3. package/dist/chunks/_tslib-BgjropY9.js.map +1 -0
  4. package/dist/chunks/_tslib-Mzh1rNsX.esm.js +75 -0
  5. package/dist/chunks/_tslib-Mzh1rNsX.esm.js.map +1 -0
  6. package/dist/chunks/{decorator-8qjFb7dw.js → decorator-DLvrD0UF.js} +103 -14
  7. package/dist/chunks/decorator-DLvrD0UF.js.map +1 -0
  8. package/dist/chunks/{decorator-AbRkXM5O.esm.js → decorator-DqiszP7i.esm.js} +100 -15
  9. package/dist/chunks/decorator-DqiszP7i.esm.js.map +1 -0
  10. package/dist/chunks/index-DzUDtFc7.esm.js +4841 -0
  11. package/dist/chunks/index-DzUDtFc7.esm.js.map +1 -0
  12. package/dist/chunks/index-HNVqPzjz.js +4891 -0
  13. package/dist/chunks/index-HNVqPzjz.js.map +1 -0
  14. package/dist/decorator.d.ts +57 -0
  15. package/dist/decorator.esm.js +1 -1
  16. package/dist/decorator.js +1 -1
  17. package/dist/destroyable.d.ts +43 -1
  18. package/dist/destroyable.esm.js +19 -1
  19. package/dist/destroyable.esm.js.map +1 -1
  20. package/dist/destroyable.js +19 -1
  21. package/dist/destroyable.js.map +1 -1
  22. package/dist/devtools/devtools.html +9 -0
  23. package/dist/devtools/devtools.js +5 -0
  24. package/dist/devtools/devtools.js.map +1 -0
  25. package/dist/devtools/manifest.json +8 -0
  26. package/dist/devtools/panel.css +72 -0
  27. package/dist/devtools/panel.html +31 -0
  28. package/dist/devtools/panel.js +13048 -0
  29. package/dist/devtools/panel.js.map +1 -0
  30. package/dist/eventful.d.ts +10 -1
  31. package/dist/eventful.esm.js +5 -27
  32. package/dist/eventful.esm.js.map +1 -1
  33. package/dist/eventful.js +15 -37
  34. package/dist/eventful.js.map +1 -1
  35. package/dist/index.d.ts +18 -14
  36. package/dist/index.esm.js +4 -3
  37. package/dist/index.esm.js.map +1 -1
  38. package/dist/index.js +44 -5
  39. package/dist/index.js.map +1 -1
  40. package/dist/indexable.d.ts +213 -1
  41. package/dist/indexable.esm.js +203 -3
  42. package/dist/indexable.esm.js.map +1 -1
  43. package/dist/indexable.js +204 -2
  44. package/dist/indexable.js.map +1 -1
  45. package/dist/mutts.umd.js +1 -1
  46. package/dist/mutts.umd.js.map +1 -1
  47. package/dist/mutts.umd.min.js +1 -1
  48. package/dist/mutts.umd.min.js.map +1 -1
  49. package/dist/promiseChain.d.ts +10 -0
  50. package/dist/promiseChain.esm.js +6 -0
  51. package/dist/promiseChain.esm.js.map +1 -1
  52. package/dist/promiseChain.js +6 -0
  53. package/dist/promiseChain.js.map +1 -1
  54. package/dist/reactive.d.ts +774 -33
  55. package/dist/reactive.esm.js +4 -1458
  56. package/dist/reactive.esm.js.map +1 -1
  57. package/dist/reactive.js +53 -1474
  58. package/dist/reactive.js.map +1 -1
  59. package/dist/std-decorators.d.ts +35 -0
  60. package/dist/std-decorators.esm.js +36 -1
  61. package/dist/std-decorators.esm.js.map +1 -1
  62. package/dist/std-decorators.js +36 -1
  63. package/dist/std-decorators.js.map +1 -1
  64. package/docs/ai/api-reference.md +133 -0
  65. package/docs/ai/manual.md +105 -0
  66. package/docs/iterableWeak.md +646 -0
  67. package/docs/mixin.md +229 -0
  68. package/docs/reactive/advanced.md +1280 -0
  69. package/docs/reactive/collections.md +767 -0
  70. package/docs/reactive/core.md +973 -0
  71. package/docs/reactive.md +21 -2688
  72. package/package.json +18 -5
  73. package/src/decorator.ts +266 -0
  74. package/src/destroyable.ts +199 -0
  75. package/src/eventful.ts +77 -0
  76. package/src/index.d.ts +9 -0
  77. package/src/index.ts +9 -0
  78. package/src/indexable.ts +484 -0
  79. package/src/introspection.ts +59 -0
  80. package/src/iterableWeak.ts +233 -0
  81. package/src/mixins.ts +123 -0
  82. package/src/promiseChain.ts +110 -0
  83. package/src/reactive/array.ts +414 -0
  84. package/src/reactive/change.ts +134 -0
  85. package/src/reactive/debug.ts +517 -0
  86. package/src/reactive/deep-touch.ts +268 -0
  87. package/src/reactive/deep-watch-state.ts +82 -0
  88. package/src/reactive/deep-watch.ts +168 -0
  89. package/src/reactive/effect-context.ts +94 -0
  90. package/src/reactive/effects.ts +1333 -0
  91. package/src/reactive/index.ts +75 -0
  92. package/src/reactive/interface.ts +223 -0
  93. package/src/reactive/map.ts +171 -0
  94. package/src/reactive/mapped.ts +130 -0
  95. package/src/reactive/memoize.ts +107 -0
  96. package/src/reactive/non-reactive-state.ts +49 -0
  97. package/src/reactive/non-reactive.ts +43 -0
  98. package/src/reactive/project.project.md +93 -0
  99. package/src/reactive/project.ts +335 -0
  100. package/src/reactive/proxy-state.ts +27 -0
  101. package/src/reactive/proxy.ts +285 -0
  102. package/src/reactive/record.ts +196 -0
  103. package/src/reactive/register.ts +421 -0
  104. package/src/reactive/set.ts +144 -0
  105. package/src/reactive/tracking.ts +101 -0
  106. package/src/reactive/types.ts +358 -0
  107. package/src/reactive/zone.ts +208 -0
  108. package/src/std-decorators.ts +217 -0
  109. package/src/utils.ts +117 -0
  110. package/dist/chunks/decorator-8qjFb7dw.js.map +0 -1
  111. package/dist/chunks/decorator-AbRkXM5O.esm.js.map +0 -1
@@ -1,11 +1,103 @@
1
- import { LegacyPropertyDecorator, ModernMethodDecorator, LegacyClassDecorator, ModernClassDecorator, ModernGetterDecorator, ModernAccessorDecorator, GenericClassDecorator } from './decorator.js';
1
+ import { LegacyPropertyDecorator, ModernMethodDecorator, LegacyClassDecorator, ModernClassDecorator, GenericClassDecorator, ModernGetterDecorator, ModernAccessorDecorator } from './decorator.js';
2
+ import { ArrayReadForward, forwardArray, getAt, setAt } from './indexable.js';
2
3
 
4
+ /**
5
+ * Function type for dependency tracking in effects
6
+ * Restores the active effect context for dependency tracking
7
+ */
3
8
  type DependencyFunction = <T>(cb: () => T) => T;
9
+ /**
10
+ * Dependency access passed to user callbacks within effects/watch
11
+ * Provides functions to track dependencies and information about the effect execution
12
+ */
13
+ interface DependencyAccess {
14
+ /**
15
+ * Tracks dependencies in the current effect context
16
+ * Use this for normal dependency tracking within the effect
17
+ * @example
18
+ * ```typescript
19
+ * effect(({ tracked }) => {
20
+ * // In async context, use tracked to restore dependency tracking
21
+ * await someAsyncOperation()
22
+ * const value = tracked(() => state.count) // Tracks state.count in this effect
23
+ * })
24
+ * ```
25
+ */
26
+ tracked: DependencyFunction;
27
+ /**
28
+ * Tracks dependencies in the parent effect context
29
+ * Use this when child effects should track dependencies in the parent,
30
+ * allowing parent cleanup to manage child effects while dependencies trigger the parent
31
+ * @example
32
+ * ```typescript
33
+ * effect(({ ascend }) => {
34
+ * const length = inputs.length
35
+ * if (length > 0) {
36
+ * ascend(() => {
37
+ * // Dependencies here are tracked in the parent effect
38
+ * inputs.forEach(item => console.log(item))
39
+ * })
40
+ * }
41
+ * })
42
+ * ```
43
+ */
44
+ ascend: DependencyFunction;
45
+ /**
46
+ * Indicates whether the effect is running as a reaction (i.e. not the first call)
47
+ * - `false`: First execution when the effect is created
48
+ * - `true`: Subsequent executions triggered by dependency changes
49
+ * @example
50
+ * ```typescript
51
+ * effect(({ reaction }) => {
52
+ * if (!reaction) {
53
+ * console.log('Effect initialized')
54
+ * // Setup code that should only run once
55
+ * } else {
56
+ * console.log('Effect re-ran due to dependency change')
57
+ * // Code that runs on every update
58
+ * }
59
+ * })
60
+ * ```
61
+ */
62
+ reaction: boolean;
63
+ }
64
+ /**
65
+ * Type for effect cleanup functions
66
+ */
4
67
  type ScopedCallback = () => void;
68
+ /**
69
+ * Async execution mode for effects
70
+ * - `cancel`: Cancel previous async execution when dependencies change (default)
71
+ * - `queue`: Queue next execution to run after current completes
72
+ * - `ignore`: Ignore new executions while async work is running
73
+ */
74
+ type AsyncExecutionMode = 'cancel' | 'queue' | 'ignore';
75
+ /**
76
+ * Options for effect creation
77
+ */
78
+ interface EffectOptions {
79
+ /**
80
+ * How to handle async effect executions when dependencies change
81
+ * @default 'cancel'
82
+ */
83
+ asyncMode?: AsyncExecutionMode;
84
+ /**
85
+ * If true, this effect is "opaque" to deep optimizations: it sees the object reference itself
86
+ * and must be notified when it changes, regardless of deep content similarity.
87
+ * Use this for effects that depend on object identity (like memoize).
88
+ */
89
+ opaque?: boolean;
90
+ }
91
+ /**
92
+ * Type for property evolution events
93
+ */
5
94
  type PropEvolution = {
6
95
  type: 'set' | 'del' | 'add' | 'invalidate';
7
96
  prop: any;
8
97
  };
98
+ /**
99
+ * Type for collection operation evolution events
100
+ */
9
101
  type BunchEvolution = {
10
102
  type: 'bunch';
11
103
  method: string;
@@ -15,36 +107,110 @@ type State = {
15
107
  evolution: Evolution;
16
108
  next: State;
17
109
  } | {};
18
- declare const profileInfo: any;
110
+ /**
111
+ * Structured error codes for machine-readable diagnosis
112
+ */
113
+ declare enum ReactiveErrorCode {
114
+ CycleDetected = "CYCLE_DETECTED",
115
+ MaxDepthExceeded = "MAX_DEPTH_EXCEEDED",
116
+ MaxReactionExceeded = "MAX_REACTION_EXCEEDED",
117
+ WriteInComputed = "WRITE_IN_COMPUTED",
118
+ TrackingError = "TRACKING_ERROR"
119
+ }
120
+ type CycleDebugInfo = {
121
+ code: ReactiveErrorCode.CycleDetected;
122
+ cycle: string[];
123
+ details?: string;
124
+ };
125
+ type MaxDepthDebugInfo = {
126
+ code: ReactiveErrorCode.MaxDepthExceeded;
127
+ depth: number;
128
+ chain: string[];
129
+ };
130
+ type MaxReactionDebugInfo = {
131
+ code: ReactiveErrorCode.MaxReactionExceeded;
132
+ count: number;
133
+ effect: string;
134
+ };
135
+ type GenericDebugInfo = {
136
+ code: ReactiveErrorCode;
137
+ causalChain?: string[];
138
+ creationStack?: string;
139
+ [key: string]: any;
140
+ };
141
+ type ReactiveDebugInfo = CycleDebugInfo | MaxDepthDebugInfo | MaxReactionDebugInfo | GenericDebugInfo;
142
+ /**
143
+ * Error class for reactive system errors
144
+ */
19
145
  declare class ReactiveError extends Error {
20
- constructor(message: string);
146
+ debugInfo?: ReactiveDebugInfo;
147
+ constructor(message: string, debugInfo?: ReactiveDebugInfo);
21
148
  }
22
149
  /**
23
- * Options for the reactive system, can be configured at runtime
150
+ * Global options for the reactive system
24
151
  */
25
152
  declare const options: {
26
153
  /**
27
154
  * Debug purpose: called when an effect is entered
28
155
  * @param effect - The effect that is entered
29
156
  */
30
- enter: (effect: Function) => void;
157
+ enter: (_effect: Function) => void;
31
158
  /**
32
159
  * Debug purpose: called when an effect is left
33
160
  * @param effect - The effect that is left
34
161
  */
35
- leave: (effect: Function) => void;
162
+ leave: (_effect: Function) => void;
36
163
  /**
37
164
  * Debug purpose: called when an effect is chained
38
165
  * @param target - The effect that is being triggered
39
166
  * @param caller - The effect that is calling the target
40
167
  */
41
- chain: (target: Function, caller?: Function) => void;
168
+ chain: (_targets: Function[], _caller?: Function) => void;
169
+ /**
170
+ * Debug purpose: called when an effect chain is started
171
+ * @param target - The effect that is being triggered
172
+ */
173
+ beginChain: (_targets: Function[]) => void;
174
+ /**
175
+ * Debug purpose: called when an effect chain is ended
176
+ */
177
+ endChain: () => void;
178
+ garbageCollected: (_fn: Function) => void;
179
+ /**
180
+ * Debug purpose: called when an object is touched
181
+ * @param obj - The object that is touched
182
+ * @param evolution - The type of change
183
+ * @param props - The properties that changed
184
+ * @param deps - The dependencies that changed
185
+ */
186
+ touched: (_obj: any, _evolution: Evolution, _props?: any[], _deps?: Set<ScopedCallback>) => void;
187
+ /**
188
+ * Debug purpose: called when an effect is skipped because it's already running
189
+ * @param effect - The effect that is already running
190
+ * @param runningChain - The array of effects from the detected one to the currently running one
191
+ */
192
+ skipRunningEffect: (_effect: ScopedCallback, _runningChain: ScopedCallback[]) => void;
42
193
  /**
43
194
  * Debug purpose: maximum effect chain (like call stack max depth)
44
195
  * Used to prevent infinite loops
45
196
  * @default 100
46
197
  */
47
198
  maxEffectChain: number;
199
+ /**
200
+ * Debug purpose: maximum effect reaction (like call stack max depth)
201
+ * Used to prevent infinite loops
202
+ * @default 'throw'
203
+ */
204
+ maxEffectReaction: "throw" | "debug" | "warn";
205
+ /**
206
+ * How to handle cycles detected in effect batches
207
+ * - 'throw': Throw an error with cycle information (default, recommended for development)
208
+ * - 'warn': Log a warning and break the cycle by executing one effect
209
+ * - 'break': Silently break the cycle by executing one effect (recommended for production)
210
+ * - 'strict': Prevent cycle creation by checking graph before execution (throws error)
211
+ * @default 'throw'
212
+ */
213
+ cycleHandling: "throw" | "warn" | "break" | "strict";
48
214
  /**
49
215
  * Maximum depth for deep watching traversal
50
216
  * Used to prevent infinite recursion in circular references
@@ -57,59 +223,634 @@ declare const options: {
57
223
  * @default true
58
224
  */
59
225
  instanceMembers: boolean;
226
+ /**
227
+ * Ignore accessors (getters and setters) and only track direct properties
228
+ * @default true
229
+ */
230
+ ignoreAccessors: boolean;
231
+ /**
232
+ * Enable recursive touching when objects with the same prototype are replaced
233
+ * When enabled, replacing an object with another of the same prototype triggers
234
+ * recursive diffing instead of notifying parent effects
235
+ * @default true
236
+ */
237
+ recursiveTouching: boolean;
238
+ /**
239
+ * Default async execution mode for effects that return Promises
240
+ * - 'cancel': Cancel previous async execution when dependencies change (default, enables async zone)
241
+ * - 'queue': Queue next execution to run after current completes (enables async zone)
242
+ * - 'ignore': Ignore new executions while async work is running (enables async zone)
243
+ * - false: Disable async zone and async mode handling (effects run concurrently)
244
+ *
245
+ * **When truthy:** Enables async zone (Promise.prototype wrapping) for automatic context
246
+ * preservation in Promise callbacks. Warning: This modifies Promise.prototype globally.
247
+ * Only enable if no other library modifies Promise.prototype.
248
+ *
249
+ * **When false:** Async zone is disabled. Use `tracked()` manually in Promise callbacks.
250
+ *
251
+ * Can be overridden per-effect via EffectOptions
252
+ * @default 'cancel'
253
+ */
254
+ asyncMode: AsyncExecutionMode | false;
60
255
  warn: (...args: any[]) => void;
256
+ /**
257
+ * Configuration for the introspection system
258
+ */
259
+ introspection: {
260
+ /**
261
+ * Whether to keep a history of mutations for debugging
262
+ * @default false
263
+ */
264
+ enableHistory: boolean;
265
+ /**
266
+ * Number of mutations to keep in history
267
+ * @default 50
268
+ */
269
+ historySize: number;
270
+ };
271
+ /**
272
+ * Configuration for zone hooks - control which async APIs are hooked
273
+ * Each option controls whether the corresponding async API is wrapped to preserve effect context
274
+ * Only applies when asyncMode is enabled (truthy)
275
+ */
276
+ zones: {
277
+ /**
278
+ * Hook setTimeout to preserve effect context
279
+ * @default true
280
+ */
281
+ setTimeout: boolean;
282
+ /**
283
+ * Hook setInterval to preserve effect context
284
+ * @default true
285
+ */
286
+ setInterval: boolean;
287
+ /**
288
+ * Hook requestAnimationFrame (runs in untracked context when hooked)
289
+ * @default true
290
+ */
291
+ requestAnimationFrame: boolean;
292
+ /**
293
+ * Hook queueMicrotask to preserve effect context
294
+ * @default true
295
+ */
296
+ queueMicrotask: boolean;
297
+ };
61
298
  };
299
+
300
+ /**
301
+ * Gets the current state of a reactive object for evolution tracking
302
+ * @param obj - The reactive object
303
+ * @returns The current state object
304
+ */
62
305
  declare function getState(obj: any): State;
63
- declare const atomic: LegacyPropertyDecorator<any> & ModernMethodDecorator<any> & (<Args extends any[], Return>(original: (...args: Args) => Return) => (...args: Args) => Return);
64
- declare class ReactiveBase {
65
- constructor();
306
+ /**
307
+ * Triggers effects for a single property change
308
+ * @param obj - The object that changed
309
+ * @param evolution - The type of change
310
+ * @param prop - The property that changed
311
+ */
312
+ declare function touched1(obj: any, evolution: Evolution, prop: any): void;
313
+ /**
314
+ * Triggers effects for property changes
315
+ * @param obj - The object that changed
316
+ * @param evolution - The type of change
317
+ * @param props - The properties that changed
318
+ */
319
+ declare function touched(obj: any, evolution: Evolution, props?: Iterable<any>): void;
320
+
321
+ /**
322
+ * Debug utilities for the reactivity system
323
+ * - Captures effect metadata (names, parent relationships)
324
+ * - Records cause → consequence edges with object/prop labels
325
+ * - Provides graph data for tooling (DevTools panel, etc.)
326
+ */
327
+
328
+ type NodeKind = 'effect' | 'external' | 'state';
329
+ type EdgeKind = 'cause' | 'dependency' | 'trigger';
330
+ interface EffectNode {
331
+ id: string;
332
+ label: string;
333
+ type: NodeKind;
334
+ depth: number;
335
+ parentId?: string;
336
+ debugName?: string;
66
337
  }
67
- declare function reactiveObject<T>(anyTarget: T): T;
68
- declare const reactive: LegacyClassDecorator<new (...args: any[]) => any> & ModernClassDecorator<new (...args: any[]) => any> & typeof reactiveObject;
69
- declare function unwrap<T>(proxy: T): T;
70
- declare function isReactive(obj: any): boolean;
71
- declare function untracked(fn: () => ScopedCallback | undefined | void): void;
338
+ interface ObjectNode {
339
+ id: string;
340
+ label: string;
341
+ type: NodeKind;
342
+ debugName?: string;
343
+ }
344
+ interface GraphEdge {
345
+ id: string;
346
+ source: string;
347
+ target: string;
348
+ type: EdgeKind;
349
+ label: string;
350
+ count?: number;
351
+ }
352
+ interface ReactivityGraph {
353
+ nodes: Array<EffectNode | ObjectNode>;
354
+ edges: GraphEdge[];
355
+ meta: {
356
+ generatedAt: number;
357
+ devtoolsEnabled: boolean;
358
+ };
359
+ }
360
+ /**
361
+ * Assign a debug-friendly name to an effect (shown in DevTools)
362
+ */
363
+ declare function setEffectName(effect: ScopedCallback, name: string): void;
364
+ /**
365
+ * Assign a debug-friendly name to a reactive object
366
+ */
367
+ declare function setObjectName(obj: object, name: string): void;
368
+ /**
369
+ * Register an effect so it appears in the DevTools graph
370
+ */
371
+ declare function registerEffectForDebug(effect: ScopedCallback): void;
372
+ /**
373
+ * Register a reactive object so it appears in the DevTools graph
374
+ */
375
+ declare function registerObjectForDebug(obj: object): void;
376
+ /**
377
+ * Builds a graph representing current reactive state (effects, objects, and trigger edges)
378
+ */
379
+ declare function buildReactivityGraph(): ReactivityGraph;
380
+ /**
381
+ * Enables the DevTools bridge and exposes the debug API on window.
382
+ * Call as early as possible in development builds.
383
+ */
384
+ declare function enableDevTools(): void;
385
+ declare function isDevtoolsEnabled(): boolean;
386
+
387
+ /**
388
+ * Deep watch an object and all its nested properties
389
+ * @param target - The object to watch deeply
390
+ * @param callback - The callback to call when any nested property changes
391
+ * @param options - Options for the deep watch
392
+ * @returns A cleanup function to stop watching
393
+ */
394
+ /**
395
+ * Sets up deep watching for an object, tracking all nested property changes
396
+ * @param target - The object to watch
397
+ * @param callback - The callback to call when changes occur
398
+ * @param options - Options for deep watching
399
+ * @returns A cleanup function to stop deep watching
400
+ */
401
+ declare function deepWatch<T extends object>(target: T, callback: (value: T) => void, { immediate }?: {
402
+ immediate?: boolean;
403
+ }): (() => void) | undefined;
404
+
405
+ declare function getActiveEffect(): ScopedCallback;
406
+
407
+ type EffectTracking = (obj: any, evolution: Evolution, prop: any) => void;
408
+
409
+ /**
410
+ * Registers a debug callback that is called when the current effect is triggered by a dependency change
411
+ *
412
+ * This function is useful for debugging purposes as it pin-points exactly which reactive property
413
+ * change triggered the effect. The callback receives information about:
414
+ * - The object that changed
415
+ * - The type of change (evolution)
416
+ * - The specific property that changed
417
+ *
418
+ * **Note:** The tracker callback is automatically removed after being called once. If you need
419
+ * to track multiple triggers, call `trackEffect` again within the effect.
420
+ *
421
+ * @param onTouch - Callback function that receives (obj, evolution, prop) when the effect is triggered
422
+ * @throws {Error} If called outside of an effect context
423
+ *
424
+ * @example
425
+ * ```typescript
426
+ * const state = reactive({ count: 0, name: 'John' })
427
+ *
428
+ * effect(() => {
429
+ * // Register a tracker to see what triggers this effect
430
+ * trackEffect((obj, evolution, prop) => {
431
+ * console.log(`Effect triggered by:`, {
432
+ * object: obj,
433
+ * change: evolution.type,
434
+ * property: prop
435
+ * })
436
+ * })
437
+ *
438
+ * // Access reactive properties
439
+ * console.log(state.count, state.name)
440
+ * })
441
+ *
442
+ * state.count = 5
443
+ * // Logs: Effect triggered by: { object: state, change: 'set', property: 'count' }
444
+ * ```
445
+ */
446
+ declare function trackEffect(onTouch: EffectTracking): void;
447
+ /**
448
+ * Adds a cleanup function to be called when the current batch of effects completes
449
+ * @param cleanup - The cleanup function to add
450
+ */
451
+ declare function addBatchCleanup(cleanup: ScopedCallback): void;
452
+ /**
453
+ * Semantic alias for `addBatchCleanup` - defers work to the end of the current reactive batch.
454
+ *
455
+ * Use this when an effect needs to perform an action that would modify state the effect depends on,
456
+ * which would create a reactive cycle. The deferred callback runs after all effects complete.
457
+ *
458
+ * @param callback - The callback to defer until after the current batch completes
459
+ *
460
+ * @example
461
+ * ```typescript
462
+ * effect(() => {
463
+ * processData()
464
+ *
465
+ * // Defer to avoid cycle (createMovement modifies state this effect reads)
466
+ * defer(() => {
467
+ * createMovement(data)
468
+ * })
469
+ * })
470
+ * ```
471
+ */
472
+ declare const defer: typeof addBatchCleanup;
473
+ /**
474
+ * Decorator that makes methods atomic - batches all effects triggered within the method
475
+ */
476
+ declare const atomic: LegacyPropertyDecorator<any> & ModernMethodDecorator<any> & (<Args extends any[], Return>(original: (...args: Args) => Return) => (...args: Args) => Return);
72
477
  /**
73
478
  * @param fn - The effect function to run - provides the cleaner
74
479
  * @returns The cleanup function
75
480
  */
76
- declare function effect<Args extends any[]>(fn: (dep: DependencyFunction, ...args: Args) => ScopedCallback | undefined | void, ...args: Args): ScopedCallback;
77
481
  /**
78
- * Set of functions to test if an object is immutable
482
+ * Creates a reactive effect that automatically re-runs when dependencies change
483
+ * @param fn - The effect function that provides dependencies and may return a cleanup function or Promise
484
+ * @param options - Options for effect execution
485
+ * @returns A cleanup function to stop the effect
79
486
  */
80
- declare const immutables: Set<(tested: any) => boolean>;
487
+ declare function effect(fn: (access: DependencyAccess) => ScopedCallback | undefined | void | Promise<any>, effectOptions?: EffectOptions): ScopedCallback;
81
488
  /**
82
- * Check if an object is marked as non-reactive (for testing purposes)
83
- * @param obj - The object to check
84
- * @returns true if the object is marked as non-reactive
489
+ * Executes a function without tracking dependencies but maintains parent cleanup relationship
490
+ * Effects created inside will still be cleaned up when the parent effect is destroyed
491
+ * @param fn - The function to execute
85
492
  */
86
- declare function isNonReactive(obj: any): boolean;
493
+ declare function untracked<T>(fn: () => T): T;
494
+ /**
495
+ * Executes a function from a virgin/root context - no parent effect, no tracking
496
+ * Creates completely independent effects that won't be cleaned up by any parent
497
+ * @param fn - The function to execute
498
+ */
499
+ declare function root<T>(fn: () => T): T;
500
+
501
+ /**
502
+ * Creates a bidirectional binding between a reactive value and a non-reactive external value
503
+ * Prevents infinite loops by automatically suppressing circular notifications
504
+ *
505
+ * @param received - Function called when the reactive value changes (external setter)
506
+ * @param get - Getter for the reactive value OR an object with `{ get, set }` properties
507
+ * @param set - Setter for the reactive value (required if `get` is a function)
508
+ * @returns A function to manually provide updates from the external side
509
+ *
510
+ * @example
511
+ * ```typescript
512
+ * const model = reactive({ value: '' })
513
+ * const input = { value: '' }
514
+ *
515
+ * // Bidirectional binding
516
+ * const provide = biDi(
517
+ * (v) => input.value = v, // external setter
518
+ * () => model.value, // reactive getter
519
+ * (v) => model.value = v // reactive setter
520
+ * )
521
+ *
522
+ * // External notification (e.g., from input event)
523
+ * provide('new value') // Updates model.value, doesn't trigger circular loop
524
+ * ```
525
+ *
526
+ * @example Using object syntax
527
+ * ```typescript
528
+ * const provide = biDi(
529
+ * (v) => setHTMLValue(v),
530
+ * { get: () => reactiveObj.value, set: (v) => reactiveObj.value = v }
531
+ * )
532
+ * ```
533
+ */
534
+ declare function biDi<T>(received: (value: T) => void, value: {
535
+ get: () => T;
536
+ set: (value: T) => void;
537
+ }): (value: T) => void;
538
+ declare function biDi<T>(received: (value: T) => void, get: () => T, set: (value: T) => void): (value: T) => void;
87
539
 
88
540
  /**
89
- * When used in a computed property computation, it will register the callback to be called when the computed property is invalidated
90
- * @param cb - The callback to register
91
- * @param warn - Whether to warn if used outside of a computed property
541
+ * Symbol for accessing the cleanup function on cleaned objects
92
542
  */
93
- declare function invalidateComputed(cb: () => void, warn?: boolean): void;
94
- type ComputedFunction<T> = (dep: DependencyFunction) => T;
543
+ declare const cleanup: unique symbol;
95
544
  /**
96
- * Get the cached value of a computed function - cache is invalidated when the dependencies change
545
+ * Options for the watch function
97
546
  */
98
- declare const computed: LegacyPropertyDecorator<any> & ModernGetterDecorator<any> & ModernAccessorDecorator<any> & (<T>(getter: ComputedFunction<T>) => T);
99
547
  interface WatchOptions {
548
+ /** Whether to call the callback immediately */
100
549
  immediate?: boolean;
550
+ /** Whether to watch nested properties */
101
551
  deep?: boolean;
102
552
  }
103
- declare function watch<T>(value: (dep: DependencyFunction) => T, changed: (value: T, oldValue?: T) => void, options?: Omit<WatchOptions, 'deep'> & {
553
+ /**
554
+ * Watches a reactive value and calls a callback when it changes
555
+ * @param value - Function that returns the value to watch
556
+ * @param changed - Callback to call when the value changes
557
+ * @param options - Watch options
558
+ * @returns Cleanup function to stop watching
559
+ */
560
+ declare function watch<T>(value: (dep: DependencyAccess) => T, changed: (value: T, oldValue?: T) => void, options?: Omit<WatchOptions, 'deep'> & {
104
561
  deep?: false;
105
562
  }): ScopedCallback;
106
- declare function watch<T extends object | any[]>(value: (dep: DependencyFunction) => T, changed: (value: T, oldValue?: T) => void, options?: Omit<WatchOptions, 'deep'> & {
563
+ /**
564
+ * Watches a reactive value with deep watching enabled
565
+ * @param value - Function that returns the value to watch
566
+ * @param changed - Callback to call when the value changes
567
+ * @param options - Watch options with deep watching enabled
568
+ * @returns Cleanup function to stop watching
569
+ */
570
+ declare function watch<T extends object | any[]>(value: (dep: DependencyAccess) => T, changed: (value: T, oldValue?: T) => void, options?: Omit<WatchOptions, 'deep'> & {
107
571
  deep: true;
108
572
  }): ScopedCallback;
573
+ /**
574
+ * Watches a reactive object directly
575
+ * @param value - The reactive object to watch
576
+ * @param changed - Callback to call when the object changes
577
+ * @param options - Watch options
578
+ * @returns Cleanup function to stop watching
579
+ */
109
580
  declare function watch<T extends object | any[]>(value: T, changed: (value: T) => void, options?: WatchOptions): ScopedCallback;
110
581
  declare function unreactiveApplication<T extends object>(...args: (keyof T)[]): GenericClassDecorator<T>;
111
582
  declare function unreactiveApplication<T extends object>(obj: T): T;
583
+ /**
584
+ * Decorator that marks classes or properties as non-reactive
585
+ * Prevents objects from being made reactive
586
+ */
112
587
  declare const unreactive: LegacyClassDecorator<new (...args: any[]) => any> & ModernClassDecorator<new (...args: any[]) => any> & typeof unreactiveApplication;
588
+ declare function cleanedBy<T extends object>(obj: T, cleanupFn: ScopedCallback): T & {
589
+ [cleanup]: ScopedCallback;
590
+ };
591
+ /**
592
+ * Creates a derived value that automatically recomputes when dependencies change
593
+ * @param compute - Function that computes the derived value
594
+ * @returns Object with value and cleanup function
595
+ */
596
+ declare function derived<T>(compute: (dep: DependencyAccess) => T): {
597
+ value: T;
598
+ [cleanup]: ScopedCallback;
599
+ };
600
+
601
+ declare class ReadOnlyError extends Error {
602
+ }
603
+ declare function mapped<T, U>(inputs: readonly T[], compute: (input: T, index: number, output: U[]) => U, resize?: (newLength: number, oldLength: number) => void): readonly U[];
604
+ declare function reduced<T, U, R extends object = any>(inputs: readonly T[], compute: (input: T, factor: R) => readonly U[]): readonly U[];
605
+
606
+ type Memoizable = object | any[] | symbol | ((...args: any[]) => any);
607
+ declare function memoizeFunction<Result, Args extends Memoizable[]>(fn: (...args: Args) => Result): (...args: Args) => Result;
608
+ declare const memoize: LegacyPropertyDecorator<any> & ModernMethodDecorator<any> & ModernGetterDecorator<any> & ModernAccessorDecorator<any> & typeof memoizeFunction;
609
+
610
+ declare const immutables: Set<(tested: any) => boolean>;
611
+ declare function isNonReactive(obj: any): boolean;
612
+ declare function registerNativeReactivity(originalClass: new (...args: any[]) => any, reactiveClass: new (...args: any[]) => any): void;
613
+
614
+ type KeyFunction<T, K extends PropertyKey> = (item: T) => K;
615
+ interface RegisterInstance<T> extends ArrayReadForward<T> {
616
+ [index: number]: T;
617
+ }
618
+ declare const RegisterClass_base: new () => ArrayReadForward<any> & {
619
+ [x: number]: any;
620
+ toArray(): any[];
621
+ };
622
+ declare class RegisterClass<T, K extends PropertyKey = PropertyKey> extends RegisterClass_base implements RegisterInstance<T> {
623
+ #private;
624
+ protected get [forwardArray](): readonly T[];
625
+ constructor(keyFn: KeyFunction<T, K>, initial?: Iterable<T>);
626
+ private ensureKey;
627
+ private assertValidKey;
628
+ private setKeyValue;
629
+ private cleanupValue;
630
+ private disposeKeyEffects;
631
+ private incrementUsage;
632
+ private decrementUsage;
633
+ private normalizeIndex;
634
+ private assignAt;
635
+ private insertKeyValue;
636
+ private rebuildFrom;
637
+ get length(): number;
638
+ [getAt](index: number): T | undefined;
639
+ [setAt](index: number, value: T): void;
640
+ push(...items: T[]): number;
641
+ pop(): T | undefined;
642
+ shift(): T | undefined;
643
+ unshift(...items: T[]): number;
644
+ splice(start: number, deleteCount?: number, ...items: T[]): T[];
645
+ clear(): void;
646
+ get(key: K): T | undefined;
647
+ set(key: K, value: T): void;
648
+ remove(key: K): void;
649
+ removeAt(index: number): T | undefined;
650
+ /**
651
+ * Keep only the items for which the predicate returns true.
652
+ * Items for which the predicate returns false are removed.
653
+ *
654
+ * The predicate is evaluated once per distinct key; duplicate keys
655
+ * will follow the same keep/remove decision.
656
+ */
657
+ keep(predicate: (value: T) => boolean): void;
658
+ hasKey(key: K): boolean;
659
+ indexOfKey(key: K): number;
660
+ mapKeys(): IterableIterator<K>;
661
+ update(...values: T[]): void;
662
+ upsert(insert: (value: T) => void, ...values: T[]): void;
663
+ entries(): IterableIterator<[number, T]>;
664
+ [Symbol.iterator](): IterableIterator<T>;
665
+ toString(): string;
666
+ at(index: number): T | undefined;
667
+ reverse(): this;
668
+ sort(compareFn?: ((a: T, b: T) => number) | undefined): this;
669
+ fill(value: T, start?: number, end?: number): this;
670
+ copyWithin(target: number, start: number, end?: number): this;
671
+ }
672
+ type Register<T, K extends PropertyKey = PropertyKey> = RegisterClass<T, K> & T[];
673
+ declare const Register: new <T, K extends PropertyKey = PropertyKey>(keyFn: KeyFunction<T, K>, initial?: Iterable<T>) => Register<T, K>;
674
+ declare function register<T, K extends PropertyKey = PropertyKey>(keyFn: KeyFunction<T, K>, initial?: Iterable<T>): Register<T, K>;
675
+
676
+ type ProjectOldValue<Target> = Target extends readonly (infer Item)[] ? Item : Target extends Map<any, infer Item> ? Item : Target extends Record<PropertyKey, infer Item> ? Item : unknown;
677
+ type ProjectAccess<SourceValue, Key, SourceType, Target> = {
678
+ readonly key: Key;
679
+ get(): SourceValue;
680
+ set(value: SourceValue): boolean;
681
+ readonly source: SourceType;
682
+ readonly old?: ProjectOldValue<Target>;
683
+ value: SourceValue;
684
+ };
685
+ type BivariantProjectCallback<Args extends any[], Return> = {
686
+ bivarianceHack(...args: Args): Return;
687
+ }['bivarianceHack'];
688
+ type ProjectCallback<SourceValue, Key, Target extends object, SourceType, Result> = BivariantProjectCallback<[ProjectAccess<SourceValue, Key, SourceType, Target>, Target], Result>;
689
+ type ProjectResult<Target extends object> = Target & {
690
+ [cleanup]: ScopedCallback;
691
+ };
692
+ declare function projectArray<SourceValue, ResultValue>(source: readonly SourceValue[], apply: ProjectCallback<SourceValue, number, ResultValue[], readonly SourceValue[], ResultValue>): ProjectResult<ResultValue[]>;
693
+ declare function projectRegister<Key extends PropertyKey, SourceValue, ResultValue>(source: Register<SourceValue, Key>, apply: ProjectCallback<SourceValue, Key, Map<Key, ResultValue>, Register<SourceValue, Key>, ResultValue>): ProjectResult<Map<Key, ResultValue>>;
694
+ declare function projectRecord<Source extends Record<PropertyKey, any>, ResultValue>(source: Source, apply: ProjectCallback<Source[keyof Source], keyof Source, Record<keyof Source, ResultValue>, Source, ResultValue>): ProjectResult<Record<keyof Source, ResultValue>>;
695
+ declare function projectMap<Key, Value, ResultValue>(source: Map<Key, Value>, apply: ProjectCallback<Value, Key, Map<Key, ResultValue>, Map<Key, Value>, ResultValue>): ProjectResult<Map<Key, ResultValue>>;
696
+ type ProjectOverload = {
697
+ <SourceValue, ResultValue>(source: readonly SourceValue[], apply: ProjectCallback<SourceValue, number, ResultValue[], readonly SourceValue[], ResultValue>): ProjectResult<ResultValue[]>;
698
+ <Key extends PropertyKey, SourceValue, ResultValue>(source: Register<SourceValue, Key>, apply: ProjectCallback<SourceValue, Key, Map<Key, ResultValue>, Register<SourceValue, Key>, ResultValue>): ProjectResult<Map<Key, ResultValue>>;
699
+ <Source extends Record<PropertyKey, any>, ResultValue>(source: Source, apply: ProjectCallback<Source[keyof Source], keyof Source, Record<keyof Source, ResultValue>, Source, ResultValue>): ProjectResult<Record<keyof Source, ResultValue>>;
700
+ <Key, Value, ResultValue>(source: Map<Key, Value>, apply: ProjectCallback<Value, Key, Map<Key, ResultValue>, Map<Key, Value>, ResultValue>): ProjectResult<Map<Key, ResultValue>>;
701
+ array: typeof projectArray;
702
+ register: typeof projectRegister;
703
+ record: typeof projectRecord;
704
+ map: typeof projectMap;
705
+ };
706
+ declare const project: ProjectOverload;
707
+
708
+ declare function unwrap<T>(obj: T): T;
709
+ declare function isReactive(obj: any): boolean;
710
+
711
+ /**
712
+ * Base mixin for reactive classes that provides proper constructor reactivity
713
+ * Solves constructor reactivity issues in complex inheritance trees
714
+ */
715
+ declare const ReactiveBase: (new (...args: any[]) => {
716
+ [x: string]: any;
717
+ }) & (<Base>(base: abstract new (...args: any[]) => Base) => new (...args: any[]) => {
718
+ [x: string]: any;
719
+ } & Base);
720
+ declare function reactiveObject<T>(anyTarget: T): T;
721
+ /**
722
+ * Main decorator for making classes reactive
723
+ * Automatically makes class instances reactive when created
724
+ */
725
+ declare const reactive: LegacyClassDecorator<new (...args: any[]) => any> & ModernClassDecorator<new (...args: any[]) => any> & typeof reactiveObject;
726
+
727
+ /**
728
+ * Provides type-safe access to a source object's property within the organized callback.
729
+ * @template Source - The type of the source object
730
+ * @template Key - The type of the property key in the source object
731
+ */
732
+ type OrganizedAccess<Source extends Record<PropertyKey, any>, Key extends keyof Source> = {
733
+ /** The property key being accessed */
734
+ readonly key: Key;
735
+ /**
736
+ * Gets the current value of the property from the source object
737
+ * @returns The current value of the property
738
+ */
739
+ get(): Source[Key];
740
+ /**
741
+ * Updates the property value in the source object
742
+ * @param value - The new value to set
743
+ * @returns {boolean} True if the update was successful
744
+ */
745
+ set(value: Source[Key]): boolean;
746
+ /**
747
+ * The current value of the property (equivalent to using get()/set() directly)
748
+ */
749
+ value: Source[Key];
750
+ };
751
+ /**
752
+ * Callback function type for the organized function that processes each source property.
753
+ * @template Source - The type of the source object
754
+ * @template Target - The type of the target object
755
+ */
756
+ type OrganizedCallback<Source extends Record<PropertyKey, any>, Target extends object> = <Key extends keyof Source>(
757
+ /**
758
+ * Accessor object for the current source property
759
+ */
760
+ access: OrganizedAccess<Source, Key>,
761
+ /**
762
+ * The target object where organized data will be stored
763
+ */
764
+ target: Target) => ScopedCallback | undefined;
765
+ /**
766
+ * The result type of the organized function, combining the target object with cleanup capability.
767
+ * @template Target - The type of the target object
768
+ */
769
+ type OrganizedResult<Target extends object> = Target & {
770
+ /**
771
+ * Cleanup function to dispose of all reactive bindings created by organized().
772
+ * This is automatically called when the effect that created the organized binding is disposed.
773
+ */
774
+ [cleanup]: ScopedCallback;
775
+ };
776
+ /**
777
+ * Organizes a source object's properties into a target object using a callback function.
778
+ * This creates a reactive mapping between source properties and a target object,
779
+ * automatically handling property additions, updates, and removals.
780
+ *
781
+ * @template Source - The type of the source object
782
+ * @template Target - The type of the target object (defaults to Record<PropertyKey, any>)
783
+ *
784
+ * @param {Source} source - The source object to organize
785
+ * @param {OrganizedCallback<Source, Target>} apply - Callback function that defines how each source property is mapped to the target
786
+ * @param {Target} [baseTarget={}] - Optional base target object to use (will be made reactive if not already)
787
+ *
788
+ * @returns {OrganizedResult<Target>} The target object with cleanup capability
789
+ *
790
+ * @example
791
+ * // Organize user permissions into role-based access
792
+ * const user = reactive({ isAdmin: true, canEdit: false });
793
+ * const permissions = organized(
794
+ * user,
795
+ * (access, target) => {
796
+ * if (access.key === 'isAdmin') {
797
+ * target.hasFullAccess = access.value;
798
+ * }
799
+ * target[`can${access.key.charAt(0).toUpperCase() + access.key.slice(1)}`] = access.value;
800
+ * }
801
+ * );
802
+ *
803
+ * @example
804
+ * // Transform object structure with cleanup
805
+ * const source = reactive({ firstName: 'John', lastName: 'Doe' });
806
+ * const formatted = organized(
807
+ * source,
808
+ * (access, target) => {
809
+ * if (access.key === 'firstName' || access.key === 'lastName') {
810
+ * target.fullName = `${source.firstName} ${source.lastName}`.trim();
811
+ * }
812
+ * }
813
+ * );
814
+ *
815
+ * @example
816
+ * // Using with cleanup in a component
817
+ * effect(() => {
818
+ * const data = fetchData();
819
+ * const organizedData = organized(data, (access, target) => {
820
+ * // Transform data
821
+ * });
822
+ *
823
+ * // The cleanup will be called automatically when the effect is disposed
824
+ * return () => organizedData[cleanup]();
825
+ * });
826
+ */
827
+ declare function organized<Source extends Record<PropertyKey, any>, Target extends object = Record<PropertyKey, any>>(source: Source, apply: OrganizedCallback<Source, Target>, baseTarget?: Target): OrganizedResult<Target>;
828
+ /**
829
+ * Organizes a property on a target object
830
+ * Shortcut for defineProperty/delete with touched signal
831
+ * @param target - The target object
832
+ * @param property - The property to organize
833
+ * @param access - The access object
834
+ * @returns The property descriptor
835
+ */
836
+ declare function organize<T>(target: object, property: PropertyKey, access: {
837
+ get?(): T;
838
+ set?(value: T): boolean;
839
+ }): () => boolean;
840
+
841
+ /**
842
+ * Manually enable/disable the zone (for testing)
843
+ */
844
+ declare function setZoneEnabled(enabled: boolean): void;
845
+ /**
846
+ * Check if zone is currently hooked
847
+ */
848
+ declare function isZoneEnabled(): boolean;
849
+
850
+ /**
851
+ * Object containing internal reactive system state for debugging and profiling
852
+ */
853
+ declare const profileInfo: any;
113
854
 
114
- export { ReactiveBase, ReactiveError, atomic, computed, effect, getState, immutables, invalidateComputed, isNonReactive, isReactive, profileInfo, reactive, options as reactiveOptions, unreactive, untracked, unwrap, watch };
115
- export type { ScopedCallback };
855
+ export { ReactiveBase, ReactiveError, ReadOnlyError, Register, addBatchCleanup, atomic, biDi, buildReactivityGraph, cleanedBy, cleanup, deepWatch, defer, derived, effect, enableDevTools, getActiveEffect, getState, immutables, isDevtoolsEnabled, isNonReactive, isReactive, isZoneEnabled, mapped, memoize, organize, organized, profileInfo, project, reactive, options as reactiveOptions, reduced, register, registerEffectForDebug, registerNativeReactivity, registerObjectForDebug, root, setEffectName, setObjectName, setZoneEnabled, touched, touched1, trackEffect, unreactive, untracked, unwrap, watch };
856
+ export type { DependencyAccess, DependencyFunction, Evolution, Memoizable, ReactivityGraph, ScopedCallback };