@asaidimu/utils-store 10.2.3 → 10.2.5

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/index.d.cts ADDED
@@ -0,0 +1,1269 @@
1
+ //#region src/persistence/types.d.ts
2
+ interface SimplePersistence<T> {
3
+ /**
4
+ * Persists data to storage.
5
+ *
6
+ * @param id The **unique identifier of the *consumer instance*** making the change. This is NOT the ID of the data (`T`) itself.
7
+ * Think of it as the ID of the specific browser tab, component, or module that's currently interacting with the persistence layer.
8
+ * It should typically be a **UUID** generated once at the consumer instance's instantiation.
9
+ * This `id` is crucial for the `subscribe` method, helping to differentiate updates originating from the current instance versus other instances/tabs, thereby preventing self-triggered notification loops.
10
+ * @param state The state (of type T) to persist. This state is generally considered the **global or shared state** that all instances interact with.
11
+ * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations (like `IndexedDBPersistence`), this returns a `Promise<boolean>`.
12
+ */
13
+ set(id: string, state: T): boolean | Promise<boolean>;
14
+ /**
15
+ * Retrieves the global persisted data from storage.
16
+ *
17
+ * @returns The retrieved state of type `T`, or `null` if no data is found or if an error occurs during retrieval/parsing.
18
+ * For asynchronous implementations, this returns a `Promise<T | null>`.
19
+ */
20
+ get(): (T | null) | Promise<T | null>;
21
+ /**
22
+ * Subscribes to changes in the global persisted data that originate from *other* instances of your application (e.g., other tabs or independent components using the same persistence layer).
23
+ *
24
+ * @param id The **unique identifier of the *consumer instance* subscribing**. This allows the persistence implementation to filter out notifications that were initiated by the subscribing instance itself.
25
+ * @param callback The function to call when the global persisted data changes from *another* source. The new state (`T`) is passed as an argument to this callback.
26
+ * @returns A function that, when called, will unsubscribe the provided callback from future updates. Call this when your component or instance is no longer active to prevent memory leaks.
27
+ */
28
+ subscribe(id: string, callback: (state: T) => void): () => void;
29
+ /**
30
+ * Clears (removes) the entire global persisted data from storage.
31
+ *
32
+ * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations, this returns a `Promise<boolean>`.
33
+ */
34
+ clear(): boolean | Promise<boolean>;
35
+ /**
36
+ * Returns metadata about the persistence layer.
37
+ *
38
+ * This is useful for distinguishing between multiple apps running on the same host
39
+ * (e.g., several apps served at `localhost:3000` that share the same storage key).
40
+ *
41
+ * @returns An object containing:
42
+ * - `version`: The semantic version string of the persistence schema or application.
43
+ * - `id`: A unique identifier for the application using this persistence instance.
44
+ */
45
+ stats(): {
46
+ version: string;
47
+ id: string;
48
+ };
49
+ }
50
+ //#endregion
51
+ //#region src/events/types.d.ts
52
+ /**
53
+ * Interface defining the shape of the EventBus.
54
+ * @template TEventMap - A record mapping event names to their respective payload types.
55
+ */
56
+ interface EventBus<TEventMap extends Record<string, any>> {
57
+ /**
58
+ * Subscribes to a specific event by name.
59
+ * @param eventName - The name of the event to subscribe to.
60
+ * @param callback - The function to call when the event is emitted.
61
+ * @param options - Extra options to determine the behaviour of the
62
+ * subscription
63
+ * @returns A function to unsubscribe from the event.
64
+ */
65
+ subscribe<TEventName extends keyof TEventMap | "*">(eventName: TEventName, callback: TEventName extends "*" ? (payload: TEventMap[keyof TEventMap], event: keyof TEventMap) => void : (payload: TEventMap[TEventName]) => void, options?: SubscribeOptions): () => void;
66
+ /**
67
+ * Subscribes to an event and automatically unsubscribes after it fires once.
68
+ * @param eventName - The name of the event to subscribe to.
69
+ * @param callback - The function to call when the event is emitted.
70
+ * @returns A function to cancel the one-shot subscription before it fires.
71
+ */
72
+ once<TEventName extends keyof TEventMap | "*">(eventName: TEventName, callback: TEventName extends "*" ? (payload: TEventMap[keyof TEventMap], event: keyof TEventMap) => void : (payload: TEventMap[TEventName]) => void, options?: SubscribeOptions): () => void;
73
+ /**
74
+ * Emits an event with a payload to all subscribed listeners.
75
+ * @param event - An object containing the event name and payload.
76
+ */
77
+ emit: <TEventName extends keyof TEventMap>(event: {
78
+ name: TEventName;
79
+ payload: TEventMap[TEventName];
80
+ }) => void;
81
+ /**
82
+ * Retrieves metrics about event bus usage.
83
+ * @returns An object containing various metrics.
84
+ */
85
+ metrics: () => EventMetrics;
86
+ /**
87
+ * Clears all subscriptions and resets metrics.
88
+ *
89
+ * After calling `clear()`, the bus is fully reset and can be reused
90
+ * cross-tab communication is re-established if it was previously enabled.
91
+ *
92
+ * @param options - Optional configuration object.
93
+ * @param options.permanent - If `true`, the bus becomes permanently unusable after clearing.
94
+ * Defaults to `false`.
95
+ * @returns {void}
96
+ */
97
+ clear: (options?: {
98
+ permanent?: boolean;
99
+ }) => void;
100
+ }
101
+ /**
102
+ * Interface defining the metrics tracked by the EventBus.
103
+ */
104
+ interface EventMetrics {
105
+ /** Total number of events emitted (both sync and deferred paths). */
106
+ totalEvents: number;
107
+ /** Number of active subscriptions across all event names. */
108
+ activeSubscriptions: number;
109
+ /** Map of event names to their emission counts. */
110
+ eventCounts: Map<string, number>;
111
+ /** Average duration of event dispatch in milliseconds. */
112
+ averageEmitDuration: number;
113
+ }
114
+ interface SubscribeOptions {
115
+ /**
116
+ * Debounce delay in milliseconds. When multiple events arrive in quick
117
+ * succession, the callback runs only after the quiet period ends, using the
118
+ * latest payload. Default = no debouncing.
119
+ */
120
+ debounce?: number;
121
+ }
122
+ //#endregion
123
+ //#region src/store/types.d.ts
124
+ /**
125
+ * Utility type for representing partial updates to the state, allowing deep nesting.
126
+ * It makes all properties optional and applies the same transformation recursively
127
+ * to nested objects, allowing for selective updates while
128
+ * preserving the original structure. It also includes the original type T and
129
+ * undefined as possibilities for the top level and nested values.
130
+ */
131
+ type DeepPartial<T> = T extends object ? T extends readonly (infer U)[] ? readonly (DeepPartial<U> | undefined)[] | undefined | T : T extends (infer U)[] ? (DeepPartial<U> | undefined)[] | undefined | T : { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> | undefined : T[K] | undefined } | undefined | T : T | undefined | symbol;
132
+ /**
133
+ * Interface for performance and execution metrics of the state store.
134
+ */
135
+ interface StoreMetrics {
136
+ /** The number of times the state has been successfully updated. */
137
+ updateCount: number;
138
+ /** The total number of listener functions executed in response to state changes. */
139
+ listenerExecutions: number;
140
+ /** The average time taken for a state update process to complete (in milliseconds). */
141
+ averageUpdateTime: number;
142
+ /** The size (e.g., number of paths changed) of the largest single state update. */
143
+ largestUpdateSize: number;
144
+ /** List of state paths that trigger the most listener executions. */
145
+ mostActiveListenerPaths: string[];
146
+ /** The total number of update attempts (including blocked ones). */
147
+ totalUpdates: number;
148
+ /** The number of updates that were blocked by blocking middleware. */
149
+ blockedUpdates: number;
150
+ /** The average duration of a state update cycle (in milliseconds). */
151
+ averageUpdateDuration: number;
152
+ /** The total number of middleware functions executed. */
153
+ middlewareExecutions: number;
154
+ /** The total number of transactions initiated. */
155
+ transactionCount: number;
156
+ /** The total number of store events fired. */
157
+ totalEventsFired: number;
158
+ /** The total number of actions dispatched. */
159
+ totalActionsDispatched: number;
160
+ /** The total number of actions that completed successfully. */
161
+ totalActionsSucceeded: number;
162
+ /** The total number of actions that failed with an error. */
163
+ totalActionsFailed: number;
164
+ /** The average duration of an action execution (in milliseconds). */
165
+ averageActionDuration: number;
166
+ }
167
+ /**
168
+ * Extended store state for monitoring the current execution status (e.g., if an update is in progress).
169
+ */
170
+ interface StoreExecutionState<T> {
171
+ /** Indicates if a state update process is currently executing. */
172
+ executing: boolean;
173
+ /** The changes (DeepPartial) currently being processed in the execution cycle. Null if none. */
174
+ changes: DeepPartial<T> | null;
175
+ /** A queue of pending state update functions/objects to be applied sequentially. */
176
+ pendingChanges: Array<StateUpdater<T>>;
177
+ /** Names of all currently registered middlewares. */
178
+ middlewares: string[];
179
+ /** Details of the middleware currently running. Null if none. */
180
+ runningMiddleware: {
181
+ id: string;
182
+ name: string;
183
+ startTime: number;
184
+ } | null;
185
+ /** Indicates if the store is currently within an active transaction block. */
186
+ transactionActive: boolean;
187
+ }
188
+ /**
189
+ * Event types emitted by the state store for observability and debugging.
190
+ */
191
+ type StoreEvent = "update:start" | "update:complete" | "middleware:start" | "middleware:complete" | "middleware:error" | "middleware:blocked" | "middleware:executed" | "transaction:start" | "transaction:complete" | "transaction:error" | "persistence:ready" | "persistence:queued" | "persistence:success" | "persistence:retry" | "persistence:failed" | "persistence:queue_cleared" | "persistence:init_error" | "action:start" | "action:complete" | "action:error" | "selector:accessed" | "selector:changed";
192
+ /**
193
+ * Payload for the 'selector:changed' event.
194
+ */
195
+ interface SelectorChangedPayload<S> {
196
+ /** Unique identifier of the selector. */
197
+ selectorId: string;
198
+ /** The new computed result of the selector. */
199
+ newResult: S;
200
+ /** Timestamp of when the change occurred. */
201
+ timestamp: number;
202
+ }
203
+ /**
204
+ * Maps each `StoreEvent` type to its corresponding event payload interface.
205
+ * Uses conditional types to ensure type safety for event listeners.
206
+ */
207
+ type StoreEvents = { [K in StoreEvent]: K extends "update:complete" ? {
208
+ /** List of state changes (deltas) applied in the update. */deltas: StateDelta[]; /** Total duration of the update process (in milliseconds). */
209
+ duration: number; /** Timestamp of the update completion. */
210
+ timestamp: number; /** Optional ID of the action that triggered the update. */
211
+ actionId?: string; /** The resulting new state after the update (may be a partial/transformed state). */
212
+ newState: any; /** True if the update was blocked by a middleware. */
213
+ blocked?: boolean; /** Any error that occurred during the update. */
214
+ error?: any;
215
+ } : K extends "selector:accessed" ? SelectorAccessedPayload : K extends "selector:changed" ? SelectorChangedPayload<any> : K extends "action:start" ? ActionStartPayload : K extends "action:complete" ? ActionCompletePayload : K extends "action:error" ? ActionErrorPayload : K extends "middleware:start" | "middleware:complete" | "middleware:error" | "middleware:blocked" | "middleware:executed" ? MiddlewareExecution : K extends "transaction:start" | "transaction:complete" | "transaction:error" ? {
216
+ transactionId: string;
217
+ timestamp: number;
218
+ } : K extends "persistence:queued" ? PersistenceQueuedPayload : K extends "persistence:success" ? PersistenceSuccessPayload : K extends "persistence:retry" ? PersistenceRetryPayload : K extends "persistence:failed" ? PersistenceFailedPayload : K extends "persistence:queue_cleared" ? PersistenceQueueClearedPayload : K extends "persistence:init_error" ? PersistenceInitErrorPayload : any };
219
+ /**
220
+ * Payload for the 'selector:accessed' event.
221
+ */
222
+ interface SelectorAccessedPayload {
223
+ /** Unique identifier of the selector. */
224
+ selectorId: string;
225
+ /** List of state paths accessed during the selector computation. */
226
+ accessedPaths: string[];
227
+ /** Duration of the selector computation (in milliseconds). */
228
+ duration: number;
229
+ /** Timestamp of the access. */
230
+ timestamp: number;
231
+ }
232
+ /**
233
+ * Payload for the 'action:start' event.
234
+ */
235
+ interface ActionStartPayload {
236
+ /** Unique identifier for the action execution. */
237
+ actionId: string;
238
+ /** Name of the action function. */
239
+ name: string;
240
+ /** The parameters passed to the action function. */
241
+ params: any[];
242
+ /** Timestamp of when the action execution started. */
243
+ timestamp: number;
244
+ }
245
+ /**
246
+ * Payload for the 'action:complete' event (successful action execution).
247
+ */
248
+ interface ActionCompletePayload {
249
+ /** Unique identifier for the action execution. */
250
+ actionId: string;
251
+ /** Name of the action function. */
252
+ name: string;
253
+ /** The parameters passed to the action function. */
254
+ params: any[];
255
+ /** Timestamp of when the action execution started. */
256
+ startTime: number;
257
+ /** Timestamp of when the action execution completed. */
258
+ endTime: number;
259
+ /** Total duration of the action execution (in milliseconds). */
260
+ duration: number;
261
+ /** The result returned by the action function. */
262
+ result: any;
263
+ }
264
+ /**
265
+ * Payload for the 'action:error' event (failed action execution).
266
+ */
267
+ interface ActionErrorPayload {
268
+ /** Unique identifier for the action execution. */
269
+ actionId: string;
270
+ /** Name of the action function. */
271
+ name: string;
272
+ /** The parameters passed to the action function. */
273
+ params: any[];
274
+ /** Timestamp of when the action execution started. */
275
+ startTime: number;
276
+ /** Timestamp of when the action execution ended (with error). */
277
+ endTime: number;
278
+ /** Total duration of the action execution (in milliseconds). */
279
+ duration: number;
280
+ /** The error object. */
281
+ error: any;
282
+ }
283
+ /**
284
+ * Type for a generic middleware function.
285
+ * It receives the current state and the incoming update, and can return
286
+ * a modified `DeepPartial<T>` (transforming the update) or `void`.
287
+ */
288
+ type Middleware<T> = (state: T, update: DeepPartial<T>) => Promise<DeepPartial<T>> | Promise<void> | DeepPartial<T> | void;
289
+ /**
290
+ * Middleware execution information for event emissions and tracking.
291
+ */
292
+ interface MiddlewareExecution {
293
+ /** Unique identifier for the middleware instance. */
294
+ id: string;
295
+ /** Name of the middleware. */
296
+ name: string;
297
+ /** Timestamp of when the middleware execution started. */
298
+ startTime: number;
299
+ /** Timestamp of when the middleware execution completed. */
300
+ endTime: number;
301
+ /** Total duration of the middleware execution (in milliseconds). */
302
+ duration: number;
303
+ /** True if the middleware blocked the update. */
304
+ blocked: boolean;
305
+ /** Error object if the middleware failed. */
306
+ error?: Error;
307
+ /** List of state changes (deltas) that resulted from this middleware's transformation. */
308
+ deltas: StateDelta[];
309
+ }
310
+ /**
311
+ * Represents a single change to the state, detailing the path, old value, and new value.
312
+ */
313
+ interface StateDelta {
314
+ /** Dot-separated path to the changed property (e.g., "user.profile.name"). */
315
+ path: string;
316
+ /** The value of the property *before* the update. */
317
+ oldValue: any;
318
+ /** The value of the property *after* the update. */
319
+ newValue: any;
320
+ }
321
+ /**
322
+ * Represents a state update, which can be:
323
+ * 1. The full new state (`T`).
324
+ * 2. A partial update object (`DeepPartial<T>`).
325
+ * 3. A function that receives the current state and returns a partial update (sync or async).
326
+ */
327
+ type StateUpdater<T> = T | DeepPartial<T> | ((state: T) => DeepPartial<T> | Promise<DeepPartial<T>>);
328
+ /**
329
+ * A unique symbol used within DeepPartial objects to explicitly signal that a property
330
+ * should be deleted from the state object.
331
+ */
332
+ declare const DELETE_SYMBOL: any;
333
+ /**
334
+ * Core types for the reactive data store
335
+ */
336
+ /**
337
+ * Type for a Transform Middleware function.
338
+ * It modifies (transforms) the incoming changes and must return a `DeepPartial<T>`.
339
+ */
340
+ type TransformMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<DeepPartial<T>> | DeepPartial<T>;
341
+ /**
342
+ * Type for a Blocking Middleware function.
343
+ * It determines whether the state update should proceed or be blocked.
344
+ * It returns a boolean or an object containing a `block` boolean and an optional `error`.
345
+ */
346
+ type BlockingMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<boolean | {
347
+ block: boolean;
348
+ error?: Error;
349
+ }> | boolean | {
350
+ block: boolean;
351
+ error?: Error;
352
+ };
353
+ /**
354
+ * Type representing the configuration object passed to the `use` method to register a middleware.
355
+ */
356
+ interface MiddlewareConfig<T> {
357
+ /** The middleware function (can be a transform or blocking middleware). */
358
+ action: TransformMiddleware<T> | BlockingMiddleware<T>;
359
+ /** An optional, human-readable name for the middleware. */
360
+ name?: string;
361
+ /** If true, the middleware is treated as a blocking middleware (must return a boolean or `{ block: boolean }`). */
362
+ block?: boolean;
363
+ }
364
+ /**
365
+ * Interface for a reactive selector result, providing access to the value and subscription capabilities.
366
+ */
367
+ interface ReactiveSelector<S> {
368
+ /** Unique identifier for the selector. */
369
+ id: string;
370
+ /** Function to get the current computed value of the selector. */
371
+ get: () => S;
372
+ /**
373
+ * Subscribes a callback function to run whenever the selector's result changes.
374
+ * Returns an unsubscribe function.
375
+ */
376
+ subscribe: (callback: (state: S) => void) => () => void;
377
+ }
378
+ interface ActionWatcher {
379
+ /** Unique identifier for the action */
380
+ name: string;
381
+ /** Function to get the current computed value of the action. */
382
+ status: () => boolean;
383
+ /**
384
+ * Subscribes a callback function to run whenever the action's status changes.
385
+ * Returns an unsubscribe function.
386
+ */
387
+ subscribe: (callback: () => void) => () => void;
388
+ }
389
+ interface TransactionOptions {
390
+ /** If true, blocks resolution until changes are fully committed to the database row */
391
+ flush?: boolean;
392
+ }
393
+ /**
394
+ * Interface defining the contract for the core data state store.
395
+ * T must be an object type.
396
+ */
397
+ interface DataStore<T extends object> {
398
+ /**
399
+ * Gets the current state of the store.
400
+ * @param clone If true, returns a deep clone of the state; otherwise, returns the internal state reference.
401
+ * @returns The current state T.
402
+ */
403
+ get(clone?: boolean): T;
404
+ /**
405
+ * Gets a subset of the store.
406
+ * @param paths The paths which to include in the returned object.
407
+ * @param separator Optional separator for paths. Defaults to `.` .
408
+ * @returns An object of the shape K mapping paths to their current values.
409
+ */
410
+ subset<K extends Record<string, any> = Record<string, any>>(paths: Array<string>, separator?: string): K;
411
+ /**
412
+ * Registers a named action function that can modify the state.
413
+ * @param action The action configuration object.
414
+ * @returns A function to unregister the action.
415
+ */
416
+ register<R extends any[]>(action: {
417
+ name: string;
418
+ fn: (state: T, ...args: R) => DeepPartial<T> | Promise<DeepPartial<T>>;
419
+ debounce?: {
420
+ delay: number;
421
+ condition?: (previous: R, current: R) => boolean;
422
+ };
423
+ }): () => void;
424
+ /**
425
+ * Executes (dispatches) a previously registered action by its name.
426
+ * @param name The name of the action.
427
+ * @param args The parameters to pass to the action function.
428
+ * @returns A promise that resolves to the final state after the action and subsequent updates are complete.
429
+ */
430
+ dispatch<R extends any[]>(name: string, ...args: R): Promise<T>;
431
+ /**
432
+ * Sets or updates the state using a StateUpdater.
433
+ * @param update The new state, partial state, or a function returning a partial state.
434
+ * @param options Configuration options for the set operation.
435
+ * @returns A promise that resolves to the current state when the update is complete.
436
+ */
437
+ set(update: StateUpdater<T>, options?: {
438
+ force?: boolean;
439
+ actionId?: string;
440
+ }): Promise<T>;
441
+ /**
442
+ * Creates a reactive selector that computes a derived value and tracks dependencies.
443
+ * @param selector A function to compute the derived state value S from the full state T.
444
+ * @returns A `ReactiveSelector<S>` object.
445
+ */
446
+ select<S>(selector: (state: T) => S): ReactiveSelector<S>;
447
+ /**
448
+ * Subscribes a callback to run when the data at the specified path(s) changes.
449
+ * @param path A single path string or an array of path strings to watch.
450
+ * @param callback The function to execute when a change occurs in the watched path(s).
451
+ * @param options Extra options to pass to the event bus
452
+ * @returns An unsubscribe function.
453
+ */
454
+ watch(path: string | Array<string>, callback: (state: T) => void, options?: SubscribeOptions): () => void;
455
+ /**
456
+ * Subscribes to execution‑status changes of a registered action.
457
+ *
458
+ * The provided callback is called **every time** the action transitions
459
+ * between idle and running (i.e. on `action:start`, `action:complete`, or
460
+ * `action:error` for the given name). The current status can also be read
461
+ * synchronously with `isActionRunning(name)`.
462
+ *
463
+ * **Deferred listener teardown**
464
+ * To avoid unnecessary churn when subscriptions are rapidly created and
465
+ * destroyed, the underlying event listeners are not removed immediately
466
+ * on unsubscribe. Instead, a *pending reset* is queued via `queueMicrotask`.
467
+ * If a new subscription for the same action arrives before that microtask
468
+ * executes, the reset is silently cancelled and the already‑established
469
+ * listeners are reused. This keeps the subscription infrastructure stable
470
+ * and prevents cascading notifications that could otherwise arise from
471
+ * repeated subscribe‑unsubscribe‑subscribe cycles.
472
+ *
473
+ * @param name - The name of the action to watch.
474
+ * @returns An ActionWatcher
475
+ */
476
+ watchAction(name: string): ActionWatcher;
477
+ /**
478
+ * Executes an operation function within a transaction block.
479
+ * All state updates (`set` or actions) within the transaction are batched and applied atomically (all or nothing).
480
+ * @param operation The function containing the state updates.
481
+ * @returns A promise that resolves to the return value of the operation function.
482
+ */
483
+ transaction<R>(operation: () => R | Promise<R>, options?: TransactionOptions): Promise<R>;
484
+ /**
485
+ * Registers a middleware function to intercept state updates.
486
+ * @param props The middleware configuration.
487
+ * @returns A function to unregister the middleware.
488
+ */
489
+ use(props: MiddlewareConfig<T>): () => boolean;
490
+ /**
491
+ * Subscribes a listener to a specific store event type.
492
+ * @param event The type of store event to listen for.
493
+ * @param listener The callback function to execute when the event fires.
494
+ * @returns An unsubscribe function.
495
+ */
496
+ on(event: StoreEvent, listener: (data: any) => void): () => void;
497
+ /**
498
+ * Returns the unique identifier of the store instance.
499
+ */
500
+ id(): string;
501
+ /**
502
+ * Checks whether the store is fully initialized and ready for use.
503
+ */
504
+ isReady(): boolean;
505
+ /**
506
+ * Returns a promise that resolves once the store is fully initialised.
507
+ * Safe to call multiple times — all callers share the same latch.
508
+ *
509
+ * @param timeout - Optional maximum wait time in milliseconds.
510
+ * @throws {TimeoutError} If the store does not become ready within the timeout.
511
+ *
512
+ * @example
513
+ * await store.ready();
514
+ * const state = store.get();
515
+ */
516
+ ready(timeout?: number): Promise<void>;
517
+ /**
518
+ * Returns a readonly snapshot of the current execution state of the store.
519
+ */
520
+ state(): Readonly<StoreExecutionState<T>>;
521
+ /**
522
+ * Releases all resources held by the store and renders it unusable
523
+ */
524
+ dispose(): Promise<void>;
525
+ }
526
+ /** Payload for the 'persistence:queued' event. */
527
+ interface PersistenceQueuedPayload {
528
+ /** Unique ID for the persistence task. */
529
+ taskId: string;
530
+ /** Paths that were changed and triggered persistence. */
531
+ changedPaths: string[];
532
+ /** The current number of tasks waiting in the persistence queue. */
533
+ queueSize: number;
534
+ /** Timestamp of when the task was queued. */
535
+ timestamp: number;
536
+ }
537
+ /** Payload for the 'persistence:success' event. */
538
+ interface PersistenceSuccessPayload {
539
+ /** Unique ID for the persistence task. */
540
+ taskId: string;
541
+ /** Paths that were successfully persisted. */
542
+ changedPaths: string[];
543
+ /** Duration of the persistence operation (in milliseconds). */
544
+ duration: number;
545
+ /** Timestamp of the success. */
546
+ timestamp: number;
547
+ }
548
+ /** Payload for the 'persistence:retry' event. */
549
+ interface PersistenceRetryPayload {
550
+ /** Unique ID for the persistence task. */
551
+ taskId: string;
552
+ /** Current retry attempt number. */
553
+ attempt: number;
554
+ /** Maximum allowed retries. */
555
+ maxRetries: number;
556
+ /** Time until the next retry attempt (in milliseconds). */
557
+ nextRetryIn: number;
558
+ /** The error that triggered the retry. */
559
+ error: any;
560
+ /** Timestamp of the retry event. */
561
+ timestamp: number;
562
+ }
563
+ /** Payload for the 'persistence:failed' event. */
564
+ interface PersistenceFailedPayload {
565
+ /** Unique ID for the persistence task. */
566
+ taskId: string;
567
+ /** Paths that failed to persist. */
568
+ changedPaths: string[];
569
+ /** Total number of attempts made. */
570
+ attempts: number;
571
+ /** The final error object. */
572
+ error: any;
573
+ /** Timestamp of the final failure. */
574
+ timestamp: number;
575
+ }
576
+ /** Payload for the 'persistence:queue_cleared' event. */
577
+ interface PersistenceQueueClearedPayload {
578
+ /** The number of persistence tasks that were cleared from the queue. */
579
+ clearedTasks: number;
580
+ /** Timestamp of when the queue was cleared. */
581
+ timestamp: number;
582
+ }
583
+ /** Payload for the 'persistence:init_error' event. */
584
+ interface PersistenceInitErrorPayload {
585
+ /** The error that occurred during persistence initialization. */
586
+ error: any;
587
+ /** Timestamp of the error. */
588
+ timestamp: number;
589
+ }
590
+ /**
591
+ * Interface describing a registered state action, including its metadata and debounce configuration.
592
+ */
593
+ type StoreAction<T, R extends any[] = any[]> = {
594
+ /** Unique identifier for the action definition. */id: string; /** Name of the action, used for dispatching. */
595
+ name: string; /** The actual function that takes state and arguments, and returns a state update. */
596
+ action: (state: T, ...args: R) => DeepPartial<T> | Promise<DeepPartial<T>>; /** Optional configuration for debouncing action execution. */
597
+ debounce?: {
598
+ /** Active timer reference, if debouncing */timer?: ReturnType<typeof setTimeout>; /** Debounce delay in milliseconds */
599
+ delay: number; /** Optional condition to decide whether to debounce based on previous vs current args */
600
+ condition?: (previous: R | undefined, current: R) => boolean; /** Last call’s arguments, used for condition checks */
601
+ args?: R; /** Internal promise resolvers to prevent memory leaks */
602
+ resolve?: (value: any) => void;
603
+ reject?: (reason?: any) => void;
604
+ };
605
+ };
606
+ //#endregion
607
+ //#region src/logger/logger.d.ts
608
+ /**
609
+ * Represents the severity level of a system log entry.
610
+ * Levels are ordered by increasing severity: trace, debug, info, warn, error.
611
+ */
612
+ type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
613
+ /**
614
+ * Structure representing a fully contextualized system log entry ready for sinking.
615
+ */
616
+ interface SystemLog {
617
+ /** The severity level of the log. */
618
+ level: LogLevel;
619
+ /** A clear, human-readable string identifying the distinct event (e.g., "user_login_failed"). */
620
+ event: string;
621
+ /** Additional structured data specific to this log instantiation. */
622
+ data?: object;
623
+ /** Contextual data shared across the logger instance (e.g., traceIds, environment). */
624
+ context?: object;
625
+ /** Epoch timestamp in milliseconds denoting when the log event occurred. */
626
+ timestamp: number;
627
+ }
628
+ /**
629
+ * Primary logger interface providing level-specific log dispatching and context-chaining.
630
+ */
631
+ interface SystemLogger {
632
+ /** Logs high-volume, extremely fine-grained diagnostic details. */
633
+ trace(event: string, data?: object): void;
634
+ /** Logs diagnostic information useful during local development or debugging. */
635
+ debug(event: string, data?: object): void;
636
+ /** Logs standard operational events that track the healthy flow of the system. */
637
+ info(event: string, data?: object): void;
638
+ /** Alias for the `info` logging method. */
639
+ log(event: string, data?: object): void;
640
+ /** Logs non-fatal operational anomalies or conditions that deserve attention. */
641
+ warn(event: string, data?: object): void;
642
+ /** Logs critical errors, failures, or exceptions preventing a transaction/process. */
643
+ error(event: string, data?: unknown): void;
644
+ /**
645
+ * Directly forwards a pre-constructed `SystemLog` record through the logger's pipeline.
646
+ * Combines instance context before outputting.
647
+ */
648
+ write(record: SystemLog): void;
649
+ /**
650
+ * Generates a new `SystemLogger` instance that shares the existing sinks and parent
651
+ * context, deeply merging the newly provided context on top.
652
+ *
653
+ * @param context - The metadata to append to all subsequent logs emitted by the child logger.
654
+ */
655
+ child(context: object): SystemLogger;
656
+ }
657
+ //#endregion
658
+ //#region src/store/logger.d.ts
659
+ type StoreLogger = SystemLogger;
660
+ declare function createStoreLogger(logger?: StoreLogger): StoreLogger;
661
+ //#endregion
662
+ //#region src/store/store.d.ts
663
+ type ReactiveDataStoreOptions<T> = {
664
+ timeout?: number;
665
+ state?: T;
666
+ persistence?: SimplePersistence<T>;
667
+ deleteMarker?: symbol;
668
+ logger?: StoreLogger;
669
+ options?: {
670
+ persistenceMaxRetries?: number;
671
+ persistenceRetryDelay?: number;
672
+ };
673
+ };
674
+ /**
675
+ * Main ReactiveDataStore - a robust, type-safe state management solution.
676
+ * It features optimistic updates, a Serializer-based update queue for safe serial
677
+ * execution with backpressure, a Latch for async readiness gating, and decoupled
678
+ * persistence.
679
+ *
680
+ * @template T The type of the data object managed by the store.
681
+ */
682
+ declare class ReactiveDataStore<T extends object> implements DataStore<T> {
683
+ /** Manages the core application state. */
684
+ private coreState;
685
+ /** Orchestrates and executes middleware for state changes. */
686
+ private middlewareEngine;
687
+ /** Manages saving state changes to a persistence layer. */
688
+ private persistenceHandler;
689
+ /** Manages atomic state updates via transactions. */
690
+ private transactionManager;
691
+ /** Collects and provides performance metrics for the store. */
692
+ private metricsCollector;
693
+ private selectorManager;
694
+ private actions;
695
+ /**
696
+ * Serializer enforces FIFO serial execution of all state updates.
697
+ *
698
+ * Replaces the bare `Promise<T | void>` chain. Benefits over the old pattern:
699
+ * - Backpressure: rejects when the queue exceeds capacity rather than growing
700
+ * unboundedly under write pressure.
701
+ * - Clean shutdown: `close()` in dispose() immediately rejects any subsequent
702
+ * `set()` calls with a clear error instead of silently enqueuing them.
703
+ * - Observability: `updateSerializer.running()` and `updateSerializer.pending()`
704
+ * replace the manually-managed `executionState.executing` flag.
705
+ * - Error isolation: errors in one update do not corrupt the queue — the
706
+ * Serializer's mutex is always released in its own `finally` block.
707
+ */
708
+ private updateSerializer;
709
+ /**
710
+ * Latch that opens once the store is fully initialised (persistence loaded).
711
+ *
712
+ * Replaces the poll-only `isReady(): boolean` pattern. Callers can now
713
+ * `await store.ready()` with an optional timeout rather than polling or
714
+ * subscribing to an internal event. `isReady()` is preserved as `latch.isOpen()`
715
+ * for synchronous checks and backwards compatibility.
716
+ */
717
+ private readyLatch;
718
+ private disposeOnce;
719
+ private updateBus;
720
+ private eventBus;
721
+ private executionState;
722
+ private instanceID;
723
+ private merge;
724
+ private diff;
725
+ private logger;
726
+ /**
727
+ * Creates a new ReactiveDataStore instance.
728
+ */
729
+ constructor(initialData: T, persistence?: SimplePersistence<T>, deleteMarker?: symbol, options?: {
730
+ persistenceMaxRetries?: number;
731
+ persistenceRetryDelay?: number;
732
+ broadcastChannel?: string;
733
+ logger?: StoreLogger;
734
+ });
735
+ /**
736
+ * Returns true if the store has finished initialising (persistence loaded).
737
+ * For async flows, prefer `await store.ready()` over polling this.
738
+ */
739
+ isReady(): boolean;
740
+ /**
741
+ * Returns a promise that resolves once the store is fully initialised.
742
+ * Safe to call multiple times — all callers share the same latch.
743
+ *
744
+ * @param timeout - Optional maximum wait time in milliseconds.
745
+ * @throws {TimeoutError} If the store does not become ready within the timeout.
746
+ *
747
+ * @example
748
+ * await store.ready();
749
+ * const state = store.get();
750
+ */
751
+ ready(timeout?: number): Promise<void>;
752
+ state(): Readonly<StoreExecutionState<T>>;
753
+ /**
754
+ * Gets the current state. Optimized default to return reference (false) for performance.
755
+ * @param clone If `true`, returns a deep clone (use sparingly).
756
+ * @returns The current state object.
757
+ */
758
+ get(clone?: boolean): T;
759
+ subset<K extends Record<string, any>>(paths: Array<string>, separator?: string): K;
760
+ select<S>(selector: (state: T) => S): ReactiveSelector<S>;
761
+ register<R extends any[]>(action: {
762
+ name: string;
763
+ fn: (state: T, ...args: R) => DeepPartial<T> | Promise<DeepPartial<T>>;
764
+ debounce?: {
765
+ delay: number;
766
+ condition?: (previous: R | undefined, current: R) => boolean;
767
+ };
768
+ }): () => void;
769
+ dispatch<R extends any[]>(name: string, ...params: R): Promise<T>;
770
+ /**
771
+ * Enqueues a state update for serial execution.
772
+ *
773
+ * Uses a `Serializer` internally, which guarantees:
774
+ * - FIFO ordering of all updates.
775
+ * - No concurrent execution — each update waits for the previous to complete.
776
+ * - Backpressure: throws if the queue exceeds capacity.
777
+ * - Clean rejection after `dispose()`.
778
+ *
779
+ * @returns A Promise that resolves with the new state T.
780
+ */
781
+ set(update: StateUpdater<T>, options?: {
782
+ force?: boolean;
783
+ actionId?: string;
784
+ }): Promise<T>;
785
+ /**
786
+ * Internal logic for performing a single, sequential state update.
787
+ * Always called inside the Serializer — never call directly.
788
+ */
789
+ private _performUpdate;
790
+ /**
791
+ * Opens the readyLatch once the persistence layer signals it is ready.
792
+ * The latch can only open once — subsequent `persistence:ready` events are no-ops.
793
+ */
794
+ private setupReadyLatch;
795
+ private setupPersistenceListener;
796
+ watch(path: string | Array<string>, callback: (state: T) => void, options?: SubscribeOptions): () => void;
797
+ /**
798
+ * Subscribes to execution‑status changes of a registered action.
799
+ *
800
+ * The provided callback is called **every time** the action transitions
801
+ * between idle and running (i.e. on `action:start`, `action:complete`, or
802
+ * `action:error` for the given name). The current status can also be read
803
+ * synchronously with `isActionRunning(name)`.
804
+ *
805
+ * **Deferred listener teardown**
806
+ * To avoid unnecessary churn when subscriptions are rapidly created and
807
+ * destroyed, the underlying event listeners are not removed immediately
808
+ * on unsubscribe. Instead, a *pending reset* is queued via `queueMicrotask`.
809
+ * If a new subscription for the same action arrives before that microtask
810
+ * executes, the reset is silently cancelled and the already‑established
811
+ * listeners are reused. This keeps the subscription infrastructure stable
812
+ * and prevents cascading notifications that could otherwise arise from
813
+ * repeated subscribe‑unsubscribe‑subscribe cycles.
814
+ *
815
+ * @param name - The name of the action to watch.
816
+ * @returns ActionWatcher
817
+ */
818
+ watchAction(name: string): {
819
+ name: string;
820
+ status: () => boolean;
821
+ subscribe: (_: () => void) => () => void;
822
+ };
823
+ /**
824
+ * Creates a debounced version of `set()` using a `Debouncer`.
825
+ *
826
+ * Useful for high-frequency write sources (e.g. text input, scroll position)
827
+ * where you want to collapse rapid updates into a single state write after a
828
+ * quiet period.
829
+ *
830
+ * @param delay - Quiet period in milliseconds before the update is applied.
831
+ * @param leading - If true, also applies the first update immediately.
832
+ * @returns A debounced setter function with the same signature as `set()`.
833
+ *
834
+ * @example
835
+ * const debouncedSet = store.debouncedSetter({ delay: 200 });
836
+ * inputEl.addEventListener("input", (e) => {
837
+ * debouncedSet((s) => ({ ...s, query: e.target.value }));
838
+ * });
839
+ */
840
+ debouncedSetter(options: {
841
+ delay: number;
842
+ leading?: boolean;
843
+ }): (update: StateUpdater<T>, setOptions?: {
844
+ force?: boolean;
845
+ actionId?: string;
846
+ }) => void;
847
+ id(): string;
848
+ transaction<R>(operation: () => R | Promise<R>, options?: TransactionOptions): Promise<R>;
849
+ use(props: MiddlewareConfig<T>): () => boolean;
850
+ metrics(): StoreMetrics;
851
+ on(event: StoreEvent, listener: (data: any) => void): () => void;
852
+ getPersistenceStatus(): {
853
+ queueSize: number;
854
+ isProcessing: boolean;
855
+ pendingRetries: number;
856
+ oldestTask?: number;
857
+ };
858
+ flush(): Promise<void>;
859
+ /**
860
+ * Discards all pending persistence tasks.
861
+ * WARNING: Any queued writes not yet persisted will be lost.
862
+ * Call flushPersistence() first if writes must not be lost.
863
+ */
864
+ discardPersistenceQueue(): void;
865
+ /**
866
+ * Disposes the store and all owned resources.
867
+ *
868
+ * Closes the update Serializer — any `set()` calls after dispose() will
869
+ * reject immediately with `SerializerExecutionDone` rather than silently
870
+ * enqueuing work against a dead store.
871
+ */
872
+ dispose(): Promise<void>;
873
+ private checkDisposed;
874
+ disposed(): boolean;
875
+ private emit;
876
+ }
877
+ //#endregion
878
+ //#region src/store/registry.d.ts
879
+ /**
880
+ * Configuration options for the StoreRegistry.
881
+ */
882
+ interface StoreRegistryOptions {
883
+ /**
884
+ * Optional callback fired when a store is actively garbage collected.
885
+ * Highly recommended for production telemetry and memory leak debugging.
886
+ */
887
+ onEvict?: (storeId: string) => void;
888
+ /** Optional logger instance. Defaults to no-op. */
889
+ logger?: StoreLogger;
890
+ }
891
+ /**
892
+ * A memory-safe, single-flight registry for ReactiveDataStores.
893
+ * Uses WeakRefs and FinalizationRegistry to allow stores to be garbage collected
894
+ * when no longer in use, automatically cleaning up internal references.
895
+ */
896
+ declare class StoreRegistry<S extends object> {
897
+ private readonly stores;
898
+ private readonly storeToOnce;
899
+ private readonly finalizer;
900
+ private readonly onEvict?;
901
+ private readonly logger;
902
+ constructor(options?: StoreRegistryOptions);
903
+ /**
904
+ * Get an existing store for storeId, or create a new one via an always-cached Once primitive.
905
+ * Ensures only one instantiation occurs even under concurrent calls.
906
+ * * @param storeId - Unique identifier for the store.
907
+ * @param initialState - The initial state to seed the store if it is created.
908
+ * @param timeout - Optional timeout (ms) for store initialization.
909
+ */
910
+ get(storeId: string, options?: ReactiveDataStoreOptions<S>): Promise<ReactiveDataStore<S>>;
911
+ getSync(storeId: string, options?: ReactiveDataStoreOptions<S>): ReactiveDataStore<S>;
912
+ /**
913
+ * Manually remove a store registry entry, unregistering its finalizer and disposing it.
914
+ * @param storeId - Unique identifier for the store.
915
+ * @returns True if a store was actively removed, false otherwise.
916
+ */
917
+ release(storeId: string): Promise<boolean>;
918
+ /**
919
+ * Clears all stores from the registry, disposes them, and unregisters all finalizers.
920
+ */
921
+ clear(): Promise<void>;
922
+ /**
923
+ * Get the store if it exists and has successfully finished initialization.
924
+ * Does not trigger initialization if the store is missing or pending.
925
+ */
926
+ has(storeId: string): boolean;
927
+ /**
928
+ * Returns the current number of tracked stores.
929
+ * Note: This includes entries that may have lost external references but haven't been GC'd yet.
930
+ */
931
+ get size(): number;
932
+ }
933
+ //#endregion
934
+ //#region src/store/observer.d.ts
935
+ /**
936
+ * @interface DebugEvent
937
+ * @description Interface for the structure of a recorded debug event.
938
+ */
939
+ interface DebugEvent {
940
+ /** The type of store event (e.g., 'update:start', 'action:complete'). */
941
+ type: string;
942
+ /** The timestamp when the event occurred. */
943
+ timestamp: number;
944
+ /** The raw data payload associated with the event, including actionId where applicable. */
945
+ data: any;
946
+ }
947
+ /**
948
+ * @interface Snapshot
949
+ * @description Represents a rich snapshot of the state at a point in time for history tracking.
950
+ */
951
+ interface Snapshot<T> {
952
+ /** The complete state object at the time of the snapshot. */
953
+ state: T;
954
+ /** The timestamp of the state change. */
955
+ timestamp: number;
956
+ /** The list of changes (deltas) that resulted in this state. */
957
+ deltas: StateDelta[];
958
+ }
959
+ /**
960
+ * @interface ObserverSessionData
961
+ * @description Defines the data structure for a saved observer session.
962
+ */
963
+ interface ObserverSessionData<T extends object> {
964
+ /** The chronological history of debug events. */
965
+ eventHistory: DebugEvent[];
966
+ /** The chronological history of state snapshots. */
967
+ stateHistory: Snapshot<T>[];
968
+ }
969
+ /**
970
+ * @interface ObserverOptions
971
+ * @description Configuration options for the observer module.
972
+ */
973
+ interface ObserverOptions {
974
+ /** Maximum number of events to retain in memory. Defaults to 500. */
975
+ maxEvents?: number;
976
+ /** Enables or disables console logging for all events (overridden by 'silent'). Defaults to false. */
977
+ enableConsoleLogging?: boolean;
978
+ /** Maximum number of state snapshots to retain for time-travel. Defaults to 20. */
979
+ maxStateHistory?: number;
980
+ /** Fine-grained control over which event types are logged to the console. */
981
+ logEvents?: {
982
+ updates?: boolean;
983
+ middleware?: boolean;
984
+ transactions?: boolean;
985
+ actions?: boolean;
986
+ selectors?: boolean;
987
+ };
988
+ /** Performance thresholds for triggering console warnings. Values are in milliseconds (ms). */
989
+ performanceThresholds?: {
990
+ updateTime?: number;
991
+ middlewareTime?: number;
992
+ };
993
+ /** If true, suppresses all console output and logging regardless of other options. Defaults to false. */
994
+ silent?: boolean;
995
+ /** Optional logger instance. Defaults to no-op. */
996
+ logger?: StoreLogger;
997
+ }
998
+ /**
999
+ * @class StoreObserver
1000
+ * @description Connects to a DataStore to capture state changes, events, and performance data.
1001
+ * @template T The type of the store's state object.
1002
+ */
1003
+ declare class StoreObserver<T extends object> {
1004
+ protected store: DataStore<T>;
1005
+ private eventHistory;
1006
+ private stateHistory;
1007
+ private unsubscribers;
1008
+ private isTimeTraveling;
1009
+ private devTools;
1010
+ private middlewareExecutions;
1011
+ private activeTransactionCount;
1012
+ private activeBatches;
1013
+ private maxEvents;
1014
+ private maxStateHistory;
1015
+ private enableConsoleLogging;
1016
+ private isSilent;
1017
+ private logEvents;
1018
+ private performanceThresholds;
1019
+ private logger;
1020
+ /**
1021
+ * @param store The DataStore instance to observe.
1022
+ * @param options Configuration options for the observer.
1023
+ */
1024
+ constructor(store: DataStore<T>, options?: ObserverOptions);
1025
+ /**
1026
+ * @private
1027
+ * Centralized logging method. Routes to the structured logger for level-based calls
1028
+ * (log, warn, error, debug) and to raw console for group/table calls which have no
1029
+ * logger equivalent. Respects the `isSilent` flag.
1030
+ * @param method The console method to call ('log', 'warn', 'error', 'group', 'groupEnd', 'table', 'debug').
1031
+ * @param args Arguments to pass to the console/log method.
1032
+ */
1033
+ private _consoleLog;
1034
+ /**
1035
+ * @private
1036
+ * Sets up listeners for all relevant store events.
1037
+ */
1038
+ private setupEventListeners;
1039
+ /**
1040
+ * @private
1041
+ * Records a new state snapshot and manages the state history limit.
1042
+ * @param deltas The state changes that led to this snapshot.
1043
+ */
1044
+ private recordStateSnapshot;
1045
+ /**
1046
+ * @private
1047
+ * Records a debug event and manages the event history limit.
1048
+ * @param type The type of event.
1049
+ * @param data The data payload of the event.
1050
+ */
1051
+ private recordEvent;
1052
+ /**
1053
+ * Returns a cloned copy of the recorded event history.
1054
+ * @returns Array of debug events.
1055
+ */
1056
+ getEventHistory(): DebugEvent[];
1057
+ /**
1058
+ * Returns a cloned copy of the recorded state history (snapshots).
1059
+ * @returns Array of state snapshots.
1060
+ */
1061
+ getStateHistory(): Snapshot<T>[];
1062
+ /**
1063
+ * Returns middleware execution history from the state.
1064
+ * @returns Array of middleware executions.
1065
+ */
1066
+ getMiddlewareExecutions(): MiddlewareExecution[];
1067
+ /**
1068
+ * Returns current transaction status.
1069
+ * @returns Object with transaction status information.
1070
+ */
1071
+ getTransactionStatus(): {
1072
+ activeTransactions: number;
1073
+ activeBatches: string[];
1074
+ };
1075
+ /**
1076
+ * Creates a standard middleware that logs all updates.
1077
+ * @param options Options for the logging middleware.
1078
+ * @returns A middleware function.
1079
+ */
1080
+ createLoggingMiddleware(options?: {
1081
+ logLevel?: "debug" | "info" | "warn";
1082
+ logUpdates?: boolean;
1083
+ }): (state: T, update: DeepPartial<T>) => DeepPartial<T>;
1084
+ /**
1085
+ * Creates a middleware that validates updates against a schema.
1086
+ * Uses the internal `_consoleLog` for warnings.
1087
+ * @param validator Function that validates updates.
1088
+ * @returns A blocking middleware function.
1089
+ */
1090
+ createValidationMiddleware(validator: (state: T, update: DeepPartial<T>) => boolean | {
1091
+ valid: boolean;
1092
+ reason?: string;
1093
+ }): (state: T, update: DeepPartial<T>) => boolean;
1094
+ /**
1095
+ * Returns a simplified view of recent state changes.
1096
+ * @param limit Maximum number of state changes to compare. Defaults to 5.
1097
+ * @returns Array of state difference objects.
1098
+ */
1099
+ getRecentChanges(limit?: number): Array<{
1100
+ timestamp: number;
1101
+ changedPaths: string[];
1102
+ from: Partial<T>;
1103
+ to: Partial<T>;
1104
+ }>;
1105
+ /**
1106
+ * Clears both the event and state history, preserving only the initial state snapshot.
1107
+ */
1108
+ clearHistory(): void;
1109
+ /**
1110
+ * Filters and returns events related to a specific action ID.
1111
+ * @param actionId The ID of the action to filter by.
1112
+ * @returns Array of debug events associated with the action.
1113
+ */
1114
+ getHistoryForAction(actionId: string): DebugEvent[];
1115
+ /**
1116
+ * Attempts to replay a state update from history using the recorded update payload.
1117
+ * @param eventIndex The index of the replayable event (an "update:start" event) in the history array.
1118
+ */
1119
+ replay(eventIndex: number): Promise<void>;
1120
+ /**
1121
+ * Creates a time-travel utility object with undo/redo capabilities.
1122
+ * @returns An object with methods for time-travel navigation.
1123
+ */
1124
+ createTimeTravel(): {
1125
+ canUndo: () => boolean;
1126
+ canRedo: () => boolean;
1127
+ undo: () => Promise<void>;
1128
+ redo: () => Promise<void>;
1129
+ length: () => number;
1130
+ clear: () => void;
1131
+ };
1132
+ /**
1133
+ * Saves the current observer session (events and state history) using a persistence mechanism.
1134
+ * @param persistence An object implementing the SimplePersistence interface.
1135
+ * @returns A promise that resolves to true if the session was saved successfully.
1136
+ */
1137
+ saveSession(persistence: SimplePersistence<ObserverSessionData<T>>): Promise<boolean>;
1138
+ /**
1139
+ * Loads a previously saved observer session and restores the state to the latest saved snapshot.
1140
+ * @param persistence An object implementing the SimplePersistence interface.
1141
+ * @returns A promise that resolves to true if a session was loaded.
1142
+ */
1143
+ loadSession(persistence: SimplePersistence<ObserverSessionData<T>>): Promise<boolean>;
1144
+ /**
1145
+ * Exports the current session data as a JSON file, initiating a browser download.
1146
+ */
1147
+ exportSession(): void;
1148
+ /**
1149
+ * Imports a session from a JSON file, restoring event history and state.
1150
+ * @param file The file object (e.g., from an <input type="file"> event) to import.
1151
+ * @returns A promise that resolves when the import is complete.
1152
+ */
1153
+ importSession(file: File): Promise<void>;
1154
+ /**
1155
+ * Cleans up the observer by unsubscribing all event listeners and clearing history.
1156
+ */
1157
+ disconnect(): void;
1158
+ /**
1159
+ * @private
1160
+ * Logs an event to the console with appropriate formatting.
1161
+ * Uses `this._consoleLog` for all output.
1162
+ * @param type Event type.
1163
+ * @param data Event data.
1164
+ */
1165
+ private _log;
1166
+ /**
1167
+ * @private
1168
+ * Checks for performance issues in the events.
1169
+ * Uses `this._consoleLog` for all output.
1170
+ * @param type Event type.
1171
+ * @param data Event data.
1172
+ */
1173
+ private _checkPerformance;
1174
+ }
1175
+ //#endregion
1176
+ //#region src/store/diff.d.ts
1177
+ /**
1178
+ * Creates a diff function with configurable options.
1179
+ *
1180
+ * @param {object} options - Configuration options for the diff function.
1181
+ * @param {symbol} [options.deleteMarker] - A custom symbol to mark properties for deletion.
1182
+ */
1183
+ declare function createDiff(options?: {
1184
+ deleteMarker?: symbol;
1185
+ }): any;
1186
+ /**
1187
+ * Creates a derivePaths function with configurable options.
1188
+ *
1189
+ * @param {object} options - Configuration options for the derivePaths function.
1190
+ * @param {symbol} [options.deleteMarker=Symbol.for("delete")] - A custom symbol to mark properties for deletion.
1191
+ */
1192
+ declare function createDerivePaths(options?: {
1193
+ deleteMarker?: symbol;
1194
+ }): <T>(changes: DeepPartial<T>) => string[];
1195
+ /**
1196
+ * @deprecated Use `createDiff()` instead.
1197
+ * Provided for backward compatibility with `Symbol.for("delete")` as the default delete marker.
1198
+ */
1199
+ declare const diff: any;
1200
+ type DiffFunction = ReturnType<typeof createDiff>;
1201
+ /**
1202
+ * @deprecated Use `createDerivePaths()` instead.
1203
+ * Provided for backward compatibility with `Symbol.for("delete")` as the default delete marker.
1204
+ */
1205
+ declare const derivePaths: <T>(changes: DeepPartial<T>) => string[];
1206
+ //#endregion
1207
+ //#region src/store/merge.d.ts
1208
+ /**
1209
+ * Creates a shallow clone of an object or array.
1210
+ */
1211
+ declare const shallowClone: (obj: any) => any;
1212
+ /**
1213
+ * Creates a deep merge function with configurable options.
1214
+ *
1215
+ * @param {object} options - Configuration options for the merge function.
1216
+ * @param {symbol} [options.deleteMarker=Symbol.for("delete")] - A custom symbol to mark properties for deletion during merge.
1217
+ */
1218
+ declare function createMerge(options?: {
1219
+ deleteMarker?: symbol;
1220
+ }): <T extends object>(original: T, changes: DeepPartial<T> | symbol) => T;
1221
+ /**
1222
+ * @deprecated Use `createMerge()` instead.
1223
+ * Provided for backward compatibility with `Symbol.for("delete")` as the default delete marker.
1224
+ */
1225
+ declare const merge: <T extends object>(original: T, changes: DeepPartial<T> | symbol) => T;
1226
+ type MergeFunction = ReturnType<typeof createMerge>;
1227
+ //#endregion
1228
+ //#region src/store/actions.d.ts
1229
+ declare class ActionCancelledError extends Error {
1230
+ constructor();
1231
+ }
1232
+ declare class UnknownActionError extends Error {
1233
+ constructor({
1234
+ action
1235
+ }: {
1236
+ action: string;
1237
+ });
1238
+ }
1239
+ declare class ActionManager<T extends object> {
1240
+ private eventBus;
1241
+ private set;
1242
+ private registrations;
1243
+ constructor(eventBus: EventBus<Record<StoreEvent, any>>, set: (update: StateUpdater<T>, options?: {
1244
+ force?: boolean;
1245
+ actionId?: string;
1246
+ }) => Promise<any>);
1247
+ register<R extends any[]>(action: {
1248
+ name: string;
1249
+ fn: (state: T, ...args: R) => DeepPartial<T> | Promise<DeepPartial<T>>;
1250
+ debounce?: {
1251
+ delay: number;
1252
+ condition?: (previous: R | undefined, current: R) => boolean;
1253
+ };
1254
+ }): () => void;
1255
+ dispatch<R extends any[]>(name: string, ...params: R): Promise<T>;
1256
+ private executeAction;
1257
+ running(name: string): boolean;
1258
+ private subscribe;
1259
+ watch(name: string): {
1260
+ name: string;
1261
+ status: () => boolean;
1262
+ subscribe: (_: () => void) => () => void;
1263
+ };
1264
+ private notifyStatusListeners;
1265
+ private emit;
1266
+ dispose(): void;
1267
+ }
1268
+ //#endregion
1269
+ export { ActionCancelledError, ActionCompletePayload, ActionErrorPayload, ActionManager, ActionStartPayload, ActionWatcher, BlockingMiddleware, DELETE_SYMBOL, DataStore, DeepPartial, DiffFunction, MergeFunction, Middleware, MiddlewareConfig, MiddlewareExecution, type ObserverOptions, PersistenceFailedPayload, PersistenceInitErrorPayload, PersistenceQueueClearedPayload, PersistenceQueuedPayload, PersistenceRetryPayload, PersistenceSuccessPayload, ReactiveDataStore, ReactiveDataStoreOptions, ReactiveSelector, SelectorAccessedPayload, SelectorChangedPayload, StateDelta, StateUpdater, StoreAction, StoreEvent, StoreEvents, StoreExecutionState, StoreLogger, StoreMetrics, StoreObserver, StoreRegistry, StoreRegistryOptions, type SubscribeOptions, TransactionOptions, TransformMiddleware, UnknownActionError, createDerivePaths, createDiff, createMerge, createStoreLogger, derivePaths, diff, merge, shallowClone };