@asaidimu/utils-artifacts 8.2.10 → 8.2.12
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 +1037 -0
- package/index.d.ts +541 -610
- package/index.js +2 -1
- package/index.mjs +2 -1
- package/package.json +4 -2
- package/index.d.mts +0 -842
package/index.d.cts
ADDED
|
@@ -0,0 +1,1037 @@
|
|
|
1
|
+
//#region src/error/error.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Severity levels for structured issues and errors.
|
|
4
|
+
*/
|
|
5
|
+
type Severity = "error" | "warning" | "info";
|
|
6
|
+
/**
|
|
7
|
+
* Represents a detailed validation or operational problem.
|
|
8
|
+
* Designed to be machine-readable while remaining human-friendly.
|
|
9
|
+
*/
|
|
10
|
+
interface Issue {
|
|
11
|
+
/** Machine-readable identifier (e.g., `"REQUIRED_FIELD_MISSING"`). */
|
|
12
|
+
readonly code: string;
|
|
13
|
+
/** Human-readable description of the problem. */
|
|
14
|
+
readonly message: string;
|
|
15
|
+
/** Field path in a document or state (e.g., `"users.0.email"`). */
|
|
16
|
+
readonly path?: string;
|
|
17
|
+
/** Optional array index when the issue relates to a specific element. */
|
|
18
|
+
readonly index?: number;
|
|
19
|
+
/** Seriousness of the issue. Defaults to `"error"`. */
|
|
20
|
+
readonly severity?: Severity;
|
|
21
|
+
/** Optional detailed explanation, can be multi-line. */
|
|
22
|
+
readonly description?: string;
|
|
23
|
+
/** Nested issues that caused this one. */
|
|
24
|
+
readonly cause?: readonly Issue[];
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Standardized error code format: `CATEGORY-XXX[-SUFFIX]`
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* // VAL-001 (Validation: required field missing)
|
|
32
|
+
* // DB-001-NF (Database: not found)
|
|
33
|
+
* // AUTH-001-DENIED (Auth: permission denied)
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
interface ErrorCodeMetadata {
|
|
37
|
+
/** The formal unique error code identifier (e.g., `"VAL-001"`). */
|
|
38
|
+
readonly code: string;
|
|
39
|
+
/** Human-readable uppercase name for the error type (e.g., `"VALIDATION_FAILED"`). */
|
|
40
|
+
readonly name: string;
|
|
41
|
+
/** Detailed description of when and why this error occurs. */
|
|
42
|
+
readonly description: string;
|
|
43
|
+
/** Suggested immediate action for engineers or systems to handle or resolve the error. */
|
|
44
|
+
readonly action?: string;
|
|
45
|
+
/** HTTP status code mapping for upstream REST APIs (e.g., `404`, `500`). */
|
|
46
|
+
readonly httpStatus?: number;
|
|
47
|
+
/** Operational category this error belongs to. */
|
|
48
|
+
readonly category: ErrorCategory;
|
|
49
|
+
/** Recommended logging level threshold (`"debug" | "info" | "warn" | "error"`). */
|
|
50
|
+
readonly logLevel?: "debug" | "info" | "warn" | "error";
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Categories classifying the origin and nature of an error.
|
|
54
|
+
*/
|
|
55
|
+
type ErrorCategory = "validation" | "database" | "auth" | "business" | "system" | "network" | "concurrency" | "custom";
|
|
56
|
+
/**
|
|
57
|
+
* Configuration options container used when constructing a new `SystemError`.
|
|
58
|
+
*/
|
|
59
|
+
interface SystemErrorParams {
|
|
60
|
+
/** The unique registered error code identifier (e.g., `ErrorCodes.INTERNAL_ERROR.code`). */
|
|
61
|
+
code: string;
|
|
62
|
+
/** Explicit error message overrides. If omitted, defaults to the error code's description. */
|
|
63
|
+
message?: string;
|
|
64
|
+
/** Operational severity tier. Defaults to `"error"`. */
|
|
65
|
+
severity?: Severity;
|
|
66
|
+
/** State path or key where the operational failure occurred (e.g., `"users.0.email"`). */
|
|
67
|
+
path?: string;
|
|
68
|
+
/** The function block, track component, or routing process executing during failure. */
|
|
69
|
+
operation?: string;
|
|
70
|
+
/** Flat array of precise granular input issues or schema violations. */
|
|
71
|
+
issues?: readonly Issue[];
|
|
72
|
+
/** The underlying trigger cause. Accepts native `Error` instances, custom errors, or concurrent `Error[]` arrays. */
|
|
73
|
+
cause?: unknown | unknown[];
|
|
74
|
+
/** Ad-hoc modifications overriding base properties mapped from the code registry. */
|
|
75
|
+
metadata?: Partial<Omit<ErrorCodeMetadata, "code" | "category">>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Primary domain operational error wrapper.
|
|
79
|
+
* Unfolds historical deep error hierarchies into flat, parallel-aware trace timelines.
|
|
80
|
+
*/
|
|
81
|
+
declare class SystemError extends Error {
|
|
82
|
+
/** The associated error identifier code (e.g., `"SYS-001"`). */
|
|
83
|
+
readonly code: string;
|
|
84
|
+
/** Static documentation mapping and registration rules bound to this code type. */
|
|
85
|
+
readonly codeMetadata: ErrorCodeMetadata;
|
|
86
|
+
/** Severity tier grading the operational consequence of this failure. */
|
|
87
|
+
readonly severity: Severity;
|
|
88
|
+
/** Target state or document path where processing failed. */
|
|
89
|
+
readonly path?: string;
|
|
90
|
+
/** Active system segment, workflow node, or function context executing during failure. */
|
|
91
|
+
readonly operation?: string;
|
|
92
|
+
/** Detailed sub-layer list representing structural data validation failures. */
|
|
93
|
+
readonly issues: readonly Issue[];
|
|
94
|
+
/** Raw backing trigger, array of concurrent branches, or source error instance. */
|
|
95
|
+
readonly cause?: unknown | unknown[];
|
|
96
|
+
/** Exact moment this error was instantiated (ISO string). */
|
|
97
|
+
readonly timestamp: string;
|
|
98
|
+
/**
|
|
99
|
+
* Instantiate a structurally traceable `SystemError`.
|
|
100
|
+
* @param params - Configuration parameters outlining the error's state context.
|
|
101
|
+
*/
|
|
102
|
+
constructor(params: SystemErrorParams);
|
|
103
|
+
/**
|
|
104
|
+
* Generates a separate immutable clone assigning a target file, state, or field path.
|
|
105
|
+
*/
|
|
106
|
+
withPath(path: string): SystemError;
|
|
107
|
+
/**
|
|
108
|
+
* Generates a separate immutable clone assigning a specific execution block or track tracking context.
|
|
109
|
+
*/
|
|
110
|
+
withOperation(operation: string): SystemError;
|
|
111
|
+
/**
|
|
112
|
+
* Appends an operational validation structural issue to a fresh clone of this error.
|
|
113
|
+
*/
|
|
114
|
+
withIssue(issue: Issue): SystemError;
|
|
115
|
+
/**
|
|
116
|
+
* Appends multiple validation issues onto a fresh clone of this error instance.
|
|
117
|
+
*/
|
|
118
|
+
withIssues(issues: readonly Issue[]): SystemError;
|
|
119
|
+
/**
|
|
120
|
+
* Maps a backing raw trigger or concurrent array tracking set to a fresh clone of this error instance.
|
|
121
|
+
*/
|
|
122
|
+
withCause(cause: unknown | unknown[]): SystemError;
|
|
123
|
+
/**
|
|
124
|
+
* Retrieves the recommended HTTP Status code mapped to this error's code metadata registry.
|
|
125
|
+
*/
|
|
126
|
+
getHttpStatus(): number | undefined;
|
|
127
|
+
/**
|
|
128
|
+
* Unrolls execution hierarchies chronologically, isolating parallel pipelines into clear trace frames.
|
|
129
|
+
* Always returns an array of trace nodes.
|
|
130
|
+
*/
|
|
131
|
+
private extractChronologicalTrace;
|
|
132
|
+
/**
|
|
133
|
+
* Transforms the error payload into a flattened transmission format.
|
|
134
|
+
* Strips recursive depth in favor of an array-mapped chronological failure `trace`.
|
|
135
|
+
*/
|
|
136
|
+
toJSON(): Record<string, unknown>;
|
|
137
|
+
/**
|
|
138
|
+
* Generates a flat payload matching `toJSON` format requirements for centralized platform ingestion engines.
|
|
139
|
+
*/
|
|
140
|
+
toLogEntry(): Record<string, unknown>;
|
|
141
|
+
/**
|
|
142
|
+
* Terminal terminal dump representation formatting details cleanly into plain strings.
|
|
143
|
+
*/
|
|
144
|
+
toString(): string;
|
|
145
|
+
}
|
|
146
|
+
//#endregion
|
|
147
|
+
//#region src/events/types.d.ts
|
|
148
|
+
/**
|
|
149
|
+
* Interface defining the shape of the EventBus.
|
|
150
|
+
* @template TEventMap - A record mapping event names to their respective payload types.
|
|
151
|
+
*/
|
|
152
|
+
interface EventBus<TEventMap extends Record<string, any>> {
|
|
153
|
+
/**
|
|
154
|
+
* Subscribes to a specific event by name.
|
|
155
|
+
* @param eventName - The name of the event to subscribe to.
|
|
156
|
+
* @param callback - The function to call when the event is emitted.
|
|
157
|
+
* @param options - Extra options to determine the behaviour of the
|
|
158
|
+
* subscription
|
|
159
|
+
* @returns A function to unsubscribe from the event.
|
|
160
|
+
*/
|
|
161
|
+
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;
|
|
162
|
+
/**
|
|
163
|
+
* Subscribes to an event and automatically unsubscribes after it fires once.
|
|
164
|
+
* @param eventName - The name of the event to subscribe to.
|
|
165
|
+
* @param callback - The function to call when the event is emitted.
|
|
166
|
+
* @returns A function to cancel the one-shot subscription before it fires.
|
|
167
|
+
*/
|
|
168
|
+
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;
|
|
169
|
+
/**
|
|
170
|
+
* Emits an event with a payload to all subscribed listeners.
|
|
171
|
+
* @param event - An object containing the event name and payload.
|
|
172
|
+
*/
|
|
173
|
+
emit: <TEventName extends keyof TEventMap>(event: {
|
|
174
|
+
name: TEventName;
|
|
175
|
+
payload: TEventMap[TEventName];
|
|
176
|
+
}) => void;
|
|
177
|
+
/**
|
|
178
|
+
* Retrieves metrics about event bus usage.
|
|
179
|
+
* @returns An object containing various metrics.
|
|
180
|
+
*/
|
|
181
|
+
metrics: () => EventMetrics;
|
|
182
|
+
/**
|
|
183
|
+
* Clears all subscriptions and resets metrics.
|
|
184
|
+
*
|
|
185
|
+
* After calling `clear()`, the bus is fully reset and can be reused
|
|
186
|
+
* cross-tab communication is re-established if it was previously enabled.
|
|
187
|
+
*
|
|
188
|
+
* @param options - Optional configuration object.
|
|
189
|
+
* @param options.permanent - If `true`, the bus becomes permanently unusable after clearing.
|
|
190
|
+
* Defaults to `false`.
|
|
191
|
+
* @returns {void}
|
|
192
|
+
*/
|
|
193
|
+
clear: (options?: {
|
|
194
|
+
permanent?: boolean;
|
|
195
|
+
}) => void;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Interface defining the metrics tracked by the EventBus.
|
|
199
|
+
*/
|
|
200
|
+
interface EventMetrics {
|
|
201
|
+
/** Total number of events emitted (both sync and deferred paths). */
|
|
202
|
+
totalEvents: number;
|
|
203
|
+
/** Number of active subscriptions across all event names. */
|
|
204
|
+
activeSubscriptions: number;
|
|
205
|
+
/** Map of event names to their emission counts. */
|
|
206
|
+
eventCounts: Map<string, number>;
|
|
207
|
+
/** Average duration of event dispatch in milliseconds. */
|
|
208
|
+
averageEmitDuration: number;
|
|
209
|
+
}
|
|
210
|
+
interface SubscribeOptions {
|
|
211
|
+
/**
|
|
212
|
+
* Debounce delay in milliseconds. When multiple events arrive in quick
|
|
213
|
+
* succession, the callback runs only after the quiet period ends, using the
|
|
214
|
+
* latest payload. Default = no debouncing.
|
|
215
|
+
*/
|
|
216
|
+
debounce?: number;
|
|
217
|
+
}
|
|
218
|
+
//#endregion
|
|
219
|
+
//#region src/store/types.d.ts
|
|
220
|
+
/**
|
|
221
|
+
* Utility type for representing partial updates to the state, allowing deep nesting.
|
|
222
|
+
* It makes all properties optional and applies the same transformation recursively
|
|
223
|
+
* to nested objects, allowing for selective updates while
|
|
224
|
+
* preserving the original structure. It also includes the original type T and
|
|
225
|
+
* undefined as possibilities for the top level and nested values.
|
|
226
|
+
*/
|
|
227
|
+
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;
|
|
228
|
+
/**
|
|
229
|
+
* Extended store state for monitoring the current execution status (e.g., if an update is in progress).
|
|
230
|
+
*/
|
|
231
|
+
interface StoreExecutionState<T> {
|
|
232
|
+
/** Indicates if a state update process is currently executing. */
|
|
233
|
+
executing: boolean;
|
|
234
|
+
/** The changes (DeepPartial) currently being processed in the execution cycle. Null if none. */
|
|
235
|
+
changes: DeepPartial<T> | null;
|
|
236
|
+
/** A queue of pending state update functions/objects to be applied sequentially. */
|
|
237
|
+
pendingChanges: Array<StateUpdater<T>>;
|
|
238
|
+
/** Names of all currently registered middlewares. */
|
|
239
|
+
middlewares: string[];
|
|
240
|
+
/** Details of the middleware currently running. Null if none. */
|
|
241
|
+
runningMiddleware: {
|
|
242
|
+
id: string;
|
|
243
|
+
name: string;
|
|
244
|
+
startTime: number;
|
|
245
|
+
} | null;
|
|
246
|
+
/** Indicates if the store is currently within an active transaction block. */
|
|
247
|
+
transactionActive: boolean;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Event types emitted by the state store for observability and debugging.
|
|
251
|
+
*/
|
|
252
|
+
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";
|
|
253
|
+
/**
|
|
254
|
+
* Represents a state update, which can be:
|
|
255
|
+
* 1. The full new state (`T`).
|
|
256
|
+
* 2. A partial update object (`DeepPartial<T>`).
|
|
257
|
+
* 3. A function that receives the current state and returns a partial update (sync or async).
|
|
258
|
+
*/
|
|
259
|
+
type StateUpdater<T> = T | DeepPartial<T> | ((state: T) => DeepPartial<T> | Promise<DeepPartial<T>>);
|
|
260
|
+
/**
|
|
261
|
+
* Core types for the reactive data store
|
|
262
|
+
*/
|
|
263
|
+
/**
|
|
264
|
+
* Type for a Transform Middleware function.
|
|
265
|
+
* It modifies (transforms) the incoming changes and must return a `DeepPartial<T>`.
|
|
266
|
+
*/
|
|
267
|
+
type TransformMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<DeepPartial<T>> | DeepPartial<T>;
|
|
268
|
+
/**
|
|
269
|
+
* Type for a Blocking Middleware function.
|
|
270
|
+
* It determines whether the state update should proceed or be blocked.
|
|
271
|
+
* It returns a boolean or an object containing a `block` boolean and an optional `error`.
|
|
272
|
+
*/
|
|
273
|
+
type BlockingMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<boolean | {
|
|
274
|
+
block: boolean;
|
|
275
|
+
error?: Error;
|
|
276
|
+
}> | boolean | {
|
|
277
|
+
block: boolean;
|
|
278
|
+
error?: Error;
|
|
279
|
+
};
|
|
280
|
+
/**
|
|
281
|
+
* Type representing the configuration object passed to the `use` method to register a middleware.
|
|
282
|
+
*/
|
|
283
|
+
interface MiddlewareConfig<T> {
|
|
284
|
+
/** The middleware function (can be a transform or blocking middleware). */
|
|
285
|
+
action: TransformMiddleware<T> | BlockingMiddleware<T>;
|
|
286
|
+
/** An optional, human-readable name for the middleware. */
|
|
287
|
+
name?: string;
|
|
288
|
+
/** If true, the middleware is treated as a blocking middleware (must return a boolean or `{ block: boolean }`). */
|
|
289
|
+
block?: boolean;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Interface for a reactive selector result, providing access to the value and subscription capabilities.
|
|
293
|
+
*/
|
|
294
|
+
interface ReactiveSelector<S> {
|
|
295
|
+
/** Unique identifier for the selector. */
|
|
296
|
+
id: string;
|
|
297
|
+
/** Function to get the current computed value of the selector. */
|
|
298
|
+
get: () => S;
|
|
299
|
+
/**
|
|
300
|
+
* Subscribes a callback function to run whenever the selector's result changes.
|
|
301
|
+
* Returns an unsubscribe function.
|
|
302
|
+
*/
|
|
303
|
+
subscribe: (callback: (state: S) => void) => () => void;
|
|
304
|
+
}
|
|
305
|
+
interface ActionWatcher {
|
|
306
|
+
/** Unique identifier for the action */
|
|
307
|
+
name: string;
|
|
308
|
+
/** Function to get the current computed value of the action. */
|
|
309
|
+
status: () => boolean;
|
|
310
|
+
/**
|
|
311
|
+
* Subscribes a callback function to run whenever the action's status changes.
|
|
312
|
+
* Returns an unsubscribe function.
|
|
313
|
+
*/
|
|
314
|
+
subscribe: (callback: () => void) => () => void;
|
|
315
|
+
}
|
|
316
|
+
interface TransactionOptions {
|
|
317
|
+
/** If true, blocks resolution until changes are fully committed to the database row */
|
|
318
|
+
flush?: boolean;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Interface defining the contract for the core data state store.
|
|
322
|
+
* T must be an object type.
|
|
323
|
+
*/
|
|
324
|
+
interface DataStore<T extends object> {
|
|
325
|
+
/**
|
|
326
|
+
* Gets the current state of the store.
|
|
327
|
+
* @param clone If true, returns a deep clone of the state; otherwise, returns the internal state reference.
|
|
328
|
+
* @returns The current state T.
|
|
329
|
+
*/
|
|
330
|
+
get(clone?: boolean): T;
|
|
331
|
+
/**
|
|
332
|
+
* Gets a subset of the store.
|
|
333
|
+
* @param paths The paths which to include in the returned object.
|
|
334
|
+
* @param separator Optional separator for paths. Defaults to `.` .
|
|
335
|
+
* @returns An object of the shape K mapping paths to their current values.
|
|
336
|
+
*/
|
|
337
|
+
subset<K extends Record<string, any> = Record<string, any>>(paths: Array<string>, separator?: string): K;
|
|
338
|
+
/**
|
|
339
|
+
* Registers a named action function that can modify the state.
|
|
340
|
+
* @param action The action configuration object.
|
|
341
|
+
* @returns A function to unregister the action.
|
|
342
|
+
*/
|
|
343
|
+
register<R extends any[]>(action: {
|
|
344
|
+
name: string;
|
|
345
|
+
fn: (state: T, ...args: R) => DeepPartial<T> | Promise<DeepPartial<T>>;
|
|
346
|
+
debounce?: {
|
|
347
|
+
delay: number;
|
|
348
|
+
condition?: (previous: R, current: R) => boolean;
|
|
349
|
+
};
|
|
350
|
+
}): () => void;
|
|
351
|
+
/**
|
|
352
|
+
* Executes (dispatches) a previously registered action by its name.
|
|
353
|
+
* @param name The name of the action.
|
|
354
|
+
* @param args The parameters to pass to the action function.
|
|
355
|
+
* @returns A promise that resolves to the final state after the action and subsequent updates are complete.
|
|
356
|
+
*/
|
|
357
|
+
dispatch<R extends any[]>(name: string, ...args: R): Promise<T>;
|
|
358
|
+
/**
|
|
359
|
+
* Sets or updates the state using a StateUpdater.
|
|
360
|
+
* @param update The new state, partial state, or a function returning a partial state.
|
|
361
|
+
* @param options Configuration options for the set operation.
|
|
362
|
+
* @returns A promise that resolves to the current state when the update is complete.
|
|
363
|
+
*/
|
|
364
|
+
set(update: StateUpdater<T>, options?: {
|
|
365
|
+
force?: boolean;
|
|
366
|
+
actionId?: string;
|
|
367
|
+
}): Promise<T>;
|
|
368
|
+
/**
|
|
369
|
+
* Creates a reactive selector that computes a derived value and tracks dependencies.
|
|
370
|
+
* @param selector A function to compute the derived state value S from the full state T.
|
|
371
|
+
* @returns A `ReactiveSelector<S>` object.
|
|
372
|
+
*/
|
|
373
|
+
select<S>(selector: (state: T) => S): ReactiveSelector<S>;
|
|
374
|
+
/**
|
|
375
|
+
* Subscribes a callback to run when the data at the specified path(s) changes.
|
|
376
|
+
* @param path A single path string or an array of path strings to watch.
|
|
377
|
+
* @param callback The function to execute when a change occurs in the watched path(s).
|
|
378
|
+
* @param options Extra options to pass to the event bus
|
|
379
|
+
* @returns An unsubscribe function.
|
|
380
|
+
*/
|
|
381
|
+
watch(path: string | Array<string>, callback: (state: T) => void, options?: SubscribeOptions): () => void;
|
|
382
|
+
/**
|
|
383
|
+
* Subscribes to execution‑status changes of a registered action.
|
|
384
|
+
*
|
|
385
|
+
* The provided callback is called **every time** the action transitions
|
|
386
|
+
* between idle and running (i.e. on `action:start`, `action:complete`, or
|
|
387
|
+
* `action:error` for the given name). The current status can also be read
|
|
388
|
+
* synchronously with `isActionRunning(name)`.
|
|
389
|
+
*
|
|
390
|
+
* **Deferred listener teardown**
|
|
391
|
+
* To avoid unnecessary churn when subscriptions are rapidly created and
|
|
392
|
+
* destroyed, the underlying event listeners are not removed immediately
|
|
393
|
+
* on unsubscribe. Instead, a *pending reset* is queued via `queueMicrotask`.
|
|
394
|
+
* If a new subscription for the same action arrives before that microtask
|
|
395
|
+
* executes, the reset is silently cancelled and the already‑established
|
|
396
|
+
* listeners are reused. This keeps the subscription infrastructure stable
|
|
397
|
+
* and prevents cascading notifications that could otherwise arise from
|
|
398
|
+
* repeated subscribe‑unsubscribe‑subscribe cycles.
|
|
399
|
+
*
|
|
400
|
+
* @param name - The name of the action to watch.
|
|
401
|
+
* @returns An ActionWatcher
|
|
402
|
+
*/
|
|
403
|
+
watchAction(name: string): ActionWatcher;
|
|
404
|
+
/**
|
|
405
|
+
* Executes an operation function within a transaction block.
|
|
406
|
+
* All state updates (`set` or actions) within the transaction are batched and applied atomically (all or nothing).
|
|
407
|
+
* @param operation The function containing the state updates.
|
|
408
|
+
* @returns A promise that resolves to the return value of the operation function.
|
|
409
|
+
*/
|
|
410
|
+
transaction<R>(operation: () => R | Promise<R>, options?: TransactionOptions): Promise<R>;
|
|
411
|
+
/**
|
|
412
|
+
* Registers a middleware function to intercept state updates.
|
|
413
|
+
* @param props The middleware configuration.
|
|
414
|
+
* @returns A function to unregister the middleware.
|
|
415
|
+
*/
|
|
416
|
+
use(props: MiddlewareConfig<T>): () => boolean;
|
|
417
|
+
/**
|
|
418
|
+
* Subscribes a listener to a specific store event type.
|
|
419
|
+
* @param event The type of store event to listen for.
|
|
420
|
+
* @param listener The callback function to execute when the event fires.
|
|
421
|
+
* @returns An unsubscribe function.
|
|
422
|
+
*/
|
|
423
|
+
on(event: StoreEvent, listener: (data: any) => void): () => void;
|
|
424
|
+
/**
|
|
425
|
+
* Returns the unique identifier of the store instance.
|
|
426
|
+
*/
|
|
427
|
+
id(): string;
|
|
428
|
+
/**
|
|
429
|
+
* Checks whether the store is fully initialized and ready for use.
|
|
430
|
+
*/
|
|
431
|
+
isReady(): boolean;
|
|
432
|
+
/**
|
|
433
|
+
* Returns a promise that resolves once the store is fully initialised.
|
|
434
|
+
* Safe to call multiple times — all callers share the same latch.
|
|
435
|
+
*
|
|
436
|
+
* @param timeout - Optional maximum wait time in milliseconds.
|
|
437
|
+
* @throws {TimeoutError} If the store does not become ready within the timeout.
|
|
438
|
+
*
|
|
439
|
+
* @example
|
|
440
|
+
* await store.ready();
|
|
441
|
+
* const state = store.get();
|
|
442
|
+
*/
|
|
443
|
+
ready(timeout?: number): Promise<void>;
|
|
444
|
+
/**
|
|
445
|
+
* Returns a readonly snapshot of the current execution state of the store.
|
|
446
|
+
*/
|
|
447
|
+
state(): Readonly<StoreExecutionState<T>>;
|
|
448
|
+
/**
|
|
449
|
+
* Releases all resources held by the store and renders it unusable
|
|
450
|
+
*/
|
|
451
|
+
dispose(): Promise<void>;
|
|
452
|
+
}
|
|
453
|
+
//#endregion
|
|
454
|
+
//#region src/artifacts/types.d.ts
|
|
455
|
+
/**
|
|
456
|
+
* Defines the lifecycle and sharing strategy for an artifact.
|
|
457
|
+
*/
|
|
458
|
+
type ArtifactScope =
|
|
459
|
+
/**
|
|
460
|
+
* **Singleton:** A single instance of the artifact is created and shared across all resolutions
|
|
461
|
+
* within the container. It is created once (often lazily) and reused until invalidated.
|
|
462
|
+
*/
|
|
463
|
+
"singleton"
|
|
464
|
+
/**
|
|
465
|
+
* **Transient:** A new instance of the artifact is created every time it is resolved.
|
|
466
|
+
* Transient artifacts do not participate in caching or shared state management.
|
|
467
|
+
*/
|
|
468
|
+
| "transient";
|
|
469
|
+
/**
|
|
470
|
+
* Enumeration of standard artifact scopes for strongly typed configuration.
|
|
471
|
+
*/
|
|
472
|
+
declare enum ArtifactScopes {
|
|
473
|
+
/** A single instance is shared globally. */
|
|
474
|
+
Singleton = "singleton",
|
|
475
|
+
/** A new instance is created on every resolution. */
|
|
476
|
+
Transient = "transient"
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Represents a snapshot of an artifact's state and dependencies for debugging purposes.
|
|
480
|
+
* Provides insight into the artifact's current status and its position within the dependency graph.
|
|
481
|
+
*/
|
|
482
|
+
interface ArtifactDebugNode {
|
|
483
|
+
/** The unique identifier (key) of the artifact. */
|
|
484
|
+
id: string;
|
|
485
|
+
/** The scope of the artifact (Singleton or Transient). */
|
|
486
|
+
scope: ArtifactScope;
|
|
487
|
+
/**
|
|
488
|
+
* The current status of the artifact, indicating its lifecycle phase.
|
|
489
|
+
* - `'active'`: The artifact is successfully built and its instance is available.
|
|
490
|
+
* - `'error'`: The artifact failed to build due to an external (runtime) error.
|
|
491
|
+
* - `'idle'`: The artifact has not yet been built (for lazy singletons) or has been disposed.
|
|
492
|
+
* - `'building'`: The artifact's factory is currently executing.
|
|
493
|
+
* - `'pending'`: The artifact is waiting to be built, often after an invalidation and before any debounce.
|
|
494
|
+
*/
|
|
495
|
+
status: "active" | "error" | "idle" | "building" | "pending" | "debouncing";
|
|
496
|
+
/** A list of artifact keys that this artifact directly depends on. */
|
|
497
|
+
dependencies: string[];
|
|
498
|
+
/** A list of artifact keys that directly depend on this artifact (its consumers). */
|
|
499
|
+
dependents: string[];
|
|
500
|
+
/** A list of state paths (selectors) that this artifact depends on. */
|
|
501
|
+
stateDependencies: string[];
|
|
502
|
+
/** The number of times this artifact's factory has been successfully executed/rebuilt. */
|
|
503
|
+
buildCount: number;
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Context provided to the `use` callback within an artifact factory.
|
|
507
|
+
* It allows an artifact to declare dependencies on other artifacts and state slices.
|
|
508
|
+
* @template TRegistry The type mapping artifact keys to their artifact types.
|
|
509
|
+
* @template TState The type of the global state managed by the DataStore.
|
|
510
|
+
*/
|
|
511
|
+
interface UseDependencyContext<TRegistry extends Record<string, any>, TState extends object> {
|
|
512
|
+
/**
|
|
513
|
+
* Resolves another artifact from the container and registers a dependency on it.
|
|
514
|
+
* If the dependency changes, the current artifact will be invalidated and rebuilt.
|
|
515
|
+
* @template K The key of the artifact to resolve.
|
|
516
|
+
* @param key The key of the artifact to resolve.
|
|
517
|
+
* @param params Parameters with which to resolve the artifact
|
|
518
|
+
* @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
|
|
519
|
+
* or an external error.
|
|
520
|
+
* @throws {SystemError} if the key is missing or if resolving creates a circular dependency.
|
|
521
|
+
*/
|
|
522
|
+
resolve<K extends keyof TRegistry>(key: K, params?: any): Promise<ResolvedArtifact<TRegistry[K]>>;
|
|
523
|
+
/**
|
|
524
|
+
* Resolves another artifact from the container and registers a dependency on it.
|
|
525
|
+
* If the dependency changes, the current artifact will be invalidated and rebuilt.
|
|
526
|
+
* @template K The key of the artifact to resolve.
|
|
527
|
+
* @param key The key of the artifact to resolve.
|
|
528
|
+
* @param params Parameters with which to resolve the artifact
|
|
529
|
+
* @returns A Promise that resolves to a the resolved instance, unlike
|
|
530
|
+
* resolve, this will throw an error if resolution fails.
|
|
531
|
+
* @throws {SystemError} if any error occurs during resolution.
|
|
532
|
+
*/
|
|
533
|
+
require<K extends keyof TRegistry>(key: K, params?: any): Promise<TRegistry[K]>;
|
|
534
|
+
/**
|
|
535
|
+
* Selects a slice of the global state and registers a dependency on it.
|
|
536
|
+
* If the selected state slice changes (based on a deep comparison), the current
|
|
537
|
+
* artifact will be invalidated and rebuilt.
|
|
538
|
+
* @template S The type of the selected state slice.
|
|
539
|
+
* @param selector A function that takes the full state and returns a slice of state.
|
|
540
|
+
* @returns The selected slice of state.
|
|
541
|
+
*/
|
|
542
|
+
select<S>(selector: (state: TState) => S, options?: SubscribeOptions): S;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Context object provided to an artifact stream producer function (`ctx.stream` callback).
|
|
546
|
+
* It contains methods and properties necessary for managing the stream and communicating
|
|
547
|
+
* new artifact values to the container and its consumers.
|
|
548
|
+
*
|
|
549
|
+
* @template TState The type of the global state.
|
|
550
|
+
* @template TArtifact The type of the artifact being streamed.
|
|
551
|
+
*/
|
|
552
|
+
type ArtifactStreamContext<TState, TArtifact> = {
|
|
553
|
+
/**
|
|
554
|
+
* The current value of the artifact. This is `undefined` before the first value is emitted.
|
|
555
|
+
* Useful for diffing or migrating state during an update.
|
|
556
|
+
* @returns The current artifact value or `undefined`.
|
|
557
|
+
*/
|
|
558
|
+
value: () => TArtifact | undefined;
|
|
559
|
+
/**
|
|
560
|
+
* An AbortSignal that indicates if the stream has been cancelled or aborted
|
|
561
|
+
* from the consumer side (e.g., due to container disposal or artifact invalidation).
|
|
562
|
+
* Producers should check this signal and stop processing when it is set to prevent leaks.
|
|
563
|
+
*/
|
|
564
|
+
signal: AbortSignal;
|
|
565
|
+
/**
|
|
566
|
+
* A function to asynchronously emit a new value of the artifact to the container.
|
|
567
|
+
* Calling this function updates the artifact's resolved value, triggers invalidation
|
|
568
|
+
* for its dependents, and updates the `value()` property for subsequent emissions.
|
|
569
|
+
*
|
|
570
|
+
* @param value The new artifact value to emit.
|
|
571
|
+
* @returns A Promise that resolves when the value has been sent and dependents have been notified.
|
|
572
|
+
*/
|
|
573
|
+
emit: (value: TArtifact) => Promise<void>;
|
|
574
|
+
/**
|
|
575
|
+
* Dispatches a state update to the global store, analogous to a standard `setState`.
|
|
576
|
+
* **Note:** This does not automatically register a dependency for the current artifact.
|
|
577
|
+
* @param update A `StateUpdater` function or a partial state object.
|
|
578
|
+
* @param options Optional settings for the update, including `force` and `actionId`.
|
|
579
|
+
* @returns A Promise that resolves when the state update is complete.
|
|
580
|
+
*/
|
|
581
|
+
set(update: StateUpdater<TState>, options?: {
|
|
582
|
+
force?: boolean;
|
|
583
|
+
actionId?: string;
|
|
584
|
+
}): Promise<any>;
|
|
585
|
+
};
|
|
586
|
+
/**
|
|
587
|
+
* The full context provided to an artifact's factory function.
|
|
588
|
+
* This context allows the artifact to interact with the container,
|
|
589
|
+
* declare dependencies, manage its lifecycle, and update its value.
|
|
590
|
+
* @template TRegistry The type mapping artifact keys to their artifact types.
|
|
591
|
+
* @template TState The type of the global state managed by the DataStore.
|
|
592
|
+
* @template TArtifact The type of the artifact being created by the factory.
|
|
593
|
+
*/
|
|
594
|
+
type ArtifactFactoryContext<TRegistry extends Record<string, any>, TState extends object, TArtifact, TExtra extends Record<string, any> = {}> = TExtra & {
|
|
595
|
+
/**
|
|
596
|
+
* Returns the current global state object. This is a non-reactive read;
|
|
597
|
+
* changes to the state will not automatically invalidate the artifact
|
|
598
|
+
* unless explicitly selected via `ctx.use` and `ctx.select`.
|
|
599
|
+
* @returns The current global state.
|
|
600
|
+
*/
|
|
601
|
+
state(): TState;
|
|
602
|
+
/**
|
|
603
|
+
* The previous instance of the artifact if it's a Singleton and is being rebuilt
|
|
604
|
+
* after an invalidation. This is `undefined` on the initial build.
|
|
605
|
+
* Useful for diffing, migrating state, or reusing resources during an update.
|
|
606
|
+
*/
|
|
607
|
+
previous?: TArtifact;
|
|
608
|
+
/**
|
|
609
|
+
* Executes a callback within a dependency tracking context.
|
|
610
|
+
* Any `resolve` or `select` calls made inside this callback will register
|
|
611
|
+
* dependencies for the current artifact.
|
|
612
|
+
* @template R The return type of the callback.
|
|
613
|
+
* @param callback The function to execute to resolve dependencies.
|
|
614
|
+
* @returns A Promise resolving to the result of the callback.
|
|
615
|
+
*/
|
|
616
|
+
use<R>(callback: (ctx: UseDependencyContext<TRegistry, TState>) => R | Promise<R>): Promise<R>;
|
|
617
|
+
/**
|
|
618
|
+
* Registers a cleanup function to be executed when the **current instance** of the
|
|
619
|
+
* artifact is invalidated and before its new instance is built. This is useful
|
|
620
|
+
* for releasing resources (e.g., event listeners) specific to the *previous* instance.
|
|
621
|
+
* @param cleanup The cleanup function.
|
|
622
|
+
*/
|
|
623
|
+
onCleanup(cleanup: ArtifactCleanup): void;
|
|
624
|
+
/**
|
|
625
|
+
* Registers a dispose function to be executed when the artifact is
|
|
626
|
+
* permanently removed from the container or the container itself is disposed.
|
|
627
|
+
* This is for final, permanent resource release.
|
|
628
|
+
* @param callback The dispose function.
|
|
629
|
+
*/
|
|
630
|
+
onDispose(callback: ArtifactCleanup): void;
|
|
631
|
+
/**
|
|
632
|
+
* Starts a streaming process for a Singleton artifact.
|
|
633
|
+
* The callback receives an `ArtifactStreamContext` to emit values and manage the
|
|
634
|
+
* stream's lifecycle. It can return a cleanup function (or a Promise resolving
|
|
635
|
+
* to one) to handle resource disposal.
|
|
636
|
+
* * @param callback - The streaming logic implementation. Can be synchronous or
|
|
637
|
+
* asynchronous, optionally returning a cleanup function.
|
|
638
|
+
* @throws {SystemError} If called on a Transient artifact, as they do not
|
|
639
|
+
* support persistent streaming states.
|
|
640
|
+
*/
|
|
641
|
+
stream(callback: (ctx: ArtifactStreamContext<TState, TArtifact>) => (void | (() => void | Promise<void>)) | Promise<void | (() => void | Promise<void>)>): void;
|
|
642
|
+
stream(callback: (ctx: ArtifactStreamContext<TState, TArtifact>) => (void | (() => void | Promise<void>)) | Promise<void | (() => void | Promise<void>)>): void;
|
|
643
|
+
/**
|
|
644
|
+
* An AbortSignal that indicates if the artifacts has been unregistered
|
|
645
|
+
*/
|
|
646
|
+
signal: AbortSignal; /** For parameterized artifacts: the parameters that were passed during resolve/watch. */
|
|
647
|
+
params?: any;
|
|
648
|
+
};
|
|
649
|
+
/**
|
|
650
|
+
* A function that performs cleanup or disposal logic for an artifact, potentially asynchronously.
|
|
651
|
+
* Used for `onCleanup` and `onDispose` callbacks.
|
|
652
|
+
*/
|
|
653
|
+
type ArtifactCleanup = () => void | Promise<void>;
|
|
654
|
+
interface ArtifactLifecycleEventMap {
|
|
655
|
+
"build:start": {
|
|
656
|
+
key: string;
|
|
657
|
+
templateKey?: string;
|
|
658
|
+
};
|
|
659
|
+
"build:complete": {
|
|
660
|
+
key: string;
|
|
661
|
+
instance: unknown;
|
|
662
|
+
};
|
|
663
|
+
"build:error": {
|
|
664
|
+
key: string;
|
|
665
|
+
error: unknown;
|
|
666
|
+
};
|
|
667
|
+
"artifact:invalidated": {
|
|
668
|
+
key: string;
|
|
669
|
+
cascade: boolean;
|
|
670
|
+
replace: boolean;
|
|
671
|
+
};
|
|
672
|
+
"artifact:disposed": {
|
|
673
|
+
key: string;
|
|
674
|
+
};
|
|
675
|
+
"artifact:registered": {
|
|
676
|
+
key: string;
|
|
677
|
+
scope: ArtifactScope;
|
|
678
|
+
};
|
|
679
|
+
"stream:emit": {
|
|
680
|
+
key: string;
|
|
681
|
+
value: unknown;
|
|
682
|
+
};
|
|
683
|
+
"container:dispose": {};
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* Common properties shared across all possible states of a resolved artifact.
|
|
687
|
+
* @template TArtifact The type of the resolved artifact instance.
|
|
688
|
+
*/
|
|
689
|
+
interface ResolvedArtifactBase {
|
|
690
|
+
/**
|
|
691
|
+
* A function to manually trigger cleanup associated with this specific
|
|
692
|
+
* resolved instance. This is typically only relevant for Transient artifacts
|
|
693
|
+
* where the consumer is responsible for cleanup.
|
|
694
|
+
*/
|
|
695
|
+
cleanup?: ArtifactCleanup;
|
|
696
|
+
/**
|
|
697
|
+
* Manually invalidates this artifact, triggering its rebuild and
|
|
698
|
+
* cascading invalidations to its dependents.
|
|
699
|
+
* @param replace If `true`, forces immediate rebuild without debounce delay.
|
|
700
|
+
* @param fatal If `true`, the artifact will not be rebuilt until next resolve
|
|
701
|
+
* regardless of the lazy option during registration.
|
|
702
|
+
*/
|
|
703
|
+
invalidate(replace?: boolean, fatal?: boolean): Promise<void>;
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* State of an artifact that is successfully built and ready for use.
|
|
707
|
+
* The instance is guaranteed to be present.
|
|
708
|
+
* @template TArtifact The type of the resolved artifact instance.
|
|
709
|
+
*/
|
|
710
|
+
interface ReadyArtifact<TArtifact> extends ResolvedArtifactBase {
|
|
711
|
+
/** The successfully resolved instance of the artifact. */
|
|
712
|
+
instance: TArtifact;
|
|
713
|
+
/** Indicates whether the artifact is ready and has an instance. */
|
|
714
|
+
ready: true;
|
|
715
|
+
error?: undefined;
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* State of an artifact that failed to build due to an external error.
|
|
719
|
+
* The instance is guaranteed to be absent.
|
|
720
|
+
*/
|
|
721
|
+
interface ErrorArtifact extends ResolvedArtifactBase {
|
|
722
|
+
instance?: undefined;
|
|
723
|
+
ready: false;
|
|
724
|
+
/**
|
|
725
|
+
* Any runtime or external error that occurred during the artifact's factory
|
|
726
|
+
* execution (e.g., network fetch failed).
|
|
727
|
+
*/
|
|
728
|
+
error: any;
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* State of an artifact that is pending, idle, or currently building.
|
|
732
|
+
* Both instance and error are absent.
|
|
733
|
+
*/
|
|
734
|
+
interface PendingArtifact extends ResolvedArtifactBase {
|
|
735
|
+
/** The instance is absent while pending or idle. Always undefined. */
|
|
736
|
+
instance?: undefined;
|
|
737
|
+
ready: false;
|
|
738
|
+
error?: undefined;
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* The result of an artifact resolution. This is a union type representing
|
|
742
|
+
* the artifact in one of three possible states: Ready, Error, or Pending/Idle.
|
|
743
|
+
*
|
|
744
|
+
* This structure allows consuming code to narrow the type based on the
|
|
745
|
+
* boolean flag `ready` or the presence of the `error` property.
|
|
746
|
+
*
|
|
747
|
+
* @template TArtifact The type of the resolved artifact instance.
|
|
748
|
+
*/
|
|
749
|
+
type ResolvedArtifact<TArtifact> = ReadyArtifact<TArtifact> | ErrorArtifact | PendingArtifact;
|
|
750
|
+
type KeyedResolvedArtifact<TRegistry, K extends keyof TRegistry> = ResolvedArtifact<TRegistry[K]> & { [P in K]?: TRegistry[K] };
|
|
751
|
+
/**
|
|
752
|
+
* The factory function responsible for creating an artifact's instance.
|
|
753
|
+
* It receives an `ArtifactFactoryContext` to interact with the container
|
|
754
|
+
* and declare dependencies.
|
|
755
|
+
* @template TRegistry The type mapping artifact keys to their artifact types.
|
|
756
|
+
* @template TState The type of the global state managed by the DataStore.
|
|
757
|
+
* @template TArtifact The type of the artifact this factory produces.
|
|
758
|
+
* @param context The context for creating the artifact.
|
|
759
|
+
* @returns The artifact instance or a Promise resolving to it.
|
|
760
|
+
*/
|
|
761
|
+
type ArtifactFactory<TRegistry extends Record<string, any>, TState extends object, TArtifact, TExtra extends Record<string, any> = {}> = (context: ArtifactFactoryContext<TRegistry, TState, TArtifact, TExtra>) => TArtifact | Promise<TArtifact>;
|
|
762
|
+
type ArtifactInstance<R> = R extends PromiseLike<infer T> ? T : R;
|
|
763
|
+
/**
|
|
764
|
+
* An interface for observing changes to an artifact without direct resolution,
|
|
765
|
+
* typically used for UI binding or monitoring.
|
|
766
|
+
* Provides a way to get the current resolved artifact and subscribe to updates.
|
|
767
|
+
* @template TArtifact The type of the artifact being watched.
|
|
768
|
+
*/
|
|
769
|
+
interface ArtifactObserver<TRegistry, K extends keyof TRegistry> {
|
|
770
|
+
/** The unique identifier (key) of the artifact being watched. */
|
|
771
|
+
id: string;
|
|
772
|
+
/**
|
|
773
|
+
* Number of active references (watchers) to this observer instance.
|
|
774
|
+
* Incremented on each `watch()` call, decremented on each `dispose()` call.
|
|
775
|
+
*/
|
|
776
|
+
count: number;
|
|
777
|
+
/**
|
|
778
|
+
* Retrieves the current `ResolvedArtifact` for the watched key.
|
|
779
|
+
* @param resolve Flag indicating whether we should resolve the artifact
|
|
780
|
+
* immediately. Defaults to `false`
|
|
781
|
+
* @returns The resolved artifact, including its instance and status.
|
|
782
|
+
*/
|
|
783
|
+
get(resolve?: boolean): KeyedResolvedArtifact<TRegistry, K>;
|
|
784
|
+
/**
|
|
785
|
+
* Subscribes a callback function to be invoked whenever the artifact's
|
|
786
|
+
* state (instance, error, or readiness) changes.
|
|
787
|
+
* @param callback The function to call on updates. It receives the new `ResolvedArtifact`.
|
|
788
|
+
* @param eager a boolean indicating whether we should immediately call the
|
|
789
|
+
* callback after subscription. Defaults to `true`
|
|
790
|
+
* @returns A function to unsubscribe the callback and stop receiving updates.
|
|
791
|
+
*/
|
|
792
|
+
subscribe(callback: (artifact: KeyedResolvedArtifact<TRegistry, K>) => void, eager?: boolean): () => void;
|
|
793
|
+
/**
|
|
794
|
+
* Resolves another artifact from the container and registers a dependency on it.
|
|
795
|
+
* If the dependency changes, the current artifact will be invalidated and rebuilt.
|
|
796
|
+
* @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
|
|
797
|
+
* or an external error.
|
|
798
|
+
* @throws {SystemError} if resolution fails.
|
|
799
|
+
*/
|
|
800
|
+
resolve(): Promise<KeyedResolvedArtifact<TRegistry, K>>;
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Configuration options for defining an artifact. These options control
|
|
804
|
+
* its lifecycle, instantiation, and error handling behavior.
|
|
805
|
+
* @template TState The type of the global state.
|
|
806
|
+
* @template TArtifact The resolved type of the artifact instance.
|
|
807
|
+
* @template TRegistry The type mapping of all artifacts in the container.
|
|
808
|
+
*/
|
|
809
|
+
interface ArtifactTemplate<TState extends object, TArtifact, TRegistry extends Record<string, any> = Record<string, any>, TExtra extends Record<string, any> = {}> {
|
|
810
|
+
/** The unique key identifying this artifact within the registry. */
|
|
811
|
+
key: keyof TRegistry;
|
|
812
|
+
/** The factory function responsible for creating the artifact's instance. */
|
|
813
|
+
factory: ArtifactFactory<TRegistry, TState, TArtifact, TExtra>;
|
|
814
|
+
/**
|
|
815
|
+
* The scope of the artifact, determining its lifecycle and sharing strategy.
|
|
816
|
+
* Defaults to `ArtifactScopes.Singleton`.
|
|
817
|
+
*/
|
|
818
|
+
scope?: ArtifactScope;
|
|
819
|
+
/**
|
|
820
|
+
* If `true` (default), the artifact's factory is executed only when the artifact
|
|
821
|
+
* is first requested (lazy instantiation). If `false`, the artifact is built
|
|
822
|
+
* immediately upon registration (only applies to Singleton scopes).
|
|
823
|
+
*/
|
|
824
|
+
lazy?: boolean;
|
|
825
|
+
/**
|
|
826
|
+
* Maximum time in milliseconds allowed for the artifact's factory function
|
|
827
|
+
* to complete execution. If exceeded, the factory will time out.
|
|
828
|
+
*/
|
|
829
|
+
timeout?: number;
|
|
830
|
+
/**
|
|
831
|
+
* Number of times to retry the artifact's factory on failure due to an
|
|
832
|
+
* external (runtime) error (e.g., an exception in an async dependency).
|
|
833
|
+
* SystemErrors (e.g., key not found) are not retried. Defaults to `0`.
|
|
834
|
+
*/
|
|
835
|
+
retries?: number;
|
|
836
|
+
/**
|
|
837
|
+
* Base debounce time in milliseconds for invalidation events originating
|
|
838
|
+
* from this artifact's dependencies. This delays the rebuild process to
|
|
839
|
+
* aggregate multiple rapid changes.
|
|
840
|
+
*/
|
|
841
|
+
debounce?: number;
|
|
842
|
+
/** If defined, the artifact is parameterized. Receives the user‑supplied params and returns a unique string key. */
|
|
843
|
+
paramKey?: (params: Record<string, unknown>) => string;
|
|
844
|
+
virtual?: true;
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Extracts the global state type (`TState`) from an `ArtifactTemplate`.
|
|
848
|
+
*/
|
|
849
|
+
type ArtifactStateType<T> = T extends ArtifactTemplate<infer TState, any, any> ? TState : never;
|
|
850
|
+
/**
|
|
851
|
+
* Extracts the full artifact registry type (`TRegistry`) from an `ArtifactTemplate`.
|
|
852
|
+
*/
|
|
853
|
+
type ArtifactRegistryType<T> = T extends ArtifactTemplate<any, any, infer TRegistry> ? TRegistry : never;
|
|
854
|
+
/**
|
|
855
|
+
* Extracts the key type (`K`) from an `ArtifactTemplate` (as a string literal if possible).
|
|
856
|
+
*/
|
|
857
|
+
type ArtifactKey<T> = T extends {
|
|
858
|
+
key: infer K;
|
|
859
|
+
} ? K : never;
|
|
860
|
+
/**
|
|
861
|
+
* Extracts the scope type (`S`) from an `ArtifactTemplate`, defaulting to `ArtifactScope` if undefined.
|
|
862
|
+
*/
|
|
863
|
+
type ArtifactScopeType<T> = T extends {
|
|
864
|
+
scope: infer S;
|
|
865
|
+
} ? S extends ArtifactScope ? S : ArtifactScope : ArtifactScope;
|
|
866
|
+
/**
|
|
867
|
+
* Helper type that creates a properly typed template map where keys correspond to artifact names
|
|
868
|
+
* and values are their corresponding templates.
|
|
869
|
+
* @template TState The type of the global state.
|
|
870
|
+
* @template TRegistry The map of all artifact keys to their resolved types.
|
|
871
|
+
*/
|
|
872
|
+
type ArtifactTemplateMap<TState extends object, TRegistry extends Record<string, any> = Record<string, any>> = { [K in keyof TRegistry]: ArtifactTemplate<TState, TRegistry[K], TRegistry> };
|
|
873
|
+
/**
|
|
874
|
+
* Extracts the artifact's resolved value type (`TArtifact`) from an object that structurally
|
|
875
|
+
* resembles an `ArtifactTemplate` (by inspecting the `factory` function's generic arguments).
|
|
876
|
+
*
|
|
877
|
+
* @template T The type that contains a factory property.
|
|
878
|
+
*/
|
|
879
|
+
type ArtifactValue<T> = T extends {
|
|
880
|
+
factory: ArtifactFactory<any, any, infer TArtifact, any>;
|
|
881
|
+
} ? TArtifact : never;
|
|
882
|
+
/**
|
|
883
|
+
* Infers the complete Artifact Registry type from a map of artifact configuration objects.
|
|
884
|
+
*
|
|
885
|
+
* This utility uses the `ArtifactValue` type to determine the resolved type for each key
|
|
886
|
+
* based on the `factory` function defined in the configuration.
|
|
887
|
+
*
|
|
888
|
+
* @template T A map where keys are artifact names and values are their configurations.
|
|
889
|
+
*/
|
|
890
|
+
type InferRegistry<T extends Record<string, {
|
|
891
|
+
factory: (...args: any[]) => any;
|
|
892
|
+
[key: string]: any;
|
|
893
|
+
}>> = { [K in keyof T]: ArtifactValue<T[K]> };
|
|
894
|
+
/**
|
|
895
|
+
* State paths grouped by options passed to the store
|
|
896
|
+
*/
|
|
897
|
+
interface StateGroup {
|
|
898
|
+
paths: string[];
|
|
899
|
+
options?: SubscribeOptions;
|
|
900
|
+
}
|
|
901
|
+
interface ExportedArtifact {
|
|
902
|
+
key: string;
|
|
903
|
+
instance: any;
|
|
904
|
+
state: {
|
|
905
|
+
groups: Array<{
|
|
906
|
+
paths: string[];
|
|
907
|
+
options?: SubscribeOptions;
|
|
908
|
+
}>;
|
|
909
|
+
hash: string;
|
|
910
|
+
};
|
|
911
|
+
dependencies: string[];
|
|
912
|
+
}
|
|
913
|
+
interface ExportedContainerState {
|
|
914
|
+
version: string;
|
|
915
|
+
timestamp: number;
|
|
916
|
+
artifacts: ExportedArtifact[];
|
|
917
|
+
checksum: string;
|
|
918
|
+
}
|
|
919
|
+
//#endregion
|
|
920
|
+
//#region src/logger/logger.d.ts
|
|
921
|
+
/**
|
|
922
|
+
* Represents the severity level of a system log entry.
|
|
923
|
+
* Levels are ordered by increasing severity: trace, debug, info, warn, error.
|
|
924
|
+
*/
|
|
925
|
+
type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
|
|
926
|
+
/**
|
|
927
|
+
* Structure representing a fully contextualized system log entry ready for sinking.
|
|
928
|
+
*/
|
|
929
|
+
interface SystemLog {
|
|
930
|
+
/** The severity level of the log. */
|
|
931
|
+
level: LogLevel;
|
|
932
|
+
/** A clear, human-readable string identifying the distinct event (e.g., "user_login_failed"). */
|
|
933
|
+
event: string;
|
|
934
|
+
/** Additional structured data specific to this log instantiation. */
|
|
935
|
+
data?: object;
|
|
936
|
+
/** Contextual data shared across the logger instance (e.g., traceIds, environment). */
|
|
937
|
+
context?: object;
|
|
938
|
+
/** Epoch timestamp in milliseconds denoting when the log event occurred. */
|
|
939
|
+
timestamp: number;
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* Primary logger interface providing level-specific log dispatching and context-chaining.
|
|
943
|
+
*/
|
|
944
|
+
interface SystemLogger {
|
|
945
|
+
/** Logs high-volume, extremely fine-grained diagnostic details. */
|
|
946
|
+
trace(event: string, data?: object): void;
|
|
947
|
+
/** Logs diagnostic information useful during local development or debugging. */
|
|
948
|
+
debug(event: string, data?: object): void;
|
|
949
|
+
/** Logs standard operational events that track the healthy flow of the system. */
|
|
950
|
+
info(event: string, data?: object): void;
|
|
951
|
+
/** Alias for the `info` logging method. */
|
|
952
|
+
log(event: string, data?: object): void;
|
|
953
|
+
/** Logs non-fatal operational anomalies or conditions that deserve attention. */
|
|
954
|
+
warn(event: string, data?: object): void;
|
|
955
|
+
/** Logs critical errors, failures, or exceptions preventing a transaction/process. */
|
|
956
|
+
error(event: string, data?: unknown): void;
|
|
957
|
+
/**
|
|
958
|
+
* Directly forwards a pre-constructed `SystemLog` record through the logger's pipeline.
|
|
959
|
+
* Combines instance context before outputting.
|
|
960
|
+
*/
|
|
961
|
+
write(record: SystemLog): void;
|
|
962
|
+
/**
|
|
963
|
+
* Generates a new `SystemLogger` instance that shares the existing sinks and parent
|
|
964
|
+
* context, deeply merging the newly provided context on top.
|
|
965
|
+
*
|
|
966
|
+
* @param context - The metadata to append to all subsequent logs emitted by the child logger.
|
|
967
|
+
*/
|
|
968
|
+
child(context: object): SystemLogger;
|
|
969
|
+
}
|
|
970
|
+
//#endregion
|
|
971
|
+
//#region src/artifacts/container.d.ts
|
|
972
|
+
declare class ArtifactContainer<TRegistry extends Record<string, any> = Record<string, any>, TState extends object = any> {
|
|
973
|
+
private readonly registry;
|
|
974
|
+
private readonly cache;
|
|
975
|
+
private readonly graph;
|
|
976
|
+
private readonly manager;
|
|
977
|
+
private readonly observer;
|
|
978
|
+
private readonly logger;
|
|
979
|
+
private readonly store;
|
|
980
|
+
readonly events: EventBus<ArtifactLifecycleEventMap>;
|
|
981
|
+
constructor(store: Pick<DataStore<TState>, "watch" | "get" | "set" | "subset">, options?: {
|
|
982
|
+
logger?: SystemLogger;
|
|
983
|
+
});
|
|
984
|
+
debugInfo(): ArtifactDebugNode[];
|
|
985
|
+
register<K extends keyof TRegistry>(params: ArtifactTemplate<TState, TRegistry[K], TRegistry>): () => void;
|
|
986
|
+
has<K extends keyof TRegistry>(key: K): boolean;
|
|
987
|
+
unregister<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<void>;
|
|
988
|
+
resolve<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<KeyedResolvedArtifact<TRegistry, K>>;
|
|
989
|
+
require<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<TRegistry[K]>;
|
|
990
|
+
watch<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>, ttl?: number): ArtifactObserver<TRegistry, K>;
|
|
991
|
+
peek<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): TRegistry[K] | undefined;
|
|
992
|
+
invalidate<K extends keyof TRegistry>(key: K, options?: {
|
|
993
|
+
replace?: boolean;
|
|
994
|
+
params?: Record<string, unknown>;
|
|
995
|
+
}): Promise<void>;
|
|
996
|
+
on<TEventName extends keyof ArtifactLifecycleEventMap>(eventName: TEventName, callback: (payload: ArtifactLifecycleEventMap[TEventName]) => void): () => void;
|
|
997
|
+
on(eventName: "*", callback: (payload: ArtifactLifecycleEventMap[keyof ArtifactLifecycleEventMap], event: keyof ArtifactLifecycleEventMap) => void): () => void;
|
|
998
|
+
once<TEventName extends keyof ArtifactLifecycleEventMap>(eventName: TEventName, callback: (payload: ArtifactLifecycleEventMap[TEventName]) => void): () => void;
|
|
999
|
+
once(eventName: "*", callback: (payload: ArtifactLifecycleEventMap[keyof ArtifactLifecycleEventMap], event: keyof ArtifactLifecycleEventMap) => void): () => void;
|
|
1000
|
+
notifyObservers(key: string): void;
|
|
1001
|
+
hasWatchers(key: string): boolean;
|
|
1002
|
+
dispose(): Promise<void>;
|
|
1003
|
+
export(): Promise<ExportedContainerState>;
|
|
1004
|
+
private restore;
|
|
1005
|
+
static from<TRegistry extends Record<string, any> = Record<string, any>, TState extends object = any>(options: {
|
|
1006
|
+
store: Pick<DataStore<TState>, "watch" | "get" | "set" | "subset">;
|
|
1007
|
+
bundle?: ExportedContainerState;
|
|
1008
|
+
templates: ArtifactTemplate<TState, any, TRegistry>[];
|
|
1009
|
+
logger?: SystemLogger;
|
|
1010
|
+
}): Promise<ArtifactContainer<TRegistry, TState>>;
|
|
1011
|
+
}
|
|
1012
|
+
//#endregion
|
|
1013
|
+
//#region src/artifacts/errors.d.ts
|
|
1014
|
+
declare const ErrorCodes: {
|
|
1015
|
+
readonly NOT_FOUND: "DB-001-NF";
|
|
1016
|
+
readonly DUPLICATE_KEY: "DB-002-DUP";
|
|
1017
|
+
readonly INVALID_COMMAND: "BUS-001";
|
|
1018
|
+
readonly INTERNAL_ERROR: "SYS-001";
|
|
1019
|
+
readonly CONCURRENCY_ERROR: "CON-001";
|
|
1020
|
+
};
|
|
1021
|
+
declare function artifactNotFound(key: string): SystemError;
|
|
1022
|
+
declare function cycleDetected(path: string[]): SystemError;
|
|
1023
|
+
declare function illegalScope(message: string): SystemError;
|
|
1024
|
+
declare function watcherDisposed(key: string): SystemError;
|
|
1025
|
+
declare function timeoutError(message?: string): SystemError;
|
|
1026
|
+
declare function keyConflict(key?: string): SystemError;
|
|
1027
|
+
declare function notParameterized(key: string): SystemError;
|
|
1028
|
+
declare function paramKeyCollision(key: string, computedKey: string): SystemError;
|
|
1029
|
+
declare function selfDependency(key: string): SystemError;
|
|
1030
|
+
declare function buildStaleAfterRetries(depKey: string): SystemError;
|
|
1031
|
+
declare function invalidImport(message: string): SystemError;
|
|
1032
|
+
declare function invalidExport(key: string): SystemError;
|
|
1033
|
+
declare class SupersededBuildError extends Error {
|
|
1034
|
+
constructor();
|
|
1035
|
+
}
|
|
1036
|
+
//#endregion
|
|
1037
|
+
export { ArtifactCleanup, ArtifactContainer, ArtifactDebugNode, ArtifactFactory, ArtifactFactoryContext, ArtifactInstance, ArtifactKey, ArtifactLifecycleEventMap, ArtifactObserver, ArtifactRegistryType, ArtifactScope, ArtifactScopeType, ArtifactScopes, ArtifactStateType, ArtifactStreamContext, ArtifactTemplate, ArtifactTemplateMap, ArtifactValue, ErrorArtifact, ErrorCodes, ExportedArtifact, ExportedContainerState, InferRegistry, type Issue, KeyedResolvedArtifact, PendingArtifact, ReadyArtifact, ResolvedArtifact, ResolvedArtifactBase, type Severity, StateGroup, SupersededBuildError, SystemError, UseDependencyContext, artifactNotFound, buildStaleAfterRetries, cycleDetected, illegalScope, invalidExport, invalidImport, keyConflict, notParameterized, paramKeyCollision, selfDependency, timeoutError, watcherDisposed };
|