unwrapped 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,105 +1,544 @@
1
+ /**
2
+ * Base class for error handling, providing structured error information and logging.
3
+ * @class ErrorBase
4
+ * @property {string} code - The error code.
5
+ * @property {string | undefined} message - The error message (optional).
6
+ * @property {unknown} thrownError - The original error object, if any (optional).
7
+ *
8
+ * @constructor
9
+ * @param {string} code - The error code.
10
+ * @param {string} [message] - The error message.
11
+ * @param {unknown} [thrownError] - The original error object, if any.
12
+ * @param {boolean} [log=true] - Whether to log the error upon creation.
13
+ */
1
14
  declare class ErrorBase {
2
15
  code: string;
3
16
  message?: string | undefined;
4
- thrownError?: any;
5
- constructor(code: string, message?: string, thrownError?: any, log?: boolean);
17
+ thrownError?: unknown;
18
+ constructor(code: string, message?: string, thrownError?: unknown, log?: boolean);
19
+ /**
20
+ * Converts the error to a string representation, on the format "Error {code}: {message}".
21
+ * @returns a string representation of the error
22
+ */
6
23
  toString(): string;
24
+ /**
25
+ * Logs the error to the console, uses console.error and ErrorBase.toString() internally.
26
+ * Logs thrownError if it was provided on creation.
27
+ */
7
28
  logError(): void;
8
29
  }
9
30
 
10
- type ResultState<T, E = ErrorBase> = {
31
+ /**
32
+ * Type representing the state of a Result, either success with a value of type T,
33
+ * or error with an error of type E (defaulting to ErrorBase).
34
+ */
35
+ type ResultState<T, E extends ErrorBase = ErrorBase> = {
11
36
  status: 'success';
12
37
  value: T;
13
38
  } | {
14
39
  status: 'error';
15
40
  error: E;
16
41
  };
17
- declare class Result<T, E = ErrorBase> {
42
+ /**
43
+ * Class representing the result of an operation that can either succeed with a value of type T,
44
+ * or fail with an error of type E (defaulting to ErrorBase).
45
+ * Provides methods for unwrapping the result, chaining operations, and handling errors.
46
+ * @class Result
47
+ * @template T - The type of the successful result value.
48
+ * @template E - The type of the error, extending ErrorBase (default is ErrorBase).
49
+ */
50
+ declare class Result<T, E extends ErrorBase = ErrorBase> {
18
51
  private _state;
52
+ /**
53
+ * Creates a new Result instance with the given state.
54
+ * @param state the state of the created Result
55
+ */
19
56
  constructor(state: ResultState<T, E>);
57
+ /** Returns the internal state of the Result. */
20
58
  get state(): ResultState<T, E>;
21
- static ok<T, E = ErrorBase>(value: T): Result<T, E>;
22
- static err<E>(error: E): Result<never, E>;
23
- static errTag(code: string, message?: string): Result<never, ErrorBase>;
59
+ /**
60
+ * Checks if the Result is successful.
61
+ * @returns whether or not the result is successful
62
+ */
63
+ isSuccess(): boolean;
64
+ /**
65
+ * Checks if the Result is an error.
66
+ * @returns whether or not the result is an error
67
+ */
68
+ isError(): boolean;
69
+ /**
70
+ * Creates a successful Result with the given value.
71
+ * @param value the result of the successful operation
72
+ * @returns a successful Result
73
+ */
74
+ static ok<T, E extends ErrorBase = ErrorBase>(value: T): Result<T, E>;
75
+ /**
76
+ * Creates an error Result with the given error.
77
+ * @param error the error of the failed operation
78
+ * @returns an error Result
79
+ */
80
+ static err<E extends ErrorBase = ErrorBase>(error: E): Result<never, E>;
81
+ /**
82
+ * Creates an error Result (containing an ErrorBase) with the given error code and optional message.
83
+ * @param code the error code
84
+ * @param message an optional error message
85
+ * @returns an error Result
86
+ */
87
+ static errTag(code: string, message?: string, thrownError?: unknown): Result<never, ErrorBase>;
88
+ /**
89
+ * Returns the successful value (if the Result is successful) or null (if it is an error).
90
+ * @returns either the successful value or null
91
+ */
24
92
  unwrapOrNull(): T | null;
93
+ /**
94
+ * Returns the successful value (if the Result is successful) or throws an error (if it is an error).
95
+ * @returns the successful value
96
+ * @throws an normal JS Error if the result is not successful
97
+ */
25
98
  unwrapOrThrow(): T;
99
+ /**
100
+ * Returns the successful value (if the Result is successful) or a default value (if it is an error).
101
+ * @param defaultValue the default value to return if the Result is an error
102
+ * @returns either the successful value or the default value
103
+ */
26
104
  unwrapOr<O>(defaultValue: O): T | O;
27
- isSuccess(): boolean;
28
- isError(): boolean;
29
- static tryPromise<T, E>(promise: Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>>;
105
+ /**
106
+ * Transforms a Promise of a successful value into a Promise of a Result,
107
+ * catching any thrown errors and mapping them using the provided errorMapper function.
108
+ * @param promise the promise to execute
109
+ * @param errorMapper a function that maps a thrown error to a Result error
110
+ * @returns a Promise resolving to a Result containing either the successful value or the mapped error
111
+ */
112
+ static tryPromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>>;
113
+ /**
114
+ * Executes an asynchronous function and transforms its result into a Result,
115
+ * catching any thrown errors and mapping them using the provided errorMapper function.
116
+ * Same as Result.tryPromise(fn(), errorMapper).
117
+ * @param fn the asynchronous function to execute
118
+ * @param errorMapper a function that maps a thrown error to a Result error
119
+ * @returns a Promise resolving to a Result containing either the successful value or the mapped error
120
+ */
30
121
  static tryFunction<T, E extends ErrorBase = ErrorBase>(fn: () => Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>>;
31
- chain<O, E2>(fn: (input: T) => ResultState<O, E | E2>): Result<O, E | E2>;
122
+ /**
123
+ * Chains the current Result with another operation that returns a ResultState.
124
+ * If the current Result is successful, applies the provided function to its value.
125
+ * Otherwise, returns the current error.
126
+ * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.
127
+ * @param fn a function taking as input the successful value of the result, and returning a ResultState describing the result of its own operation
128
+ * @returns a new Result that has either the successful value of the operation, or either the error of the current result or the error returned by fn
129
+ */
130
+ chain<O, E2 extends ErrorBase = ErrorBase>(fn: (input: T) => ResultState<O, E | E2>): Result<O, E | E2>;
131
+ /**
132
+ * Chains the current Result with another operation that returns a Result.
133
+ * If the current Result is successful, applies the provided function to its value.
134
+ * Otherwise, returns the current error.
135
+ * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.
136
+ * Same as chain, but the function returns a Result directly instead of a ResultState.
137
+ * @param fn a function taking as input the successful value of the result, and returning a Result describing the result of its own operation
138
+ * @returns a new Result that has either the successful value of the operation, or either the error of the current result or the error returned by fn
139
+ */
140
+ flatChain<O, E2 extends ErrorBase = ErrorBase>(fn: (input: T) => Result<O, E | E2>): Result<O, E | E2>;
141
+ /**
142
+ * @yields the current Result, and if it is successful, returns its value.
143
+ * This allows using Result instances in generator functions to simplify error handling and propagation.
144
+ * @example
145
+ * function* example(): Generator<Result<number>, number, any> {
146
+ * const result1 = yield* Result.ok(5);
147
+ * const result2 = yield* Result.ok(10);
148
+ * return result1 + result2;
149
+ * }
150
+ */
32
151
  [Symbol.iterator](): Generator<Result<T, E>, T, any>;
33
- static run<T, E>(generator: () => Generator<Result<any, E>, T, any>): Result<T, E>;
152
+ /**
153
+ * Runs a generator function that yields Result instances, propagating errors automatically.
154
+ * If any yielded Result is an error, the execution stops and the error is returned.
155
+ * If all yielded Results are successful, returns a successful Result with the final returned value.
156
+ *
157
+ * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.
158
+ * Think of it as "async/await" but for Result handling in generator functions.
159
+ *
160
+ * @param generator a generator function that yields Result instances
161
+ * @returns a Result containing either the final successful value or the first encountered error
162
+ *
163
+ * @example
164
+ * const result = Result.run(function* () {
165
+ * const value1 = yield* Result.ok(5);
166
+ * const value2 = yield* Result.ok(10);
167
+ * return value1 + value2;
168
+ * });
169
+ */
170
+ static run<T, E extends ErrorBase = ErrorBase>(generator: () => Generator<Result<any, E>, T, any>): Result<T, E>;
34
171
  }
35
172
 
36
- type AsyncResultState<T, E> = {
173
+ /**
174
+ * Type representing the state of an AsyncResult.
175
+ * It can be 'idle', 'loading' with a promise, or a settled ResultState (success or error).
176
+ */
177
+ type AsyncResultState<T, E extends ErrorBase = ErrorBase> = {
37
178
  status: 'idle';
38
179
  } | {
39
180
  status: 'loading';
40
181
  promise: Promise<Result<T, E>>;
41
182
  } | ResultState<T, E>;
42
- type ChainFunction<I, O, E> = (input: I) => Result<O, E> | Promise<Result<O, E>>;
43
- type FlatChainFunction<I, O, E> = (input: I) => AsyncResult<O, E>;
44
- type AsyncResultListener<T, E> = (result: AsyncResult<T, E>) => any;
45
- declare class AsyncResult<T, E = ErrorBase> {
183
+ /**
184
+ * An Action is a function returning a Promise of a Result.
185
+ */
186
+ type Action<T, E extends ErrorBase = ErrorBase> = () => Promise<Result<T, E>>;
187
+ /**
188
+ * A LazyAction is an object containing a trigger function to start the action, and the AsyncResult representing the action's state.
189
+ */
190
+ type LazyAction<T, E extends ErrorBase = ErrorBase> = {
191
+ trigger: () => void;
192
+ result: AsyncResult<T, E>;
193
+ };
194
+ /**
195
+ * A ChainStep is a function that takes an arbitrary input and returns a Result or a Promise of a Result.
196
+ * It takes an input of type I and returns either a Result<O, E> or a Promise<Result<O, E>>.
197
+ *
198
+ * Used for chaining operations on AsyncResult.
199
+ */
200
+ type ChainStep<I, O, E extends ErrorBase = ErrorBase> = (input: I) => Result<O, E> | Promise<Result<O, E>>;
201
+ /**
202
+ * A FlatChainStep is a function that takes an arbitrary input and returns an AsyncResult.
203
+ * It takes an input of type I and returns an AsyncResult<O, E>.
204
+ *
205
+ * Used for flat-chaining operations on AsyncResult.
206
+ */
207
+ type FlatChainStep<I, O, E extends ErrorBase = ErrorBase> = (input: I) => AsyncResult<O, E>;
208
+ /**
209
+ * Type representing a generator function that yields AsyncResult instances and returns a final value of type T.
210
+ *
211
+ * Used for running generators with AsyncResult.run().
212
+ */
213
+ type AsyncResultGenerator<T> = Generator<AsyncResult<any, any>, T, any>;
214
+ /**
215
+ * Type representing a listener function for AsyncResult state changes.
216
+ */
217
+ type AsyncResultListener<T, E extends ErrorBase = ErrorBase> = (result: AsyncResult<T, E>) => any;
218
+ /**
219
+ * Class representing the asynchronous result of an operation that can be idle, loading, successful, or failed.
220
+ * Provides methods for listening to state changes, updating state, chaining operations, and converting to and from promises.
221
+ * @class AsyncResult
222
+ * @template T - The type of the successful result value.
223
+ * @template E - The type of the error, extending ErrorBase (default is ErrorBase).
224
+ */
225
+ declare class AsyncResult<T, E extends ErrorBase = ErrorBase> {
46
226
  private _state;
47
227
  private _listeners;
48
228
  constructor(state?: AsyncResultState<T, E>);
229
+ /**
230
+ * Returns the internal state of the AsyncResult.
231
+ */
49
232
  get state(): AsyncResultState<T, E>;
50
- private set state(value);
51
- static ok<T>(value: T): AsyncResult<T, never>;
52
- static err<E>(error: E): AsyncResult<never, E>;
233
+ /**
234
+ * Checks if the AsyncResult is successful.
235
+ * @returns whether or not the result is successful
236
+ */
53
237
  isSuccess(): boolean;
238
+ /**
239
+ * Checks if the AsyncResult is an error.
240
+ * @returns whether or not the result is an error
241
+ */
54
242
  isError(): boolean;
243
+ /**
244
+ * Checks if the AsyncResult is idle.
245
+ * @returns whether or not the result is idle
246
+ */
247
+ isIdle(): boolean;
248
+ /**
249
+ * Checks if the AsyncResult is loading.
250
+ * @returns whether or not the result is loading
251
+ */
55
252
  isLoading(): boolean;
56
- listen(listener: AsyncResultListener<T, E>, immediate?: boolean): () => void;
57
- listenUntilSettled(listener: AsyncResultListener<T, E>, immediate?: boolean): () => void;
58
- setState(newState: AsyncResultState<T, E>): void;
59
- copyOnceSettled(other: AsyncResult<T, E>): void;
60
- update(newState: AsyncResultState<T, E>): void;
61
- updateToValue(value: T): void;
62
- updateToError(error: E): void;
63
- updateFromResultPromise(promise: Promise<Result<T, E>>): void;
64
- static fromResultPromise<T, E>(promise: Promise<Result<T, E>>): AsyncResult<T, E>;
65
- updateFromValuePromise(promise: Promise<T>): void;
66
- static fromValuePromise<T, E>(promise: Promise<T>): AsyncResult<T, E>;
253
+ /**
254
+ * Returns the successful value if the AsyncResult is in a success state, otherwise returns null.
255
+ * @returns the successful value or null
256
+ */
257
+ unwrapOrNull(): T | null;
258
+ /**
259
+ * Returns the successful value if the AsyncResult is in a success state, otherwise throws an error.
260
+ * @returns the successful value
261
+ * @throws an normal JS Error if the result is not successful
262
+ */
263
+ unwrapOrThrow(): T;
264
+ private set state(value);
265
+ private setState;
266
+ /**
267
+ * Creates a successful AsyncResult with the given value.
268
+ * @param value the result of the successful operation
269
+ * @returns a successful AsyncResult
270
+ */
271
+ static ok<T>(value: T): AsyncResult<T, never>;
272
+ /**
273
+ * Creates an error AsyncResult with the given error.
274
+ * @param error the error of the failed operation
275
+ * @returns an error AsyncResult
276
+ */
277
+ static err<E extends ErrorBase = ErrorBase>(error: E): AsyncResult<never, E>;
278
+ /**
279
+ * Creates an error AsyncResult with a new ErrorBase constructed from the given parameters.
280
+ * @param code the error code
281
+ * @param message the error message (optional)
282
+ * @param thrownError the original error object, if any (optional)
283
+ * @param log whether to log the error upon creation (default is true)
284
+ * @returns an error AsyncResult
285
+ */
286
+ static errTag(code: string, message?: string, thrownError?: unknown, log?: boolean): AsyncResult<never, ErrorBase>;
287
+ /**
288
+ * Updates the AsyncResult to a successful state with the given value.
289
+ * Like AsyncResult.ok, but in place.
290
+ * @param value the successful value
291
+ */
292
+ updateFromValue(value: T): this;
293
+ /**
294
+ * Updates the AsyncResult to an error state with the given error.
295
+ * Like AsyncResult.err, but in place.
296
+ * @param error the error
297
+ */
298
+ updateFromError(error: E): this;
299
+ /**
300
+ * Creates an AsyncResult from a promise that resolves to a value.
301
+ * The AsyncResult is initially in a loading state, and updates to a successful state once the promise resolves.
302
+ * If the promise rejects, the AsyncResult is updated to an error state with the caught error.
303
+ *
304
+ * Like AsyncResult.fromResultPromise, but for promise that only resolves to a successful value and not a Result.
305
+ *
306
+ * @param promise the promise that resolves to a value
307
+ * @returns an AsyncResult representing the state of the promise
308
+ */
309
+ static fromValuePromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<T>): AsyncResult<T, E>;
310
+ /**
311
+ * Updates the AsyncResult to a loading state with the given promise.
312
+ * The AsyncResult is initially in a loading state, and updates to a successful state once the promise resolves.
313
+ * If the promise rejects, the AsyncResult is updated to an error state with the caught error.
314
+ *
315
+ * Like AsyncResult.fromValuePromise, but in place.
316
+ *
317
+ * @param promise the promise that resolves to a value
318
+ */
319
+ updateFromValuePromise(promise: Promise<T>): this;
320
+ /**
321
+ * Waits for the AsyncResult to settle (either success or error) if it is currently loading.
322
+ * @returns itself once settled
323
+ */
67
324
  waitForSettled(): Promise<AsyncResult<T, E>>;
68
- waitForSettledResult(): Promise<Result<T, E>>;
325
+ /**
326
+ * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns a Result representing the settled state.
327
+ * @returns a Result representing the settled state
328
+ */
69
329
  toResultPromise(): Promise<Result<T, E>>;
70
- toValuePromiseThrow(): Promise<T>;
330
+ /**
331
+ * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns the successful value or throws an error.
332
+ * @returns the successful value
333
+ * @throws an normal JS Error if the result is not successful
334
+ */
335
+ toValueOrThrowPromise(): Promise<T>;
336
+ /**
337
+ * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns the successful value or null.
338
+ * @returns either the successful value or null
339
+ */
71
340
  toValueOrNullPromise(): Promise<T | null>;
72
- unwrapOrNull(): T | null;
73
- unwrapOrNullOnceSettled(): Promise<T | null>;
74
- unwrapOrThrow(): T;
75
- unwrapOrThrowOnceSettled(): Promise<T>;
76
- chain<O, E2>(fn: ChainFunction<T, O, E | E2>): AsyncResult<O, E | E2>;
77
- flatChain<O, E2>(fn: FlatChainFunction<T, O, E | E2>): AsyncResult<O, E | E2>;
341
+ /**
342
+ * Creates an AsyncResult from a promise that resolves to a Result.
343
+ * The AsyncResult is initially in a loading state, and updates to the settled state once the promise resolves.
344
+ * If the promise rejects, the AsyncResult is updated to an error state with a default ErrorBase.
345
+ *
346
+ * @param promise the promise that resolves to a Result
347
+ * @returns an AsyncResult representing the state of the promise
348
+ */
349
+ static fromResultPromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<Result<T, E>>): AsyncResult<T, E>;
350
+ /**
351
+ * Updates the AsyncResult to a loading state with the given promise.
352
+ * The promise must produce a Result once settled (meaning it should return the error in the result when possible).
353
+ * If the promise rejects, the AsyncResult is updated to an error state with a default ErrorBase.
354
+ *
355
+ * Like AsyncResult.fromResultPromise, but in place.
356
+ *
357
+ * @param promise the promise that resolves to a Result
358
+ */
359
+ updateFromResultPromise(promise: Promise<Result<T, E>>): this;
360
+ /**
361
+ * Adds a listener that is called whenever the AsyncResult state changes.
362
+ * @param listener the listener function to add
363
+ * @param immediate whether to call the listener immediately with the current state (default is true)
364
+ * @returns a function to remove the listener
365
+ */
366
+ listen(listener: AsyncResultListener<T, E>, immediate?: boolean): () => void;
367
+ /**
368
+ * Adds a listener that is called whenever the AsyncResult state changes, and automatically unsubscribes once it is settled (success or error).
369
+ * @param listener the listener function to add
370
+ * @param immediate whether to call the listener immediately with the current state (default is true)
371
+ * @returns a function to remove the listener
372
+ */
373
+ listenUntilSettled(listener: AsyncResultListener<T, E>, immediate?: boolean): () => void;
374
+ /**
375
+ * Mirrors the state of another AsyncResult into this one.
376
+ * Whenever the other AsyncResult changes state, this AsyncResult is updated to match.
377
+ * @param other the AsyncResult to mirror
378
+ * @returns a function to stop mirroring
379
+ */
78
380
  mirror(other: AsyncResult<T, E>): () => void;
381
+ /**
382
+ * Mirrors the state of another AsyncResult into this one, until the other AsyncResult is settled (success or error).
383
+ * Whenever the other AsyncResult changes state, this AsyncResult is updated to match, until the other AsyncResult is settled.
384
+ * @param other the AsyncResult to mirror
385
+ * @returns a function to stop mirroring
386
+ */
79
387
  mirrorUntilSettled(other: AsyncResult<T, E>): () => void;
388
+ /**
389
+ * Creates a LazyAction that can be triggered to run the given Action.
390
+ * @param action the Action to run when triggered
391
+ * @returns an object containing the trigger function and the associated AsyncResult
392
+ */
393
+ static makeLazyAction<T, E extends ErrorBase = ErrorBase>(action: Action<T, E>): LazyAction<T, E>;
394
+ /**
395
+ * Chains the current AsyncResult with another operation that returns a Result or a Promise of a Result.
396
+ *
397
+ * If the current AsyncResult is loading, waits for it to settle first, then applies the provided function to its value.
398
+ * If the current AsyncResult is successful, applies the provided function to its value.
399
+ * Otherwise, returns the current error.
400
+ *
401
+ * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.
402
+ *
403
+ * @param fn a function taking as input the successful value of the result, and returning a Result or a Promise of a Result describing the result of its own operation
404
+ * @returns a new AsyncResult that has either the successful value of the operation, or either the error of the current result or the error returned by fn
405
+ */
406
+ chain<O, E2 extends ErrorBase = ErrorBase>(fn: ChainStep<T, O, E | E2>): AsyncResult<O, E | E2>;
407
+ /**
408
+ * Chains the current AsyncResult with another operation that returns an AsyncResult.
409
+ *
410
+ * If the current AsyncResult is loading, waits for it to settle first, then applies the provided function to its value.
411
+ * If the current AsyncResult is successful, applies the provided function to its value.
412
+ * Otherwise, returns the current error.
413
+ *
414
+ * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.
415
+ *
416
+ * Like chain, but for functions returning AsyncResult instead of Result.
417
+ *
418
+ * @param fn a function taking as input the successful value of the result, and returning an AsyncResult describing the result of its own operation
419
+ * @returns a new AsyncResult that has either the successful value of the operation, or either the error of the current result or the error returned by fn
420
+ */
421
+ flatChain<O, E2 extends ErrorBase = ErrorBase>(fn: FlatChainStep<T, O, E | E2>): AsyncResult<O, E | E2>;
422
+ /**
423
+ * Ensures that all provided AsyncResults are successful.
424
+ * If all are successful, returns an AsyncResult containing an array of their values.
425
+ * If any AsyncResult is an error, returns an AsyncResult with the first encountered error.
426
+ * @param results an array of AsyncResults to check
427
+ * @returns an AsyncResult containing either an array of successful values or the first encountered error
428
+ */
80
429
  static ensureAvailable<R extends readonly AsyncResult<any, any>[]>(results: R): AsyncResult<{
81
430
  [K in keyof R]: R[K] extends AsyncResult<infer T, any> ? T : never;
82
431
  }, R[number] extends AsyncResult<any, infer E> ? E : never>;
432
+ /**
433
+ * Yields the current AsyncResult, and if it is successful, returns its value.
434
+ * This allows using AsyncResult instances in generator functions to simplify error handling and propagation.
435
+ * @example
436
+ * function* example(): Generator<AsyncResult<number>, number, any> {
437
+ * const result1 = yield* AsyncResult.ok(5);
438
+ * const result2 = yield* AsyncResult.ok(10);
439
+ * return result1 + result2;
440
+ * }
441
+ */
83
442
  [Symbol.iterator](): Generator<AsyncResult<T, E>, T, any>;
84
443
  private static _runGeneratorProcessor;
85
- static run<T, E = ErrorBase>(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): AsyncResult<T, E>;
86
- runInPlace(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): void;
444
+ /**
445
+ * Runs a generator function that yields AsyncResult instances, propagating errors automatically.
446
+ * If any yielded AsyncResult is an error, the execution stops and the error is returned.
447
+ * If all yielded AsyncResults are successful, returns a successful AsyncResult with the final returned value.
448
+ *
449
+ * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.
450
+ * Think of it as "async/await" but for AsyncResult handling in generator functions.
451
+ *
452
+ * @param generatorFunc a generator function that yields AsyncResult instances
453
+ * @returns a AsyncResult containing either the final successful value or the first encountered error
454
+ *
455
+ * @example
456
+ * const result = AsyncResult.run(function* () {
457
+ * const value1 = yield* AsyncResult.ok(5);
458
+ * const value2 = yield* AsyncResult.ok(10);
459
+ * return value1 + value2;
460
+ * }
461
+ */
462
+ static run<T, E extends ErrorBase = ErrorBase>(generatorFunc: () => AsyncResultGenerator<T>): AsyncResult<T, E>;
463
+ /**
464
+ * Runs a generator function that yields AsyncResult instances, propagating errors automatically, and updates this AsyncResult in place.
465
+ * If any yielded AsyncResult is an error, the execution stops and this AsyncResult is updated to that error.
466
+ * If all yielded AsyncResults are successful, this AsyncResult is updated to a successful state with the final returned value.
467
+ *
468
+ * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.
469
+ * Think of it as "async/await" but for AsyncResult handling in generator functions.
470
+ *
471
+ * @param generatorFunc a generator function that yields AsyncResult instances
472
+ */
473
+ runInPlace(generatorFunc: () => AsyncResultGenerator<T>): this;
474
+ log(name?: string): void;
475
+ debug(name?: string): () => void;
87
476
  }
88
477
 
89
478
  type KeyedAsyncCacheRefetchOptions = {
90
479
  policy: 'refetch' | 'if-error' | 'no-refetch';
91
480
  };
92
- declare class KeyedAsyncCache<P, V, E = ErrorBase> {
481
+ /**
482
+ * A cache for asynchronous operations that maps parameter sets to their corresponding AsyncResult.
483
+ * Supports automatic refetching based on specified policies.
484
+ *
485
+ * @template P - The type of the parameters used to fetch values.
486
+ * @template V - The type of the values being fetched.
487
+ * @template E - The type of the error, extending ErrorBase (default is ErrorBase).
488
+ */
489
+ declare class KeyedAsyncCache<P, V, E extends ErrorBase = ErrorBase> {
93
490
  private _cache;
94
491
  private _fetcher;
95
492
  private _paramsToKey;
96
- constructor(fetcher: ChainFunction<P, V, E>, paramsToKey?: (params: P) => string);
493
+ private _cacheTTL?;
494
+ /**
495
+ * Creates a new KeyedAsyncCache instance.
496
+ * @param fetcher the function used to fetch values based on parameters
497
+ * @param paramsToKey a function that converts parameters to a unique string key (default uses JSON.stringify for objects)
498
+ * @param cacheTTL optional time-to-live for cache entries in milliseconds
499
+ */
500
+ constructor(fetcher: ChainStep<P, V, E>, paramsToKey?: (params: P) => string, cacheTTL?: number);
97
501
  private makeCacheItem;
98
502
  private shouldRefetch;
503
+ private updateOrCreateCacheItemFromParams;
504
+ /**
505
+ * Gets the AsyncResult for the given parameters, fetching it if not cached or if refetching is required.
506
+ * @param params the parameters to fetch the value
507
+ * @param refetch options determining whether to refetch the value
508
+ * @returns the AsyncResult corresponding to the given parameters
509
+ */
99
510
  get(params: P, refetch?: KeyedAsyncCacheRefetchOptions): AsyncResult<V, E>;
511
+ /**
512
+ * Gets the settled state of the AsyncResult for the given parameters, fetching it if not cached or if refetching is required.
513
+ * Waits for the AsyncResult to settle before returning its state.
514
+ * @param params the parameters to fetch the value
515
+ * @param refetch options determining whether to refetch the value
516
+ * @returns a promise resolving to the settled state of the AsyncResult
517
+ */
100
518
  getSettledState(params: P, refetch?: KeyedAsyncCacheRefetchOptions): Promise<AsyncResultState<V, E>>;
519
+ /**
520
+ * Checks if any cached AsyncResult is currently loading.
521
+ * @returns whether any cached AsyncResult is loading
522
+ */
101
523
  anyLoading(): boolean;
524
+ /**
525
+ * Clears the entire cache.
526
+ */
102
527
  clear(): void;
528
+ /**
529
+ * Invalidates the cache entry for the given key.
530
+ * @param key the key of the cache entry to invalidate
531
+ */
532
+ invalidateKey(key: string): void;
533
+ /**
534
+ * Invalidates the cache entry for the given parameters.
535
+ * @param params the parameters of the cache entry to invalidate
536
+ */
537
+ invalidateParams(params: P): void;
538
+ /**
539
+ * Invalidates all cache entries.
540
+ */
541
+ invalidateAll(): void;
103
542
  }
104
543
 
105
- export { AsyncResult, type AsyncResultListener, type AsyncResultState, type ChainFunction, ErrorBase, type FlatChainFunction, KeyedAsyncCache, Result, type ResultState };
544
+ export { type Action, AsyncResult, type AsyncResultGenerator, type AsyncResultListener, type AsyncResultState, type ChainStep, ErrorBase, type FlatChainStep, KeyedAsyncCache, type LazyAction, Result, type ResultState };