mutts 1.0.5 → 1.0.7

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