unwrapped 0.1.6 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/core/index.d.mts +8 -2
- package/dist/core/index.d.ts +8 -2
- package/dist/core/index.js +19 -13
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.mjs +19 -13
- package/dist/core/index.mjs.map +1 -1
- package/dist/vue/index.d.mts +121 -126
- package/dist/vue/index.d.ts +121 -126
- package/dist/vue/index.js +30 -50
- package/dist/vue/index.js.map +1 -1
- package/dist/vue/index.mjs +30 -50
- package/dist/vue/index.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
package/dist/core/index.d.mts
CHANGED
|
@@ -484,6 +484,11 @@ declare class AsyncResult<T, E extends ErrorBase = ErrorBase> {
|
|
|
484
484
|
* The possible states of an AsyncResultList.
|
|
485
485
|
*/
|
|
486
486
|
type AsyncResultListState = "any-loading" | "all-settled";
|
|
487
|
+
interface AsyncResultListItem<T = any, E extends ErrorBase = ErrorBase> {
|
|
488
|
+
key: string;
|
|
489
|
+
result: AsyncResult<T, E>;
|
|
490
|
+
unsub: () => void;
|
|
491
|
+
}
|
|
487
492
|
/**
|
|
488
493
|
* A list that manages multiple AsyncResult instances, tracking their states and providing utilities to monitor them.
|
|
489
494
|
*/
|
|
@@ -494,7 +499,7 @@ declare class AsyncResultList<T = any, E extends ErrorBase = ErrorBase> {
|
|
|
494
499
|
/**
|
|
495
500
|
* Gets the current tasks in the AsyncResultList.
|
|
496
501
|
*/
|
|
497
|
-
get tasks(): Map<string,
|
|
502
|
+
get tasks(): Map<string, AsyncResultListItem<T, E>>;
|
|
498
503
|
/**
|
|
499
504
|
* Gets the number of tasks in the list.
|
|
500
505
|
*/
|
|
@@ -523,6 +528,7 @@ declare class AsyncResultList<T = any, E extends ErrorBase = ErrorBase> {
|
|
|
523
528
|
* @returns the added AsyncResult task
|
|
524
529
|
*/
|
|
525
530
|
add(key: string, task: AsyncResult<T, E>, removeOnSettle?: boolean): AsyncResult<T, E>;
|
|
531
|
+
clear(): void;
|
|
526
532
|
/**
|
|
527
533
|
* Checks if any task in the list is currently loading.
|
|
528
534
|
* @returns true if any task is loading, false otherwise
|
|
@@ -652,4 +658,4 @@ declare class KeyedAsyncCache<P, V, E extends ErrorBase = ErrorBase> {
|
|
|
652
658
|
|
|
653
659
|
declare function delay(ms: number): AsyncResult<true>;
|
|
654
660
|
|
|
655
|
-
export { type Action, AsyncResult, type AsyncResultGenerator, AsyncResultList, type AsyncResultListState, type AsyncResultListener, type AsyncResultState, type ChainStep, ErrorBase, type FlatChainStep, KeyedAsyncCache, type LazyAction, Result, type ResultState, delay };
|
|
661
|
+
export { type Action, AsyncResult, type AsyncResultGenerator, AsyncResultList, type AsyncResultListItem, type AsyncResultListState, type AsyncResultListener, type AsyncResultState, type ChainStep, ErrorBase, type FlatChainStep, KeyedAsyncCache, type LazyAction, Result, type ResultState, delay };
|
package/dist/core/index.d.ts
CHANGED
|
@@ -484,6 +484,11 @@ declare class AsyncResult<T, E extends ErrorBase = ErrorBase> {
|
|
|
484
484
|
* The possible states of an AsyncResultList.
|
|
485
485
|
*/
|
|
486
486
|
type AsyncResultListState = "any-loading" | "all-settled";
|
|
487
|
+
interface AsyncResultListItem<T = any, E extends ErrorBase = ErrorBase> {
|
|
488
|
+
key: string;
|
|
489
|
+
result: AsyncResult<T, E>;
|
|
490
|
+
unsub: () => void;
|
|
491
|
+
}
|
|
487
492
|
/**
|
|
488
493
|
* A list that manages multiple AsyncResult instances, tracking their states and providing utilities to monitor them.
|
|
489
494
|
*/
|
|
@@ -494,7 +499,7 @@ declare class AsyncResultList<T = any, E extends ErrorBase = ErrorBase> {
|
|
|
494
499
|
/**
|
|
495
500
|
* Gets the current tasks in the AsyncResultList.
|
|
496
501
|
*/
|
|
497
|
-
get tasks(): Map<string,
|
|
502
|
+
get tasks(): Map<string, AsyncResultListItem<T, E>>;
|
|
498
503
|
/**
|
|
499
504
|
* Gets the number of tasks in the list.
|
|
500
505
|
*/
|
|
@@ -523,6 +528,7 @@ declare class AsyncResultList<T = any, E extends ErrorBase = ErrorBase> {
|
|
|
523
528
|
* @returns the added AsyncResult task
|
|
524
529
|
*/
|
|
525
530
|
add(key: string, task: AsyncResult<T, E>, removeOnSettle?: boolean): AsyncResult<T, E>;
|
|
531
|
+
clear(): void;
|
|
526
532
|
/**
|
|
527
533
|
* Checks if any task in the list is currently loading.
|
|
528
534
|
* @returns true if any task is loading, false otherwise
|
|
@@ -652,4 +658,4 @@ declare class KeyedAsyncCache<P, V, E extends ErrorBase = ErrorBase> {
|
|
|
652
658
|
|
|
653
659
|
declare function delay(ms: number): AsyncResult<true>;
|
|
654
660
|
|
|
655
|
-
export { type Action, AsyncResult, type AsyncResultGenerator, AsyncResultList, type AsyncResultListState, type AsyncResultListener, type AsyncResultState, type ChainStep, ErrorBase, type FlatChainStep, KeyedAsyncCache, type LazyAction, Result, type ResultState, delay };
|
|
661
|
+
export { type Action, AsyncResult, type AsyncResultGenerator, AsyncResultList, type AsyncResultListItem, type AsyncResultListState, type AsyncResultListener, type AsyncResultState, type ChainStep, ErrorBase, type FlatChainStep, KeyedAsyncCache, type LazyAction, Result, type ResultState, delay };
|
package/dist/core/index.js
CHANGED
|
@@ -733,7 +733,7 @@ var AsyncResultList = class {
|
|
|
733
733
|
* Gets all tasks in the list as an array.
|
|
734
734
|
*/
|
|
735
735
|
get items() {
|
|
736
|
-
return Array.from(this._list.values());
|
|
736
|
+
return Array.from(this._list.values()).map((i) => i.result);
|
|
737
737
|
}
|
|
738
738
|
/**
|
|
739
739
|
* Gets the current state of the AsyncResultList.
|
|
@@ -769,30 +769,36 @@ var AsyncResultList = class {
|
|
|
769
769
|
* @returns the added AsyncResult task
|
|
770
770
|
*/
|
|
771
771
|
add(key, task, removeOnSettle = true) {
|
|
772
|
-
|
|
773
|
-
this.state = "any-loading";
|
|
772
|
+
let unsub = null;
|
|
774
773
|
if (removeOnSettle) {
|
|
775
|
-
task.listenUntilSettled((r) => {
|
|
774
|
+
unsub = task.listenUntilSettled((r) => {
|
|
776
775
|
if (r.isLoading() || r.isIdle()) return;
|
|
777
776
|
this._onTaskFinished();
|
|
778
777
|
this._list.delete(key);
|
|
779
778
|
}, true);
|
|
780
779
|
} else {
|
|
781
|
-
task.listen((r) => {
|
|
780
|
+
unsub = task.listen((r) => {
|
|
782
781
|
if (r.isLoading() || r.isIdle()) return;
|
|
783
782
|
this._onTaskFinished();
|
|
784
783
|
}, true);
|
|
785
784
|
}
|
|
785
|
+
this._list.set(key, { key, result: task, unsub });
|
|
786
|
+
this.state = "any-loading";
|
|
786
787
|
return task;
|
|
787
788
|
}
|
|
789
|
+
clear() {
|
|
790
|
+
this._list.forEach(({ unsub }) => unsub());
|
|
791
|
+
this._list.clear();
|
|
792
|
+
this.state = "all-settled";
|
|
793
|
+
}
|
|
788
794
|
// === Querying tasks ===
|
|
789
795
|
/**
|
|
790
796
|
* Checks if any task in the list is currently loading.
|
|
791
797
|
* @returns true if any task is loading, false otherwise
|
|
792
798
|
*/
|
|
793
799
|
anyLoading() {
|
|
794
|
-
for (const
|
|
795
|
-
if (
|
|
800
|
+
for (const item of this._list.values()) {
|
|
801
|
+
if (item.result.isLoading()) {
|
|
796
802
|
return true;
|
|
797
803
|
}
|
|
798
804
|
}
|
|
@@ -805,9 +811,9 @@ var AsyncResultList = class {
|
|
|
805
811
|
*/
|
|
806
812
|
getAllFiltered(predicate) {
|
|
807
813
|
const filtered = [];
|
|
808
|
-
for (const
|
|
809
|
-
if (predicate(
|
|
810
|
-
filtered.push(
|
|
814
|
+
for (const item of this._list.values()) {
|
|
815
|
+
if (predicate(item.result)) {
|
|
816
|
+
filtered.push(item.result);
|
|
811
817
|
}
|
|
812
818
|
}
|
|
813
819
|
return filtered;
|
|
@@ -820,9 +826,9 @@ var AsyncResultList = class {
|
|
|
820
826
|
*/
|
|
821
827
|
getAllFilteredAndMap(filterPredicate, mapFunc) {
|
|
822
828
|
const results = [];
|
|
823
|
-
for (const
|
|
824
|
-
if (filterPredicate(
|
|
825
|
-
results.push(mapFunc(
|
|
829
|
+
for (const item of this._list.values()) {
|
|
830
|
+
if (filterPredicate(item.result)) {
|
|
831
|
+
results.push(mapFunc(item.result));
|
|
826
832
|
}
|
|
827
833
|
}
|
|
828
834
|
return results;
|
package/dist/core/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/index.ts","../../src/core/error.ts","../../src/core/result.ts","../../src/core/asyncResult.ts","../../src/core/asyncResultList.ts","../../src/core/cache.ts","../../src/core/utils.ts"],"sourcesContent":["export * from \"./error\";\nexport * from \"./result\";\nexport * from \"./asyncResult\";\nexport * from \"./asyncResultList\";\nexport * from \"./cache\";\nexport * from \"./utils\";","/**\n * Base class for error handling, providing structured error information and logging.\n * @class ErrorBase\n * @property {string} code - The error code.\n * @property {string | undefined} message - The error message (optional).\n * @property {unknown} thrownError - The original error object, if any (optional).\n * \n * @constructor\n * @param {string} code - The error code.\n * @param {string} [message] - The error message.\n * @param {unknown} [thrownError] - The original error object, if any.\n * @param {boolean} [log=true] - Whether to log the error upon creation.\n */\nexport class ErrorBase {\n code: string;\n message?: string | undefined;\n thrownError?: unknown;\n\n constructor(code: string, message?: string, thrownError?: unknown, log: boolean = true) {\n this.code = code;\n this.message = message;\n this.thrownError = thrownError;\n\n if (log) {\n this.logError();\n }\n }\n\n /**\n * Converts the error to a string representation, on the format \"Error {code}: {message}\".\n * @returns a string representation of the error\n */\n toString(): string {\n return `Error ${this.code}: ${this.message ?? ''}`;\n }\n\n /**\n * Logs the error to the console, uses console.error and ErrorBase.toString() internally.\n * Logs thrownError if it was provided on creation.\n */\n logError(): void {\n if (this.thrownError) {\n console.error(this.toString(), this.thrownError);\n } else {\n console.error(this.toString());\n }\n }\n}\n","import { ErrorBase } from \"./error\";\n\n/**\n * Type representing the state of a Result, either success with a value of type T,\n * or error with an error of type E (defaulting to ErrorBase).\n */\nexport type ResultState<T, E extends ErrorBase = ErrorBase> =\n | { status: 'success'; value: T }\n | { status: 'error'; error: E };\n\n/**\n * Class representing the result of an operation that can either succeed with a value of type T,\n * or fail with an error of type E (defaulting to ErrorBase).\n * Provides methods for unwrapping the result, chaining operations, and handling errors.\n * @class Result\n * @template T - The type of the successful result value.\n * @template E - The type of the error, extending ErrorBase (default is ErrorBase).\n */\nexport class Result<T, E extends ErrorBase = ErrorBase> {\n private _state: ResultState<T, E>;\n\n /**\n * Creates a new Result instance with the given state.\n * @param state the state of the created Result\n */\n constructor(state: ResultState<T, E>) {\n this._state = state;\n }\n\n /** Returns the internal state of the Result. */\n get state() {\n return this._state;\n }\n\n /**\n * Checks if the Result is successful.\n * @returns whether or not the result is successful\n */\n isSuccess(): boolean {\n return this._state.status === 'success';\n }\n\n /**\n * Checks if the Result is an error.\n * @returns whether or not the result is an error\n */\n isError(): boolean {\n return this._state.status === 'error';\n }\n\n /**\n * Creates a successful Result with the given value.\n * @param value the result of the successful operation\n * @returns a successful Result\n */\n static ok<T, E extends ErrorBase = ErrorBase>(value: T): Result<T, E> {\n return new Result({ status: 'success', value });\n }\n\n /**\n * Creates an error Result with the given error.\n * @param error the error of the failed operation\n * @returns an error Result\n */\n static err<E extends ErrorBase = ErrorBase>(error: E): Result<never, E> {\n return new Result({ status: 'error', error });\n }\n\n /**\n * Creates an error Result (containing an ErrorBase) with the given error code and optional message.\n * @param code the error code\n * @param message an optional error message\n * @returns an error Result\n */\n static errTag(code: string, message?: string, thrownError?: unknown): Result<never, ErrorBase> {\n return Result.err(new ErrorBase(code, message, thrownError));\n }\n\n /**\n * Returns the successful value (if the Result is successful) or null (if it is an error).\n * @returns either the successful value or null\n */\n unwrapOrNull(): T | null {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return null;\n }\n\n /**\n * Returns the successful value (if the Result is successful) or throws an error (if it is an error).\n * @returns the successful value\n * @throws an normal JS Error if the result is not successful\n */\n unwrapOrThrow(): T {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n throw new Error('Tried to unwrap a Result that is not successful');\n }\n\n /**\n * Returns the successful value (if the Result is successful) or a default value (if it is an error).\n * @param defaultValue the default value to return if the Result is an error\n * @returns either the successful value or the default value\n */\n unwrapOr<O>(defaultValue: O): T | O {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return defaultValue;\n }\n\n /**\n * Transforms a Promise of a successful value into a Promise of a Result,\n * catching any thrown errors and mapping them using the provided errorMapper function.\n * @param promise the promise to execute\n * @param errorMapper a function that maps a thrown error to a Result error\n * @returns a Promise resolving to a Result containing either the successful value or the mapped error\n */\n static tryPromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>> {\n return promise\n .then((value) => Result.ok<T, E>(value))\n .catch((error) => Result.err(errorMapper(error)));\n }\n\n /**\n * Executes an asynchronous function and transforms its result into a Result,\n * catching any thrown errors and mapping them using the provided errorMapper function.\n * Same as Result.tryPromise(fn(), errorMapper).\n * @param fn the asynchronous function to execute\n * @param errorMapper a function that maps a thrown error to a Result error\n * @returns a Promise resolving to a Result containing either the successful value or the mapped error\n */\n static tryFunction<T, E extends ErrorBase = ErrorBase>(fn: () => Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>> {\n return Result.tryPromise(fn(), errorMapper);\n }\n\n /**\n * Chains the current Result with another operation that returns a ResultState.\n * If the current Result is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * @param fn a function taking as input the successful value of the result, and returning a ResultState describing the result of its own operation\n * @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\n */\n chain<O, E2 extends ErrorBase = ErrorBase>(fn: (input: T) => ResultState<O, E | E2>): Result<O, E | E2> {\n if (this._state.status === 'success') {\n return new Result<O, E | E2>(fn(this._state.value));\n }\n return Result.err<E>(this._state.error);\n }\n\n /**\n * Chains the current Result with another operation that returns a Result.\n * If the current Result is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * Same as chain, but the function returns a Result directly instead of a ResultState.\n * @param fn a function taking as input the successful value of the result, and returning a Result describing the result of its own operation\n * @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\n */\n flatChain<O, E2 extends ErrorBase = ErrorBase>(fn: (input: T) => Result<O, E | E2>): Result<O, E | E2> {\n if (this._state.status === 'success') {\n return fn(this._state.value);\n }\n return Result.err<E>(this._state.error);\n }\n\n /**\n * @yields the current Result, and if it is successful, returns its value.\n * This allows using Result instances in generator functions to simplify error handling and propagation.\n * @example\n * function* example(): Generator<Result<number>, number, any> {\n * const result1 = yield* Result.ok(5);\n * const result2 = yield* Result.ok(10);\n * return result1 + result2;\n * }\n */\n *[Symbol.iterator](): Generator<Result<T, E>, T, any> {\n yield this;\n\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return undefined as T;\n }\n\n /**\n * Runs a generator function that yields Result instances, propagating errors automatically.\n * If any yielded Result is an error, the execution stops and the error is returned.\n * If all yielded Results are successful, returns a successful Result with the final returned value.\n * \n * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.\n * Think of it as \"async/await\" but for Result handling in generator functions.\n * \n * @param generator a generator function that yields Result instances\n * @returns a Result containing either the final successful value or the first encountered error\n * \n * @example\n * const result = Result.run(function* () {\n * const value1 = yield* Result.ok(5);\n * const value2 = yield* Result.ok(10);\n * return value1 + value2;\n * });\n */\n static run<T, E extends ErrorBase = ErrorBase>(generator: () => Generator<Result<any, E>, T, any>): Result<T, E> {\n const iterator = generator();\n let result = iterator.next();\n\n while (!result.done) {\n const yielded = result.value;\n if (yielded._state.status === 'error') {\n return Result.err(yielded._state.error);\n }\n result = iterator.next(yielded._state.value);\n }\n\n return Result.ok(result.value);\n }\n}\n","import { ErrorBase } from \"./error\";\nimport { Result, type ResultState } from \"./result\";\n\n/**\n * Type representing the state of an AsyncResult.\n * It can be 'idle', 'loading' with a promise, or a settled ResultState (success or error).\n */\nexport type AsyncResultState<T, E extends ErrorBase = ErrorBase> =\n | { status: 'idle' }\n | { status: 'loading'; promise: Promise<Result<T, E>> }\n | ResultState<T, E>;\n\n\n/**\n * An Action is a function returning a Promise of a Result.\n */\nexport type Action<T,E extends ErrorBase = ErrorBase> = () => Promise<Result<T, E>>;\n\n/**\n * A LazyAction is an object containing a trigger function to start the action, and the AsyncResult representing the action's state.\n */\nexport type LazyAction<T, E extends ErrorBase = ErrorBase> = {\n trigger: () => void;\n result: AsyncResult<T, E>;\n};\n\n/**\n * A ChainStep is a function that takes an arbitrary input and returns a Result or a Promise of a Result.\n * It takes an input of type I and returns either a Result<O, E> or a Promise<Result<O, E>>.\n * \n * Used for chaining operations on AsyncResult.\n */\nexport type ChainStep<I, O, E extends ErrorBase = ErrorBase> = (input: I) => Result<O, E> | Promise<Result<O, E>>;\n\n/**\n * A FlatChainStep is a function that takes an arbitrary input and returns an AsyncResult.\n * It takes an input of type I and returns an AsyncResult<O, E>.\n * \n * Used for flat-chaining operations on AsyncResult.\n */\nexport type FlatChainStep<I, O, E extends ErrorBase = ErrorBase> = (input: I) => AsyncResult<O, E>;\n\n/**\n * Type representing a generator function that yields AsyncResult instances and returns a final value of type T.\n * \n * Used for running generators with AsyncResult.run().\n */\nexport type AsyncResultGenerator<T> = Generator<AsyncResult<any, any>, T, any>;\n\n/**\n * Type representing a listener function for AsyncResult state changes.\n */\nexport type AsyncResultListener<T, E extends ErrorBase = ErrorBase> = (result: AsyncResult<T, E>) => any;\n\n/**\n * Class representing the asynchronous result of an operation that can be idle, loading, successful, or failed.\n * Provides methods for listening to state changes, updating state, chaining operations, and converting to and from promises.\n * @class AsyncResult\n * @template T - The type of the successful result value.\n * @template E - The type of the error, extending ErrorBase (default is ErrorBase).\n */\nexport class AsyncResult<T, E extends ErrorBase = ErrorBase> {\n private _state: AsyncResultState<T, E>;\n private _listeners: Set<AsyncResultListener<T, E>> = new Set();\n\n constructor(state?: AsyncResultState<T, E>) {\n this._state = state || { status: 'idle' };\n }\n\n\n\n // === Getting current state ===\n\n /**\n * Returns the internal state of the AsyncResult.\n */\n get state() {\n return this._state;\n }\n\n /**\n * Checks if the AsyncResult is successful.\n * @returns whether or not the result is successful\n */\n isSuccess() {\n return this._state.status === 'success';\n }\n\n /**\n * Checks if the AsyncResult is an error.\n * @returns whether or not the result is an error\n */\n isError() {\n return this._state.status === 'error';\n }\n\n /**\n * Checks if the AsyncResult is idle.\n * @returns whether or not the result is idle\n */\n isIdle() {\n return this._state.status === 'idle';\n }\n\n /**\n * Checks if the AsyncResult is loading.\n * @returns whether or not the result is loading\n */\n isLoading() {\n return this._state.status === 'loading';\n }\n\n\n\n // === Unwrapping values ===\n\n /**\n * Returns the successful value if the AsyncResult is in a success state, otherwise returns null.\n * @returns the successful value or null\n */\n unwrapOrNull(): T | null {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return null;\n }\n\n /**\n * Returns the successful value if the AsyncResult is in a success state, otherwise throws an error.\n * @returns the successful value\n * @throws an normal JS Error if the result is not successful\n */\n unwrapOrThrow(): T {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n throw new Error('Tried to unwrap an AsyncResult that is not successful');\n }\n\n /**\n * Returns the error value if the AsyncResult is in an error state, otherwise returns null.\n * @returns the error value or null\n */\n unwrapErrorOrNull(): E | null {\n if (this._state.status === 'error') {\n return this._state.error;\n }\n return null;\n }\n\n // === Creating/updating from settled values ===\n\n private set state(newState: AsyncResultState<T, E>) {\n this._state = newState;\n this._listeners.forEach((listener) => listener(this));\n }\n\n private setState(newState: AsyncResultState<T, E>) {\n this.state = newState;\n }\n\n /**\n * Creates a successful AsyncResult with the given value.\n * @param value the result of the successful operation\n * @returns a successful AsyncResult\n */\n static ok<T>(value: T): AsyncResult<T, never> {\n return new AsyncResult<T, never>({ status: 'success', value });\n }\n\n /**\n * Creates an error AsyncResult with the given error.\n * @param error the error of the failed operation\n * @returns an error AsyncResult\n */\n static err<E extends ErrorBase = ErrorBase>(error: E): AsyncResult<never, E> {\n return new AsyncResult<never, E>({ status: 'error', error });\n }\n\n /**\n * Creates an error AsyncResult with a new ErrorBase constructed from the given parameters.\n * @param code the error code\n * @param message the error message (optional)\n * @param thrownError the original error object, if any (optional)\n * @param log whether to log the error upon creation (default is true)\n * @returns an error AsyncResult\n */\n static errTag(code: string, message?: string, thrownError?: unknown, log: boolean = true): AsyncResult<never, ErrorBase> {\n const error = new ErrorBase(code, message, thrownError, log);\n return AsyncResult.err(error);\n }\n\n /**\n * Updates the AsyncResult to a successful state with the given value.\n * Like AsyncResult.ok, but in place.\n * @param value the successful value\n */\n updateFromValue(value: T) {\n this.state = { status: 'success', value };\n return this;\n }\n\n /**\n * Updates the AsyncResult to an error state with the given error.\n * Like AsyncResult.err, but in place.\n * @param error the error\n */\n updateFromError(error: E) {\n this.state = { status: 'error', error };\n return this;\n }\n\n\n\n // === Creating/updating from promises ===\n\n /**\n * Creates an AsyncResult from a promise that resolves to a value.\n * The AsyncResult is initially in a loading state, and updates to a successful state once the promise resolves.\n * If the promise rejects, the AsyncResult is updated to an error state with the caught error.\n * \n * Like AsyncResult.fromResultPromise, but for promise that only resolves to a successful value and not a Result.\n * \n * @param promise the promise that resolves to a value\n * @returns an AsyncResult representing the state of the promise\n */\n static fromValuePromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<T>): AsyncResult<T, E> {\n const result = new AsyncResult<T, E>();\n result.updateFromValuePromise(promise);\n return result;\n }\n\n /**\n * Updates the AsyncResult to a loading state with the given promise.\n * The AsyncResult is initially in a loading state, and updates to a successful state once the promise resolves.\n * If the promise rejects, the AsyncResult is updated to an error state with the caught error.\n * \n * Like AsyncResult.fromValuePromise, but in place.\n * \n * @param promise the promise that resolves to a value\n */\n updateFromValuePromise(promise: Promise<T>) {\n const resultStatePromise = async (): Promise<Result<T, E>> => {\n try {\n const value = await promise;\n return Result.ok(value);\n } catch (error) {\n return Result.err(error as E);\n }\n };\n return this.updateFromResultPromise(resultStatePromise());\n }\n\n\n // === Waiting for settled state and get result ===\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading.\n * @returns itself once settled\n */\n async waitForSettled(): Promise<AsyncResult<T, E>> {\n if (this._state.status === 'loading') {\n try {\n const value = await this._state.promise;\n this._state = value.state;\n } catch (error) {\n this._state = { status: 'error', error: error as E };\n }\n }\n return this;\n }\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns a Result representing the settled state.\n * @returns a Result representing the settled state\n */\n async toResultPromise(): Promise<Result<T, E>> {\n const settled = await this.waitForSettled();\n if (settled.state.status === 'idle' || settled.state.status === 'loading') {\n throw new Error('Cannot convert idle or loading AsyncResult to ResultState');\n }\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n return Result.ok(settled.state.value);\n }\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns the successful value or throws an error.\n * @returns the successful value\n * @throws an normal JS Error if the result is not successful\n */\n async toValueOrThrowPromise(): Promise<T> {\n const settled = await this.waitForSettled();\n return settled.unwrapOrThrow();\n }\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns the successful value or null.\n * @returns either the successful value or null\n */\n async toValueOrNullPromise(): Promise<T | null> {\n const settled = await this.waitForSettled();\n return settled.unwrapOrNull();\n }\n\n /**\n * Creates an AsyncResult from a promise that resolves to a Result.\n * The AsyncResult is initially in a loading state, and updates to the settled state once the promise resolves.\n * If the promise rejects, the AsyncResult is updated to an error state with a default ErrorBase.\n * \n * @param promise the promise that resolves to a Result\n * @returns an AsyncResult representing the state of the promise\n */\n static fromResultPromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<Result<T, E>>): AsyncResult<T, E> {\n const result = new AsyncResult<T, E>();\n result.updateFromResultPromise(promise);\n return result;\n }\n\n /**\n * Updates the AsyncResult to a loading state with the given promise.\n * The promise must produce a Result once settled (meaning it should return the error in the result when possible).\n * If the promise rejects, the AsyncResult is updated to an error state with a default ErrorBase.\n * \n * Like AsyncResult.fromResultPromise, but in place.\n * \n * @param promise the promise that resolves to a Result\n */\n updateFromResultPromise(promise: Promise<Result<T, E>>) {\n this.state = { status: 'loading', promise };\n promise\n .then((res) => {\n this.state = res.state;\n })\n .catch((error) => {\n this.updateFromError(new ErrorBase('defect_on_updateFromResultPromise', 'The promise provided to AsyncResult rejected', error) as E);\n });\n return this;\n }\n\n\n // === Listeners ===\n\n /**\n * Adds a listener that is called whenever the AsyncResult state changes.\n * @param listener the listener function to add\n * @param immediate whether to call the listener immediately with the current state (default is true)\n * @returns a function to remove the listener\n */\n listen(listener: AsyncResultListener<T, E>, immediate = true) {\n this._listeners.add(listener);\n if (immediate) {\n listener(this);\n }\n\n return () => {\n this._listeners.delete(listener);\n };\n }\n\n /**\n * Adds a listener that is called whenever the AsyncResult state changes, and automatically unsubscribes once it is settled (success or error).\n * @param listener the listener function to add\n * @param immediate whether to call the listener immediately with the current state (default is true)\n * @returns a function to remove the listener\n */\n listenUntilSettled(listener: AsyncResultListener<T, E>, immediate = true) {\n const unsub = this.listen((result) => {\n listener(result);\n if (result.state.status === 'success' || result.state.status === 'error') {\n unsub();\n }\n }, immediate);\n\n return unsub;\n }\n\n // === Mirroring ===\n\n /**\n * Mirrors the state of another AsyncResult into this one.\n * Whenever the other AsyncResult changes state, this AsyncResult is updated to match.\n * @param other the AsyncResult to mirror\n * @returns a function to stop mirroring\n */\n mirror(other: AsyncResult<T, E>) {\n return other.listen((newState) => {\n this.setState(newState.state);\n }, true);\n }\n\n /**\n * Mirrors the state of another AsyncResult into this one, until the other AsyncResult is settled (success or error).\n * Whenever the other AsyncResult changes state, this AsyncResult is updated to match, until the other AsyncResult is settled.\n * @param other the AsyncResult to mirror\n * @returns a function to stop mirroring\n */\n mirrorUntilSettled(other: AsyncResult<T, E>) {\n return other.listenUntilSettled((newState) => {\n this.setState(newState.state);\n }, true);\n }\n\n\n // === Actions ===\n\n /**\n * Creates a LazyAction that can be triggered to run the given Action.\n * @param action the Action to run when triggered\n * @returns an object containing the trigger function and the associated AsyncResult\n */\n static makeLazyAction<T, E extends ErrorBase = ErrorBase>(action: Action<T, E>): LazyAction<T, E> {\n const result = new AsyncResult<T, E>();\n const trigger = () => {\n result.updateFromResultPromise(action());\n };\n\n return { trigger, result };\n }\n\n // === Chaining ===\n\n /**\n * Chains the current AsyncResult with another operation that returns a Result or a Promise of a Result.\n * \n * If the current AsyncResult is loading, waits for it to settle first, then applies the provided function to its value.\n * If the current AsyncResult is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * \n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * \n * @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\n * @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\n */\n chain<O, E2 extends ErrorBase = ErrorBase>(fn: ChainStep<T, O, E | E2>): AsyncResult<O, E | E2> {\n const newResultBuilder = async (): Promise<Result<O, E | E2>> => {\n const settled = await this.waitForSettled();\n if (settled.state.status === 'loading' || settled.state.status === 'idle') {\n throw new Error('Unexpected state after waitForSettled'); // TODO handle this case properly\n }\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n\n return fn(settled.state.value);\n };\n\n return AsyncResult.fromResultPromise<O, E | E2>(newResultBuilder());\n }\n\n /**\n * Chains the current AsyncResult with another operation that returns an AsyncResult.\n * \n * If the current AsyncResult is loading, waits for it to settle first, then applies the provided function to its value.\n * If the current AsyncResult is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * \n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * \n * Like chain, but for functions returning AsyncResult instead of Result.\n * \n * @param fn a function taking as input the successful value of the result, and returning an AsyncResult describing the result of its own operation\n * @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\n */\n flatChain<O, E2 extends ErrorBase = ErrorBase>(fn: FlatChainStep<T, O, E | E2>): AsyncResult<O, E | E2> {\n const newResultBuilder = async (): Promise<Result<O, E | E2>> => {\n const settled = await this.toResultPromise();\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n\n const nextAsyncResult = fn(settled.state.value);\n const nextSettled = await nextAsyncResult.toResultPromise();\n return nextSettled;\n }\n\n return AsyncResult.fromResultPromise<O, E | E2>(newResultBuilder());\n }\n\n // pipeParallel PipeFunction[] -> AsyncResult<T, E>[]\n // pipeParallelAndCollapse PipeFunction[] -> AsyncResult<T[], E>\n\n /**\n * Ensures that all provided AsyncResults are successful.\n * If all are successful, returns an AsyncResult containing an array of their values.\n * If any AsyncResult is an error, returns an AsyncResult with the first encountered error.\n * @param results an array of AsyncResults to check\n * @returns an AsyncResult containing either an array of successful values or the first encountered error\n */\n static ensureAvailable<R extends readonly AsyncResult<any, any>[]>(results: R): AsyncResult<{ [K in keyof R]: R[K] extends AsyncResult<infer T, any> ? T : never }, R[number] extends AsyncResult<any, infer E> ? E : never> {\n if (results.length === 0) {\n // empty case — TS infers void tuple, so handle gracefully\n return AsyncResult.ok(undefined as never);\n }\n\n const promise = Promise.all(results.map((r) => r.waitForSettled())).then(\n (settledResults) => {\n for (const res of settledResults) {\n if (res.state.status === 'error') {\n return Result.err(res.state.error);\n }\n }\n\n const values = settledResults.map((r) => r.unwrapOrNull()!) as {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof R]: R[K] extends AsyncResult<infer T, any>\n ? T\n : never;\n };\n\n return Result.ok(values);\n }\n );\n\n return AsyncResult.fromResultPromise(promise);\n }\n\n // === Generator support ===\n\n /**\n * Yields the current AsyncResult, and if it is successful, returns its value.\n * This allows using AsyncResult instances in generator functions to simplify error handling and propagation.\n * @example\n * function* example(): Generator<AsyncResult<number>, number, any> {\n * const result1 = yield* AsyncResult.ok(5);\n * const result2 = yield* AsyncResult.ok(10);\n * return result1 + result2;\n * }\n */\n *[Symbol.iterator](): Generator<AsyncResult<T, E>, T, any> {\n yield this;\n\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return undefined as T;\n }\n\n private static _runGeneratorProcessor<T, E extends ErrorBase>(iterator: AsyncResultGenerator<T>): () => Promise<Result<T, E>> {\n return async (): Promise<Result<T, E>> => {\n let result = iterator.next();\n\n while (!result.done) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const yielded = result.value as AsyncResult<any, E>;\n const settled = await yielded.toResultPromise();\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n result = iterator.next(settled.state.value);\n }\n\n return Result.ok(result.value);\n }\n }\n\n /**\n * Runs a generator function that yields AsyncResult instances, propagating errors automatically.\n * If any yielded AsyncResult is an error, the execution stops and the error is returned.\n * If all yielded AsyncResults are successful, returns a successful AsyncResult with the final returned value.\n * \n * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.\n * Think of it as \"async/await\" but for AsyncResult handling in generator functions.\n * \n * @param generatorFunc a generator function that yields AsyncResult instances\n * @returns a AsyncResult containing either the final successful value or the first encountered error\n * \n * @example\n * const result = AsyncResult.run(function* () {\n * const value1 = yield* AsyncResult.ok(5);\n * const value2 = yield* AsyncResult.ok(10);\n * return value1 + value2;\n * }\n */\n static run<T, E extends ErrorBase = ErrorBase>(generatorFunc: () => AsyncResultGenerator<T>): AsyncResult<T, E> {\n const iterator = generatorFunc();\n return AsyncResult.fromResultPromise<T, E>(AsyncResult._runGeneratorProcessor<T, E>(iterator)());\n }\n\n\n /**\n * Runs a generator function that yields AsyncResult instances, propagating errors automatically, and updates this AsyncResult in place.\n * If any yielded AsyncResult is an error, the execution stops and this AsyncResult is updated to that error.\n * If all yielded AsyncResults are successful, this AsyncResult is updated to a successful state with the final returned value.\n * \n * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.\n * Think of it as \"async/await\" but for AsyncResult handling in generator functions.\n * \n * @param generatorFunc a generator function that yields AsyncResult instances\n */\n runInPlace(generatorFunc: () => AsyncResultGenerator<T>) {\n const iterator = generatorFunc();\n return this.updateFromResultPromise(AsyncResult._runGeneratorProcessor<T, E>(iterator)());\n }\n\n\n // === Debuging ===\n\n\n log(name?: string) {\n const time = (new Date()).toTimeString().slice(0, 8);\n console.log(`${name ?? \"<Anonymous AsyncResult>\"} ; State at ${time} :`, this.state);\n }\n\n debug(name?: string) {\n return this.listen((r) => r.log(name));\n }\n}\n","import type { AsyncResult } from \"./asyncResult\";\nimport type { ErrorBase } from \"./error\";\nimport type { Result } from \"./result\";\n\n/**\n * The possible states of an AsyncResultList.\n */\nexport type AsyncResultListState = \"any-loading\" | \"all-settled\";\n\n/**\n * A list that manages multiple AsyncResult instances, tracking their states and providing utilities to monitor them.\n */\nexport class AsyncResultList<T = any, E extends ErrorBase = ErrorBase> {\n private _list = new Map<string, AsyncResult<T, E>>();\n private _listeners: Set<(taskQueue: AsyncResultList<T, E>) => void> = new Set();\n private _state: AsyncResultListState = \"all-settled\";\n\n // === Getters ===\n\n /**\n * Gets the current tasks in the AsyncResultList.\n */\n get tasks() {\n return this._list;\n }\n\n /**\n * Gets the number of tasks in the list.\n */\n get length(): number {\n return this._list.size;\n }\n\n /**\n * Gets all tasks in the list as an array.\n */\n get items(): AsyncResult<T, E>[] {\n return Array.from(this._list.values());\n }\n\n /**\n * Gets the current state of the AsyncResultList.\n */\n get state() {\n return this._state;\n }\n\n private set state(s: AsyncResultListState) {\n this._state = s;\n this._listeners.forEach(f => f(this));\n }\n\n private _onTaskFinished() {\n this.state = this.anyLoading() ? \"any-loading\" : \"all-settled\";\n }\n\n // === Listeners ===\n\n /**\n * Adds a listener that gets called whenever the state of the AsyncResultList changes.\n * @param listener the function to call when the state changes\n * @returns a function to unsubscribe the listener\n */\n listen(listener: (taskQueue: AsyncResultList<T, E>) => void) {\n this._listeners.add(listener);\n return () => {\n this._listeners.delete(listener);\n };\n }\n\n // === Managing tasks ===\n\n /**\n * Adds an AsyncResult task to the list.\n * @param key the unique key for the task\n * @param task the AsyncResult task to add\n * @param removeOnSettle whether to remove the task from the list once it settles (defaults to true)\n * @returns the added AsyncResult task\n */\n add(key: string, task: AsyncResult<T, E>, removeOnSettle: boolean = true): AsyncResult<T, E> {\n this._list.set(key, task);\n this.state = \"any-loading\";\n\n if (removeOnSettle) {\n task.listenUntilSettled((r) => {\n if (r.isLoading() || r.isIdle()) return;\n this._onTaskFinished();\n this._list.delete(key);\n }, true);\n } else {\n task.listen((r) => {\n if (r.isLoading() || r.isIdle()) return;\n this._onTaskFinished();\n }, true);\n }\n\n return task;\n }\n\n // === Querying tasks ===\n\n /**\n * Checks if any task in the list is currently loading.\n * @returns true if any task is loading, false otherwise\n */\n anyLoading(): boolean {\n for (const task of this._list.values()) {\n if (task.isLoading()) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets all tasks that satisfy the given predicate.\n * @param predicate the function to test each task\n * @returns an array of tasks that satisfy the predicate\n */\n getAllFiltered(predicate: (task: AsyncResult<T, E>) => boolean): AsyncResult<T, E>[] {\n const filtered: AsyncResult<T, E>[] = [];\n for (const task of this._list.values()) {\n if (predicate(task)) {\n filtered.push(task);\n }\n }\n return filtered;\n }\n\n /**\n * Gets all tasks that satisfy the given predicate and maps them using the provided function.\n * @param filterPredicate the function to test each task\n * @param mapFunc the function to map each task\n * @returns an array of mapped values\n */\n getAllFilteredAndMap<U>(filterPredicate: (task: AsyncResult<T, E>) => boolean, mapFunc: (task: AsyncResult<T, E>) => U): U[] {\n const results: U[] = [];\n for (const task of this._list.values()) {\n if (filterPredicate(task)) {\n results.push(mapFunc(task));\n }\n }\n return results;\n }\n\n /**\n * Gets all tasks that have succeeded.\n * @returns an array of successful AsyncResult tasks\n */\n getAllSuccess(): AsyncResult<T, E>[] {\n return this.getAllFiltered((task) => task.isSuccess());\n }\n\n /**\n * Gets the success values of all tasks that have succeeded.\n * @returns an array of successful values\n */\n getAllSuccessValues(): T[] {\n return this.getAllFilteredAndMap((task) => task.isSuccess(), (task) => task.unwrapOrThrow());\n }\n\n /**\n * Gets all tasks that have errored.\n * @returns an array of error AsyncResult tasks\n */\n getAllErrors(): AsyncResult<T, E>[] {\n return this.getAllFiltered((task) => task.isError());\n }\n\n /**\n * Gets the error values of all tasks that have errored.\n * @returns an array of error values\n */\n getAllErrorValues(): E[] {\n return this.getAllFilteredAndMap((task) => task.isError(), (task) => task.unwrapErrorOrNull()!);\n }\n\n /**\n * Gets all tasks that are currently loading.\n * @returns an array of loading AsyncResult tasks\n */\n getAllLoading(): AsyncResult<T, E>[] {\n return this.getAllFiltered((task) => task.isLoading());\n }\n\n /**\n * Gets the promises of all tasks that are currently loading.\n * @returns an array of promises for loading tasks\n */\n getAllLoadingPromises(): Promise<Result<T, E>>[] {\n return this.getAllFilteredAndMap((task) => task.isLoading(), (task) => task.toResultPromise());\n }\n\n // === Debugging utilities ===\n\n /**\n * Logs the current state and tasks of the AsyncResultList to the console.\n * @param name an optional name to identify the log\n */\n log(name?: string) {\n const time = (new Date()).toTimeString().slice(0, 8);\n console.log(`${name ?? '<Anonymous TaskQueue>'} ; State at ${time} :`, this.state, this._list);\n }\n\n /**\n * Sets up a listener to log the state and tasks of the AsyncResultList whenever it changes.\n * @param name an optional name to identify the log\n * @returns a function to unsubscribe the debug listener\n */\n debug(name?: string) {\n return this.listen(() => {\n this.log(name);\n });\n }\n}","import { AsyncResult, type AsyncResultState, type ChainStep } from \"./asyncResult\";\nimport type { ErrorBase } from \"./error\";\n\ntype KeyedAsyncCacheRefetchOptions = {\n policy: 'refetch' | 'if-error' | 'no-refetch';\n};\n\ntype CacheItem<P, V, E extends ErrorBase = ErrorBase> = {\n result: AsyncResult<V, E>;\n fetcherParams: P;\n valid: boolean;\n lastFetched?: number;\n ttl?: number;\n};\n\nconst _defaultRefetchOptions: KeyedAsyncCacheRefetchOptions = { policy: 'no-refetch' };\n\nfunction defaultParamsToKey<P>(params: P): string {\n if (typeof params === 'object') {\n return JSON.stringify(params);\n }\n return String(params);\n}\n\n/**\n * A cache for asynchronous operations that maps parameter sets to their corresponding AsyncResult.\n * Supports automatic refetching based on specified policies.\n * \n * @template P - The type of the parameters used to fetch values.\n * @template V - The type of the values being fetched.\n * @template E - The type of the error, extending ErrorBase (default is ErrorBase).\n */\nexport class KeyedAsyncCache<P, V, E extends ErrorBase = ErrorBase> {\n private _cache: Map<string, CacheItem<P, V, E>> = new Map();\n private _fetcher: ChainStep<P, V, E>;\n private _paramsToKey: (params: P) => string;\n private _cacheTTL?: number;\n\n /**\n * Creates a new KeyedAsyncCache instance.\n * @param fetcher the function used to fetch values based on parameters\n * @param paramsToKey a function that converts parameters to a unique string key (default uses JSON.stringify for objects)\n * @param cacheTTL optional time-to-live for cache entries in milliseconds\n */\n constructor(fetcher: ChainStep<P, V, E>, paramsToKey: (params: P) => string = defaultParamsToKey, cacheTTL: number = Infinity) {\n this._fetcher = fetcher;\n this._paramsToKey = paramsToKey;\n this._cacheTTL = cacheTTL;\n }\n\n private makeCacheItem(result: AsyncResult<V, E>, fetcherParams: P, ttl?: number | undefined): CacheItem<P, V, E> {\n return {\n result,\n fetcherParams,\n ttl: ttl ?? this._cacheTTL,\n valid: true,\n };\n }\n\n private shouldRefetch(existingResult: CacheItem<P, V, E>, refetch: KeyedAsyncCacheRefetchOptions): boolean {\n if (!existingResult.valid) {\n return true;\n }\n if (refetch.policy === 'refetch') {\n return true;\n }\n if (refetch.policy === 'if-error') {\n return existingResult.result.state.status === 'error';\n }\n if (existingResult.ttl !== undefined && existingResult.lastFetched !== undefined) {\n const now = Date.now();\n if (now - existingResult.lastFetched > existingResult.ttl) {\n return true;\n }\n }\n return false;\n }\n\n private updateOrCreateCacheItemFromParams(params: P, cacheItem?: CacheItem<P, V, E>) {\n const promise = Promise.resolve(this._fetcher(params));\n let result = cacheItem?.result.updateFromResultPromise(promise) ?? AsyncResult.fromResultPromise(promise);\n cacheItem = cacheItem ?? this.makeCacheItem(result, params);\n \n promise.then(() => {\n cacheItem.lastFetched = Date.now();\n });\n\n return cacheItem;\n }\n\n /**\n * Gets the AsyncResult for the given parameters, fetching it if not cached or if refetching is required.\n * @param params the parameters to fetch the value\n * @param refetch options determining whether to refetch the value\n * @returns the AsyncResult corresponding to the given parameters\n */\n get(params: P, refetch: KeyedAsyncCacheRefetchOptions = _defaultRefetchOptions): AsyncResult<V, E> {\n const key = this._paramsToKey(params);\n if (this._cache.has(key)) {\n const cacheItem = this._cache.get(key)!;\n if (!this.shouldRefetch(cacheItem, refetch)) {\n return cacheItem.result;\n } else {\n this.updateOrCreateCacheItemFromParams(params, cacheItem);\n return cacheItem.result;\n }\n }\n \n const cacheItem = this.updateOrCreateCacheItemFromParams(params);\n this._cache.set(key, cacheItem);\n return cacheItem.result;\n }\n\n /**\n * Gets the settled state of the AsyncResult for the given parameters, fetching it if not cached or if refetching is required.\n * Waits for the AsyncResult to settle before returning its state.\n * @param params the parameters to fetch the value\n * @param refetch options determining whether to refetch the value\n * @returns a promise resolving to the settled state of the AsyncResult\n */\n async getSettledState(params: P, refetch: KeyedAsyncCacheRefetchOptions = _defaultRefetchOptions): Promise<AsyncResultState<V, E>> {\n const asyncResult = this.get(params, refetch);\n await asyncResult.waitForSettled();\n return asyncResult.state;\n }\n\n /**\n * Checks if any cached AsyncResult is currently loading.\n * @returns whether any cached AsyncResult is loading\n */\n anyLoading(): boolean {\n for (const cacheItem of this._cache.values()) {\n if (cacheItem.result.isLoading()) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Clears the entire cache.\n */\n clear() {\n this._cache.clear();\n }\n\n /**\n * Invalidates the cache entry for the given key.\n * @param key the key of the cache entry to invalidate\n */\n invalidateKey(key: string) {\n if (this._cache.has(key)) {\n const cacheItem = this._cache.get(key)!;\n cacheItem.valid = false;\n }\n }\n\n /**\n * Invalidates the cache entry for the given parameters.\n * @param params the parameters of the cache entry to invalidate\n */\n invalidateParams(params: P) {\n const key = this._paramsToKey(params);\n this.invalidateKey(key);\n }\n\n /**\n * Invalidates all cache entries.\n */\n invalidateAll() {\n for (const cacheItem of this._cache.values()) {\n cacheItem.valid = false;\n }\n }\n}\n","import { AsyncResult } from \"./asyncResult\";\n\nexport function delay(ms: number): AsyncResult<true> {\n return AsyncResult.fromValuePromise(new Promise(resolve => {\n setTimeout(() => resolve(true), ms);\n }));\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,YAAN,MAAgB;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,MAAc,SAAkB,aAAuB,MAAe,MAAM;AACpF,SAAK,OAAO;AACZ,SAAK,UAAU;AACf,SAAK,cAAc;AAEnB,QAAI,KAAK;AACL,WAAK,SAAS;AAAA,IAClB;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAmB;AACf,WAAO,SAAS,KAAK,IAAI,KAAK,KAAK,WAAW,EAAE;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAiB;AACb,QAAI,KAAK,aAAa;AAClB,cAAQ,MAAM,KAAK,SAAS,GAAG,KAAK,WAAW;AAAA,IACnD,OAAO;AACH,cAAQ,MAAM,KAAK,SAAS,CAAC;AAAA,IACjC;AAAA,EACJ;AACJ;;;AC7BO,IAAM,SAAN,MAAM,QAA2C;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA;AAAA,EAMR,YAAY,OAA0B;AAClC,SAAK,SAAS;AAAA,EAClB;AAAA;AAAA,EAGA,IAAI,QAAQ;AACR,WAAO,KAAK;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAqB;AACjB,WAAO,KAAK,OAAO,WAAW;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,UAAmB;AACf,WAAO,KAAK,OAAO,WAAW;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,GAAuC,OAAwB;AAClE,WAAO,IAAI,QAAO,EAAE,QAAQ,WAAW,MAAM,CAAC;AAAA,EAClD;AAAA;AAAA;AAAA;AAAA;AAAA;AA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YAAY,eAAe;AACjC,WAAO,YAAY;AAAA,EACvB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAsB;AAClB,eAAW,aAAa,KAAK,OAAO,OAAO,GAAG;AAC1C,UAAI,UAAU,OAAO,UAAU,GAAG;AAC9B,eAAO;AAAA,MACX;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA,EAKA,QAAQ;AACJ,SAAK,OAAO,MAAM;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,cAAc,KAAa;AACvB,QAAI,KAAK,OAAO,IAAI,GAAG,GAAG;AACtB,YAAM,YAAY,KAAK,OAAO,IAAI,GAAG;AACrC,gBAAU,QAAQ;AAAA,IACtB;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAiB,QAAW;AACxB,UAAM,MAAM,KAAK,aAAa,MAAM;AACpC,SAAK,cAAc,GAAG;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAgB;AACZ,eAAW,aAAa,KAAK,OAAO,OAAO,GAAG;AAC1C,gBAAU,QAAQ;AAAA,IACtB;AAAA,EACJ;AACJ;;;AC5KO,SAAS,MAAM,IAA+B;AACjD,SAAO,YAAY,iBAAiB,IAAI,QAAQ,aAAW;AACvD,eAAW,MAAM,QAAQ,IAAI,GAAG,EAAE;AAAA,EACtC,CAAC,CAAC;AACN;","names":["cacheItem"]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/index.ts","../../src/core/error.ts","../../src/core/result.ts","../../src/core/asyncResult.ts","../../src/core/asyncResultList.ts","../../src/core/cache.ts","../../src/core/utils.ts"],"sourcesContent":["export * from \"./error\";\nexport * from \"./result\";\nexport * from \"./asyncResult\";\nexport * from \"./asyncResultList\";\nexport * from \"./cache\";\nexport * from \"./utils\";","/**\n * Base class for error handling, providing structured error information and logging.\n * @class ErrorBase\n * @property {string} code - The error code.\n * @property {string | undefined} message - The error message (optional).\n * @property {unknown} thrownError - The original error object, if any (optional).\n * \n * @constructor\n * @param {string} code - The error code.\n * @param {string} [message] - The error message.\n * @param {unknown} [thrownError] - The original error object, if any.\n * @param {boolean} [log=true] - Whether to log the error upon creation.\n */\nexport class ErrorBase {\n code: string;\n message?: string | undefined;\n thrownError?: unknown;\n\n constructor(code: string, message?: string, thrownError?: unknown, log: boolean = true) {\n this.code = code;\n this.message = message;\n this.thrownError = thrownError;\n\n if (log) {\n this.logError();\n }\n }\n\n /**\n * Converts the error to a string representation, on the format \"Error {code}: {message}\".\n * @returns a string representation of the error\n */\n toString(): string {\n return `Error ${this.code}: ${this.message ?? ''}`;\n }\n\n /**\n * Logs the error to the console, uses console.error and ErrorBase.toString() internally.\n * Logs thrownError if it was provided on creation.\n */\n logError(): void {\n if (this.thrownError) {\n console.error(this.toString(), this.thrownError);\n } else {\n console.error(this.toString());\n }\n }\n}\n","import { ErrorBase } from \"./error\";\n\n/**\n * Type representing the state of a Result, either success with a value of type T,\n * or error with an error of type E (defaulting to ErrorBase).\n */\nexport type ResultState<T, E extends ErrorBase = ErrorBase> =\n | { status: 'success'; value: T }\n | { status: 'error'; error: E };\n\n/**\n * Class representing the result of an operation that can either succeed with a value of type T,\n * or fail with an error of type E (defaulting to ErrorBase).\n * Provides methods for unwrapping the result, chaining operations, and handling errors.\n * @class Result\n * @template T - The type of the successful result value.\n * @template E - The type of the error, extending ErrorBase (default is ErrorBase).\n */\nexport class Result<T, E extends ErrorBase = ErrorBase> {\n private _state: ResultState<T, E>;\n\n /**\n * Creates a new Result instance with the given state.\n * @param state the state of the created Result\n */\n constructor(state: ResultState<T, E>) {\n this._state = state;\n }\n\n /** Returns the internal state of the Result. */\n get state() {\n return this._state;\n }\n\n /**\n * Checks if the Result is successful.\n * @returns whether or not the result is successful\n */\n isSuccess(): boolean {\n return this._state.status === 'success';\n }\n\n /**\n * Checks if the Result is an error.\n * @returns whether or not the result is an error\n */\n isError(): boolean {\n return this._state.status === 'error';\n }\n\n /**\n * Creates a successful Result with the given value.\n * @param value the result of the successful operation\n * @returns a successful Result\n */\n static ok<T, E extends ErrorBase = ErrorBase>(value: T): Result<T, E> {\n return new Result({ status: 'success', value });\n }\n\n /**\n * Creates an error Result with the given error.\n * @param error the error of the failed operation\n * @returns an error Result\n */\n static err<E extends ErrorBase = ErrorBase>(error: E): Result<never, E> {\n return new Result({ status: 'error', error });\n }\n\n /**\n * Creates an error Result (containing an ErrorBase) with the given error code and optional message.\n * @param code the error code\n * @param message an optional error message\n * @returns an error Result\n */\n static errTag(code: string, message?: string, thrownError?: unknown): Result<never, ErrorBase> {\n return Result.err(new ErrorBase(code, message, thrownError));\n }\n\n /**\n * Returns the successful value (if the Result is successful) or null (if it is an error).\n * @returns either the successful value or null\n */\n unwrapOrNull(): T | null {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return null;\n }\n\n /**\n * Returns the successful value (if the Result is successful) or throws an error (if it is an error).\n * @returns the successful value\n * @throws an normal JS Error if the result is not successful\n */\n unwrapOrThrow(): T {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n throw new Error('Tried to unwrap a Result that is not successful');\n }\n\n /**\n * Returns the successful value (if the Result is successful) or a default value (if it is an error).\n * @param defaultValue the default value to return if the Result is an error\n * @returns either the successful value or the default value\n */\n unwrapOr<O>(defaultValue: O): T | O {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return defaultValue;\n }\n\n /**\n * Transforms a Promise of a successful value into a Promise of a Result,\n * catching any thrown errors and mapping them using the provided errorMapper function.\n * @param promise the promise to execute\n * @param errorMapper a function that maps a thrown error to a Result error\n * @returns a Promise resolving to a Result containing either the successful value or the mapped error\n */\n static tryPromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>> {\n return promise\n .then((value) => Result.ok<T, E>(value))\n .catch((error) => Result.err(errorMapper(error)));\n }\n\n /**\n * Executes an asynchronous function and transforms its result into a Result,\n * catching any thrown errors and mapping them using the provided errorMapper function.\n * Same as Result.tryPromise(fn(), errorMapper).\n * @param fn the asynchronous function to execute\n * @param errorMapper a function that maps a thrown error to a Result error\n * @returns a Promise resolving to a Result containing either the successful value or the mapped error\n */\n static tryFunction<T, E extends ErrorBase = ErrorBase>(fn: () => Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>> {\n return Result.tryPromise(fn(), errorMapper);\n }\n\n /**\n * Chains the current Result with another operation that returns a ResultState.\n * If the current Result is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * @param fn a function taking as input the successful value of the result, and returning a ResultState describing the result of its own operation\n * @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\n */\n chain<O, E2 extends ErrorBase = ErrorBase>(fn: (input: T) => ResultState<O, E | E2>): Result<O, E | E2> {\n if (this._state.status === 'success') {\n return new Result<O, E | E2>(fn(this._state.value));\n }\n return Result.err<E>(this._state.error);\n }\n\n /**\n * Chains the current Result with another operation that returns a Result.\n * If the current Result is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * Same as chain, but the function returns a Result directly instead of a ResultState.\n * @param fn a function taking as input the successful value of the result, and returning a Result describing the result of its own operation\n * @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\n */\n flatChain<O, E2 extends ErrorBase = ErrorBase>(fn: (input: T) => Result<O, E | E2>): Result<O, E | E2> {\n if (this._state.status === 'success') {\n return fn(this._state.value);\n }\n return Result.err<E>(this._state.error);\n }\n\n /**\n * @yields the current Result, and if it is successful, returns its value.\n * This allows using Result instances in generator functions to simplify error handling and propagation.\n * @example\n * function* example(): Generator<Result<number>, number, any> {\n * const result1 = yield* Result.ok(5);\n * const result2 = yield* Result.ok(10);\n * return result1 + result2;\n * }\n */\n *[Symbol.iterator](): Generator<Result<T, E>, T, any> {\n yield this;\n\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return undefined as T;\n }\n\n /**\n * Runs a generator function that yields Result instances, propagating errors automatically.\n * If any yielded Result is an error, the execution stops and the error is returned.\n * If all yielded Results are successful, returns a successful Result with the final returned value.\n * \n * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.\n * Think of it as \"async/await\" but for Result handling in generator functions.\n * \n * @param generator a generator function that yields Result instances\n * @returns a Result containing either the final successful value or the first encountered error\n * \n * @example\n * const result = Result.run(function* () {\n * const value1 = yield* Result.ok(5);\n * const value2 = yield* Result.ok(10);\n * return value1 + value2;\n * });\n */\n static run<T, E extends ErrorBase = ErrorBase>(generator: () => Generator<Result<any, E>, T, any>): Result<T, E> {\n const iterator = generator();\n let result = iterator.next();\n\n while (!result.done) {\n const yielded = result.value;\n if (yielded._state.status === 'error') {\n return Result.err(yielded._state.error);\n }\n result = iterator.next(yielded._state.value);\n }\n\n return Result.ok(result.value);\n }\n}\n","import { ErrorBase } from \"./error\";\nimport { Result, type ResultState } from \"./result\";\n\n/**\n * Type representing the state of an AsyncResult.\n * It can be 'idle', 'loading' with a promise, or a settled ResultState (success or error).\n */\nexport type AsyncResultState<T, E extends ErrorBase = ErrorBase> =\n | { status: 'idle' }\n | { status: 'loading'; promise: Promise<Result<T, E>> }\n | ResultState<T, E>;\n\n\n/**\n * An Action is a function returning a Promise of a Result.\n */\nexport type Action<T,E extends ErrorBase = ErrorBase> = () => Promise<Result<T, E>>;\n\n/**\n * A LazyAction is an object containing a trigger function to start the action, and the AsyncResult representing the action's state.\n */\nexport type LazyAction<T, E extends ErrorBase = ErrorBase> = {\n trigger: () => void;\n result: AsyncResult<T, E>;\n};\n\n/**\n * A ChainStep is a function that takes an arbitrary input and returns a Result or a Promise of a Result.\n * It takes an input of type I and returns either a Result<O, E> or a Promise<Result<O, E>>.\n * \n * Used for chaining operations on AsyncResult.\n */\nexport type ChainStep<I, O, E extends ErrorBase = ErrorBase> = (input: I) => Result<O, E> | Promise<Result<O, E>>;\n\n/**\n * A FlatChainStep is a function that takes an arbitrary input and returns an AsyncResult.\n * It takes an input of type I and returns an AsyncResult<O, E>.\n * \n * Used for flat-chaining operations on AsyncResult.\n */\nexport type FlatChainStep<I, O, E extends ErrorBase = ErrorBase> = (input: I) => AsyncResult<O, E>;\n\n/**\n * Type representing a generator function that yields AsyncResult instances and returns a final value of type T.\n * \n * Used for running generators with AsyncResult.run().\n */\nexport type AsyncResultGenerator<T> = Generator<AsyncResult<any, any>, T, any>;\n\n/**\n * Type representing a listener function for AsyncResult state changes.\n */\nexport type AsyncResultListener<T, E extends ErrorBase = ErrorBase> = (result: AsyncResult<T, E>) => any;\n\n/**\n * Class representing the asynchronous result of an operation that can be idle, loading, successful, or failed.\n * Provides methods for listening to state changes, updating state, chaining operations, and converting to and from promises.\n * @class AsyncResult\n * @template T - The type of the successful result value.\n * @template E - The type of the error, extending ErrorBase (default is ErrorBase).\n */\nexport class AsyncResult<T, E extends ErrorBase = ErrorBase> {\n private _state: AsyncResultState<T, E>;\n private _listeners: Set<AsyncResultListener<T, E>> = new Set();\n\n constructor(state?: AsyncResultState<T, E>) {\n this._state = state || { status: 'idle' };\n }\n\n\n\n // === Getting current state ===\n\n /**\n * Returns the internal state of the AsyncResult.\n */\n get state() {\n return this._state;\n }\n\n /**\n * Checks if the AsyncResult is successful.\n * @returns whether or not the result is successful\n */\n isSuccess() {\n return this._state.status === 'success';\n }\n\n /**\n * Checks if the AsyncResult is an error.\n * @returns whether or not the result is an error\n */\n isError() {\n return this._state.status === 'error';\n }\n\n /**\n * Checks if the AsyncResult is idle.\n * @returns whether or not the result is idle\n */\n isIdle() {\n return this._state.status === 'idle';\n }\n\n /**\n * Checks if the AsyncResult is loading.\n * @returns whether or not the result is loading\n */\n isLoading() {\n return this._state.status === 'loading';\n }\n\n\n\n // === Unwrapping values ===\n\n /**\n * Returns the successful value if the AsyncResult is in a success state, otherwise returns null.\n * @returns the successful value or null\n */\n unwrapOrNull(): T | null {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return null;\n }\n\n /**\n * Returns the successful value if the AsyncResult is in a success state, otherwise throws an error.\n * @returns the successful value\n * @throws an normal JS Error if the result is not successful\n */\n unwrapOrThrow(): T {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n throw new Error('Tried to unwrap an AsyncResult that is not successful');\n }\n\n /**\n * Returns the error value if the AsyncResult is in an error state, otherwise returns null.\n * @returns the error value or null\n */\n unwrapErrorOrNull(): E | null {\n if (this._state.status === 'error') {\n return this._state.error;\n }\n return null;\n }\n\n // === Creating/updating from settled values ===\n\n private set state(newState: AsyncResultState<T, E>) {\n this._state = newState;\n this._listeners.forEach((listener) => listener(this));\n }\n\n private setState(newState: AsyncResultState<T, E>) {\n this.state = newState;\n }\n\n /**\n * Creates a successful AsyncResult with the given value.\n * @param value the result of the successful operation\n * @returns a successful AsyncResult\n */\n static ok<T>(value: T): AsyncResult<T, never> {\n return new AsyncResult<T, never>({ status: 'success', value });\n }\n\n /**\n * Creates an error AsyncResult with the given error.\n * @param error the error of the failed operation\n * @returns an error AsyncResult\n */\n static err<E extends ErrorBase = ErrorBase>(error: E): AsyncResult<never, E> {\n return new AsyncResult<never, E>({ status: 'error', error });\n }\n\n /**\n * Creates an error AsyncResult with a new ErrorBase constructed from the given parameters.\n * @param code the error code\n * @param message the error message (optional)\n * @param thrownError the original error object, if any (optional)\n * @param log whether to log the error upon creation (default is true)\n * @returns an error AsyncResult\n */\n static errTag(code: string, message?: string, thrownError?: unknown, log: boolean = true): AsyncResult<never, ErrorBase> {\n const error = new ErrorBase(code, message, thrownError, log);\n return AsyncResult.err(error);\n }\n\n /**\n * Updates the AsyncResult to a successful state with the given value.\n * Like AsyncResult.ok, but in place.\n * @param value the successful value\n */\n updateFromValue(value: T) {\n this.state = { status: 'success', value };\n return this;\n }\n\n /**\n * Updates the AsyncResult to an error state with the given error.\n * Like AsyncResult.err, but in place.\n * @param error the error\n */\n updateFromError(error: E) {\n this.state = { status: 'error', error };\n return this;\n }\n\n\n\n // === Creating/updating from promises ===\n\n /**\n * Creates an AsyncResult from a promise that resolves to a value.\n * The AsyncResult is initially in a loading state, and updates to a successful state once the promise resolves.\n * If the promise rejects, the AsyncResult is updated to an error state with the caught error.\n * \n * Like AsyncResult.fromResultPromise, but for promise that only resolves to a successful value and not a Result.\n * \n * @param promise the promise that resolves to a value\n * @returns an AsyncResult representing the state of the promise\n */\n static fromValuePromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<T>): AsyncResult<T, E> {\n const result = new AsyncResult<T, E>();\n result.updateFromValuePromise(promise);\n return result;\n }\n\n /**\n * Updates the AsyncResult to a loading state with the given promise.\n * The AsyncResult is initially in a loading state, and updates to a successful state once the promise resolves.\n * If the promise rejects, the AsyncResult is updated to an error state with the caught error.\n * \n * Like AsyncResult.fromValuePromise, but in place.\n * \n * @param promise the promise that resolves to a value\n */\n updateFromValuePromise(promise: Promise<T>) {\n const resultStatePromise = async (): Promise<Result<T, E>> => {\n try {\n const value = await promise;\n return Result.ok(value);\n } catch (error) {\n return Result.err(error as E);\n }\n };\n return this.updateFromResultPromise(resultStatePromise());\n }\n\n\n // === Waiting for settled state and get result ===\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading.\n * @returns itself once settled\n */\n async waitForSettled(): Promise<AsyncResult<T, E>> {\n if (this._state.status === 'loading') {\n try {\n const value = await this._state.promise;\n this._state = value.state;\n } catch (error) {\n this._state = { status: 'error', error: error as E };\n }\n }\n return this;\n }\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns a Result representing the settled state.\n * @returns a Result representing the settled state\n */\n async toResultPromise(): Promise<Result<T, E>> {\n const settled = await this.waitForSettled();\n if (settled.state.status === 'idle' || settled.state.status === 'loading') {\n throw new Error('Cannot convert idle or loading AsyncResult to ResultState');\n }\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n return Result.ok(settled.state.value);\n }\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns the successful value or throws an error.\n * @returns the successful value\n * @throws an normal JS Error if the result is not successful\n */\n async toValueOrThrowPromise(): Promise<T> {\n const settled = await this.waitForSettled();\n return settled.unwrapOrThrow();\n }\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns the successful value or null.\n * @returns either the successful value or null\n */\n async toValueOrNullPromise(): Promise<T | null> {\n const settled = await this.waitForSettled();\n return settled.unwrapOrNull();\n }\n\n /**\n * Creates an AsyncResult from a promise that resolves to a Result.\n * The AsyncResult is initially in a loading state, and updates to the settled state once the promise resolves.\n * If the promise rejects, the AsyncResult is updated to an error state with a default ErrorBase.\n * \n * @param promise the promise that resolves to a Result\n * @returns an AsyncResult representing the state of the promise\n */\n static fromResultPromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<Result<T, E>>): AsyncResult<T, E> {\n const result = new AsyncResult<T, E>();\n result.updateFromResultPromise(promise);\n return result;\n }\n\n /**\n * Updates the AsyncResult to a loading state with the given promise.\n * The promise must produce a Result once settled (meaning it should return the error in the result when possible).\n * If the promise rejects, the AsyncResult is updated to an error state with a default ErrorBase.\n * \n * Like AsyncResult.fromResultPromise, but in place.\n * \n * @param promise the promise that resolves to a Result\n */\n updateFromResultPromise(promise: Promise<Result<T, E>>) {\n this.state = { status: 'loading', promise };\n promise\n .then((res) => {\n this.state = res.state;\n })\n .catch((error) => {\n this.updateFromError(new ErrorBase('defect_on_updateFromResultPromise', 'The promise provided to AsyncResult rejected', error) as E);\n });\n return this;\n }\n\n\n // === Listeners ===\n\n /**\n * Adds a listener that is called whenever the AsyncResult state changes.\n * @param listener the listener function to add\n * @param immediate whether to call the listener immediately with the current state (default is true)\n * @returns a function to remove the listener\n */\n listen(listener: AsyncResultListener<T, E>, immediate = true) {\n this._listeners.add(listener);\n if (immediate) {\n listener(this);\n }\n\n return () => {\n this._listeners.delete(listener);\n };\n }\n\n /**\n * Adds a listener that is called whenever the AsyncResult state changes, and automatically unsubscribes once it is settled (success or error).\n * @param listener the listener function to add\n * @param immediate whether to call the listener immediately with the current state (default is true)\n * @returns a function to remove the listener\n */\n listenUntilSettled(listener: AsyncResultListener<T, E>, immediate = true) {\n const unsub = this.listen((result) => {\n listener(result);\n if (result.state.status === 'success' || result.state.status === 'error') {\n unsub();\n }\n }, immediate);\n\n return unsub;\n }\n\n // === Mirroring ===\n\n /**\n * Mirrors the state of another AsyncResult into this one.\n * Whenever the other AsyncResult changes state, this AsyncResult is updated to match.\n * @param other the AsyncResult to mirror\n * @returns a function to stop mirroring\n */\n mirror(other: AsyncResult<T, E>) {\n return other.listen((newState) => {\n this.setState(newState.state);\n }, true);\n }\n\n /**\n * Mirrors the state of another AsyncResult into this one, until the other AsyncResult is settled (success or error).\n * Whenever the other AsyncResult changes state, this AsyncResult is updated to match, until the other AsyncResult is settled.\n * @param other the AsyncResult to mirror\n * @returns a function to stop mirroring\n */\n mirrorUntilSettled(other: AsyncResult<T, E>) {\n return other.listenUntilSettled((newState) => {\n this.setState(newState.state);\n }, true);\n }\n\n\n // === Actions ===\n\n /**\n * Creates a LazyAction that can be triggered to run the given Action.\n * @param action the Action to run when triggered\n * @returns an object containing the trigger function and the associated AsyncResult\n */\n static makeLazyAction<T, E extends ErrorBase = ErrorBase>(action: Action<T, E>): LazyAction<T, E> {\n const result = new AsyncResult<T, E>();\n const trigger = () => {\n result.updateFromResultPromise(action());\n };\n\n return { trigger, result };\n }\n\n // === Chaining ===\n\n /**\n * Chains the current AsyncResult with another operation that returns a Result or a Promise of a Result.\n * \n * If the current AsyncResult is loading, waits for it to settle first, then applies the provided function to its value.\n * If the current AsyncResult is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * \n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * \n * @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\n * @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\n */\n chain<O, E2 extends ErrorBase = ErrorBase>(fn: ChainStep<T, O, E | E2>): AsyncResult<O, E | E2> {\n const newResultBuilder = async (): Promise<Result<O, E | E2>> => {\n const settled = await this.waitForSettled();\n if (settled.state.status === 'loading' || settled.state.status === 'idle') {\n throw new Error('Unexpected state after waitForSettled'); // TODO handle this case properly\n }\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n\n return fn(settled.state.value);\n };\n\n return AsyncResult.fromResultPromise<O, E | E2>(newResultBuilder());\n }\n\n /**\n * Chains the current AsyncResult with another operation that returns an AsyncResult.\n * \n * If the current AsyncResult is loading, waits for it to settle first, then applies the provided function to its value.\n * If the current AsyncResult is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * \n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * \n * Like chain, but for functions returning AsyncResult instead of Result.\n * \n * @param fn a function taking as input the successful value of the result, and returning an AsyncResult describing the result of its own operation\n * @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\n */\n flatChain<O, E2 extends ErrorBase = ErrorBase>(fn: FlatChainStep<T, O, E | E2>): AsyncResult<O, E | E2> {\n const newResultBuilder = async (): Promise<Result<O, E | E2>> => {\n const settled = await this.toResultPromise();\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n\n const nextAsyncResult = fn(settled.state.value);\n const nextSettled = await nextAsyncResult.toResultPromise();\n return nextSettled;\n }\n\n return AsyncResult.fromResultPromise<O, E | E2>(newResultBuilder());\n }\n\n // pipeParallel PipeFunction[] -> AsyncResult<T, E>[]\n // pipeParallelAndCollapse PipeFunction[] -> AsyncResult<T[], E>\n\n /**\n * Ensures that all provided AsyncResults are successful.\n * If all are successful, returns an AsyncResult containing an array of their values.\n * If any AsyncResult is an error, returns an AsyncResult with the first encountered error.\n * @param results an array of AsyncResults to check\n * @returns an AsyncResult containing either an array of successful values or the first encountered error\n */\n static ensureAvailable<R extends readonly AsyncResult<any, any>[]>(results: R): AsyncResult<{ [K in keyof R]: R[K] extends AsyncResult<infer T, any> ? T : never }, R[number] extends AsyncResult<any, infer E> ? E : never> {\n if (results.length === 0) {\n // empty case — TS infers void tuple, so handle gracefully\n return AsyncResult.ok(undefined as never);\n }\n\n const promise = Promise.all(results.map((r) => r.waitForSettled())).then(\n (settledResults) => {\n for (const res of settledResults) {\n if (res.state.status === 'error') {\n return Result.err(res.state.error);\n }\n }\n\n const values = settledResults.map((r) => r.unwrapOrNull()!) as {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof R]: R[K] extends AsyncResult<infer T, any>\n ? T\n : never;\n };\n\n return Result.ok(values);\n }\n );\n\n return AsyncResult.fromResultPromise(promise);\n }\n\n // === Generator support ===\n\n /**\n * Yields the current AsyncResult, and if it is successful, returns its value.\n * This allows using AsyncResult instances in generator functions to simplify error handling and propagation.\n * @example\n * function* example(): Generator<AsyncResult<number>, number, any> {\n * const result1 = yield* AsyncResult.ok(5);\n * const result2 = yield* AsyncResult.ok(10);\n * return result1 + result2;\n * }\n */\n *[Symbol.iterator](): Generator<AsyncResult<T, E>, T, any> {\n yield this;\n\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return undefined as T;\n }\n\n private static _runGeneratorProcessor<T, E extends ErrorBase>(iterator: AsyncResultGenerator<T>): () => Promise<Result<T, E>> {\n return async (): Promise<Result<T, E>> => {\n let result = iterator.next();\n\n while (!result.done) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const yielded = result.value as AsyncResult<any, E>;\n const settled = await yielded.toResultPromise();\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n result = iterator.next(settled.state.value);\n }\n\n return Result.ok(result.value);\n }\n }\n\n /**\n * Runs a generator function that yields AsyncResult instances, propagating errors automatically.\n * If any yielded AsyncResult is an error, the execution stops and the error is returned.\n * If all yielded AsyncResults are successful, returns a successful AsyncResult with the final returned value.\n * \n * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.\n * Think of it as \"async/await\" but for AsyncResult handling in generator functions.\n * \n * @param generatorFunc a generator function that yields AsyncResult instances\n * @returns a AsyncResult containing either the final successful value or the first encountered error\n * \n * @example\n * const result = AsyncResult.run(function* () {\n * const value1 = yield* AsyncResult.ok(5);\n * const value2 = yield* AsyncResult.ok(10);\n * return value1 + value2;\n * }\n */\n static run<T, E extends ErrorBase = ErrorBase>(generatorFunc: () => AsyncResultGenerator<T>): AsyncResult<T, E> {\n const iterator = generatorFunc();\n return AsyncResult.fromResultPromise<T, E>(AsyncResult._runGeneratorProcessor<T, E>(iterator)());\n }\n\n\n /**\n * Runs a generator function that yields AsyncResult instances, propagating errors automatically, and updates this AsyncResult in place.\n * If any yielded AsyncResult is an error, the execution stops and this AsyncResult is updated to that error.\n * If all yielded AsyncResults are successful, this AsyncResult is updated to a successful state with the final returned value.\n * \n * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.\n * Think of it as \"async/await\" but for AsyncResult handling in generator functions.\n * \n * @param generatorFunc a generator function that yields AsyncResult instances\n */\n runInPlace(generatorFunc: () => AsyncResultGenerator<T>) {\n const iterator = generatorFunc();\n return this.updateFromResultPromise(AsyncResult._runGeneratorProcessor<T, E>(iterator)());\n }\n\n\n // === Debuging ===\n\n\n log(name?: string) {\n const time = (new Date()).toTimeString().slice(0, 8);\n console.log(`${name ?? \"<Anonymous AsyncResult>\"} ; State at ${time} :`, this.state);\n }\n\n debug(name?: string) {\n return this.listen((r) => r.log(name));\n }\n}\n","import type { AsyncResult } from \"./asyncResult\";\nimport type { ErrorBase } from \"./error\";\nimport type { Result } from \"./result\";\n\n/**\n * The possible states of an AsyncResultList.\n */\nexport type AsyncResultListState = \"any-loading\" | \"all-settled\";\n\nexport interface AsyncResultListItem<T = any, E extends ErrorBase = ErrorBase> {\n key: string;\n result: AsyncResult<T, E>;\n unsub: () => void;\n}\n\n/**\n * A list that manages multiple AsyncResult instances, tracking their states and providing utilities to monitor them.\n */\nexport class AsyncResultList<T = any, E extends ErrorBase = ErrorBase> {\n private _list = new Map<string, AsyncResultListItem<T, E>>();\n private _listeners: Set<(taskQueue: AsyncResultList<T, E>) => void> = new Set();\n private _state: AsyncResultListState = \"all-settled\";\n\n // === Getters ===\n\n /**\n * Gets the current tasks in the AsyncResultList.\n */\n get tasks() {\n return this._list;\n }\n\n /**\n * Gets the number of tasks in the list.\n */\n get length(): number {\n return this._list.size;\n }\n\n /**\n * Gets all tasks in the list as an array.\n */\n get items(): AsyncResult<T, E>[] {\n return Array.from(this._list.values()).map(i => i.result);\n }\n\n /**\n * Gets the current state of the AsyncResultList.\n */\n get state() {\n return this._state;\n }\n\n private set state(s: AsyncResultListState) {\n this._state = s;\n this._listeners.forEach(f => f(this));\n }\n\n private _onTaskFinished() {\n this.state = this.anyLoading() ? \"any-loading\" : \"all-settled\";\n }\n\n // === Listeners ===\n\n /**\n * Adds a listener that gets called whenever the state of the AsyncResultList changes.\n * @param listener the function to call when the state changes\n * @returns a function to unsubscribe the listener\n */\n listen(listener: (taskQueue: AsyncResultList<T, E>) => void) {\n this._listeners.add(listener);\n return () => {\n this._listeners.delete(listener);\n };\n }\n\n // === Managing tasks ===\n\n /**\n * Adds an AsyncResult task to the list.\n * @param key the unique key for the task\n * @param task the AsyncResult task to add\n * @param removeOnSettle whether to remove the task from the list once it settles (defaults to true)\n * @returns the added AsyncResult task\n */\n add(key: string, task: AsyncResult<T, E>, removeOnSettle: boolean = true): AsyncResult<T, E> {\n let unsub = null;\n if (removeOnSettle) {\n unsub = task.listenUntilSettled((r) => {\n if (r.isLoading() || r.isIdle()) return;\n this._onTaskFinished();\n this._list.delete(key);\n }, true)\n } else {\n unsub = task.listen((r) => {\n if (r.isLoading() || r.isIdle()) return;\n this._onTaskFinished();\n }, true);\n }\n\n this._list.set(key, { key, result: task, unsub });\n this.state = \"any-loading\";\n\n return task;\n }\n\n clear() {\n this._list.forEach(({ unsub }) => unsub());\n this._list.clear();\n this.state = \"all-settled\";\n }\n\n // === Querying tasks ===\n\n /**\n * Checks if any task in the list is currently loading.\n * @returns true if any task is loading, false otherwise\n */\n anyLoading(): boolean {\n for (const item of this._list.values()) {\n if (item.result.isLoading()) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets all tasks that satisfy the given predicate.\n * @param predicate the function to test each task\n * @returns an array of tasks that satisfy the predicate\n */\n getAllFiltered(predicate: (task: AsyncResult<T, E>) => boolean): AsyncResult<T, E>[] {\n const filtered: AsyncResult<T, E>[] = [];\n for (const item of this._list.values()) {\n if (predicate(item.result)) {\n filtered.push(item.result);\n }\n }\n return filtered;\n }\n\n /**\n * Gets all tasks that satisfy the given predicate and maps them using the provided function.\n * @param filterPredicate the function to test each task\n * @param mapFunc the function to map each task\n * @returns an array of mapped values\n */\n getAllFilteredAndMap<U>(filterPredicate: (task: AsyncResult<T, E>) => boolean, mapFunc: (task: AsyncResult<T, E>) => U): U[] {\n const results: U[] = [];\n for (const item of this._list.values()) {\n if (filterPredicate(item.result)) {\n results.push(mapFunc(item.result));\n }\n }\n return results;\n }\n\n /**\n * Gets all tasks that have succeeded.\n * @returns an array of successful AsyncResult tasks\n */\n getAllSuccess(): AsyncResult<T, E>[] {\n return this.getAllFiltered((task) => task.isSuccess());\n }\n\n /**\n * Gets the success values of all tasks that have succeeded.\n * @returns an array of successful values\n */\n getAllSuccessValues(): T[] {\n return this.getAllFilteredAndMap((task) => task.isSuccess(), (task) => task.unwrapOrThrow());\n }\n\n /**\n * Gets all tasks that have errored.\n * @returns an array of error AsyncResult tasks\n */\n getAllErrors(): AsyncResult<T, E>[] {\n return this.getAllFiltered((task) => task.isError());\n }\n\n /**\n * Gets the error values of all tasks that have errored.\n * @returns an array of error values\n */\n getAllErrorValues(): E[] {\n return this.getAllFilteredAndMap((task) => task.isError(), (task) => task.unwrapErrorOrNull()!);\n }\n\n /**\n * Gets all tasks that are currently loading.\n * @returns an array of loading AsyncResult tasks\n */\n getAllLoading(): AsyncResult<T, E>[] {\n return this.getAllFiltered((task) => task.isLoading());\n }\n\n /**\n * Gets the promises of all tasks that are currently loading.\n * @returns an array of promises for loading tasks\n */\n getAllLoadingPromises(): Promise<Result<T, E>>[] {\n return this.getAllFilteredAndMap((task) => task.isLoading(), (task) => task.toResultPromise());\n }\n\n // === Debugging utilities ===\n\n /**\n * Logs the current state and tasks of the AsyncResultList to the console.\n * @param name an optional name to identify the log\n */\n log(name?: string) {\n const time = (new Date()).toTimeString().slice(0, 8);\n console.log(`${name ?? '<Anonymous TaskQueue>'} ; State at ${time} :`, this.state, this._list);\n }\n\n /**\n * Sets up a listener to log the state and tasks of the AsyncResultList whenever it changes.\n * @param name an optional name to identify the log\n * @returns a function to unsubscribe the debug listener\n */\n debug(name?: string) {\n return this.listen(() => {\n this.log(name);\n });\n }\n}","import { AsyncResult, type AsyncResultState, type ChainStep } from \"./asyncResult\";\nimport type { ErrorBase } from \"./error\";\n\ntype KeyedAsyncCacheRefetchOptions = {\n policy: 'refetch' | 'if-error' | 'no-refetch';\n};\n\ntype CacheItem<P, V, E extends ErrorBase = ErrorBase> = {\n result: AsyncResult<V, E>;\n fetcherParams: P;\n valid: boolean;\n lastFetched?: number;\n ttl?: number;\n};\n\nconst _defaultRefetchOptions: KeyedAsyncCacheRefetchOptions = { policy: 'no-refetch' };\n\nfunction defaultParamsToKey<P>(params: P): string {\n if (typeof params === 'object') {\n return JSON.stringify(params);\n }\n return String(params);\n}\n\n/**\n * A cache for asynchronous operations that maps parameter sets to their corresponding AsyncResult.\n * Supports automatic refetching based on specified policies.\n * \n * @template P - The type of the parameters used to fetch values.\n * @template V - The type of the values being fetched.\n * @template E - The type of the error, extending ErrorBase (default is ErrorBase).\n */\nexport class KeyedAsyncCache<P, V, E extends ErrorBase = ErrorBase> {\n private _cache: Map<string, CacheItem<P, V, E>> = new Map();\n private _fetcher: ChainStep<P, V, E>;\n private _paramsToKey: (params: P) => string;\n private _cacheTTL?: number;\n\n /**\n * Creates a new KeyedAsyncCache instance.\n * @param fetcher the function used to fetch values based on parameters\n * @param paramsToKey a function that converts parameters to a unique string key (default uses JSON.stringify for objects)\n * @param cacheTTL optional time-to-live for cache entries in milliseconds\n */\n constructor(fetcher: ChainStep<P, V, E>, paramsToKey: (params: P) => string = defaultParamsToKey, cacheTTL: number = Infinity) {\n this._fetcher = fetcher;\n this._paramsToKey = paramsToKey;\n this._cacheTTL = cacheTTL;\n }\n\n private makeCacheItem(result: AsyncResult<V, E>, fetcherParams: P, ttl?: number | undefined): CacheItem<P, V, E> {\n return {\n result,\n fetcherParams,\n ttl: ttl ?? this._cacheTTL,\n valid: true,\n };\n }\n\n private shouldRefetch(existingResult: CacheItem<P, V, E>, refetch: KeyedAsyncCacheRefetchOptions): boolean {\n if (!existingResult.valid) {\n return true;\n }\n if (refetch.policy === 'refetch') {\n return true;\n }\n if (refetch.policy === 'if-error') {\n return existingResult.result.state.status === 'error';\n }\n if (existingResult.ttl !== undefined && existingResult.lastFetched !== undefined) {\n const now = Date.now();\n if (now - existingResult.lastFetched > existingResult.ttl) {\n return true;\n }\n }\n return false;\n }\n\n private updateOrCreateCacheItemFromParams(params: P, cacheItem?: CacheItem<P, V, E>) {\n const promise = Promise.resolve(this._fetcher(params));\n let result = cacheItem?.result.updateFromResultPromise(promise) ?? AsyncResult.fromResultPromise(promise);\n cacheItem = cacheItem ?? this.makeCacheItem(result, params);\n \n promise.then(() => {\n cacheItem.lastFetched = Date.now();\n });\n\n return cacheItem;\n }\n\n /**\n * Gets the AsyncResult for the given parameters, fetching it if not cached or if refetching is required.\n * @param params the parameters to fetch the value\n * @param refetch options determining whether to refetch the value\n * @returns the AsyncResult corresponding to the given parameters\n */\n get(params: P, refetch: KeyedAsyncCacheRefetchOptions = _defaultRefetchOptions): AsyncResult<V, E> {\n const key = this._paramsToKey(params);\n if (this._cache.has(key)) {\n const cacheItem = this._cache.get(key)!;\n if (!this.shouldRefetch(cacheItem, refetch)) {\n return cacheItem.result;\n } else {\n this.updateOrCreateCacheItemFromParams(params, cacheItem);\n return cacheItem.result;\n }\n }\n \n const cacheItem = this.updateOrCreateCacheItemFromParams(params);\n this._cache.set(key, cacheItem);\n return cacheItem.result;\n }\n\n /**\n * Gets the settled state of the AsyncResult for the given parameters, fetching it if not cached or if refetching is required.\n * Waits for the AsyncResult to settle before returning its state.\n * @param params the parameters to fetch the value\n * @param refetch options determining whether to refetch the value\n * @returns a promise resolving to the settled state of the AsyncResult\n */\n async getSettledState(params: P, refetch: KeyedAsyncCacheRefetchOptions = _defaultRefetchOptions): Promise<AsyncResultState<V, E>> {\n const asyncResult = this.get(params, refetch);\n await asyncResult.waitForSettled();\n return asyncResult.state;\n }\n\n /**\n * Checks if any cached AsyncResult is currently loading.\n * @returns whether any cached AsyncResult is loading\n */\n anyLoading(): boolean {\n for (const cacheItem of this._cache.values()) {\n if (cacheItem.result.isLoading()) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Clears the entire cache.\n */\n clear() {\n this._cache.clear();\n }\n\n /**\n * Invalidates the cache entry for the given key.\n * @param key the key of the cache entry to invalidate\n */\n invalidateKey(key: string) {\n if (this._cache.has(key)) {\n const cacheItem = this._cache.get(key)!;\n cacheItem.valid = false;\n }\n }\n\n /**\n * Invalidates the cache entry for the given parameters.\n * @param params the parameters of the cache entry to invalidate\n */\n invalidateParams(params: P) {\n const key = this._paramsToKey(params);\n this.invalidateKey(key);\n }\n\n /**\n * Invalidates all cache entries.\n */\n invalidateAll() {\n for (const cacheItem of this._cache.values()) {\n cacheItem.valid = false;\n }\n }\n}\n","import { AsyncResult } from \"./asyncResult\";\n\nexport function delay(ms: number): AsyncResult<true> {\n return AsyncResult.fromValuePromise(new Promise(resolve => {\n setTimeout(() => resolve(true), ms);\n }));\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,YAAN,MAAgB;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,MAAc,SAAkB,aAAuB,MAAe,MAAM;AACpF,SAAK,OAAO;AACZ,SAAK,UAAU;AACf,SAAK,cAAc;AAEnB,QAAI,KAAK;AACL,WAAK,SAAS;AAAA,IAClB;AAAA,E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AAI,UAAU,OAAO,UAAU,GAAG;AAC9B,eAAO;AAAA,MACX;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA,EAKA,QAAQ;AACJ,SAAK,OAAO,MAAM;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,cAAc,KAAa;AACvB,QAAI,KAAK,OAAO,IAAI,GAAG,GAAG;AACtB,YAAM,YAAY,KAAK,OAAO,IAAI,GAAG;AACrC,gBAAU,QAAQ;AAAA,IACtB;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAiB,QAAW;AACxB,UAAM,MAAM,KAAK,aAAa,MAAM;AACpC,SAAK,cAAc,GAAG;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAgB;AACZ,eAAW,aAAa,KAAK,OAAO,OAAO,GAAG;AAC1C,gBAAU,QAAQ;AAAA,IACtB;AAAA,EACJ;AACJ;;;AC5KO,SAAS,MAAM,IAA+B;AACjD,SAAO,YAAY,iBAAiB,IAAI,QAAQ,aAAW;AACvD,eAAW,MAAM,QAAQ,IAAI,GAAG,EAAE;AAAA,EACtC,CAAC,CAAC;AACN;","names":["cacheItem"]}
|
package/dist/core/index.mjs
CHANGED
|
@@ -702,7 +702,7 @@ var AsyncResultList = class {
|
|
|
702
702
|
* Gets all tasks in the list as an array.
|
|
703
703
|
*/
|
|
704
704
|
get items() {
|
|
705
|
-
return Array.from(this._list.values());
|
|
705
|
+
return Array.from(this._list.values()).map((i) => i.result);
|
|
706
706
|
}
|
|
707
707
|
/**
|
|
708
708
|
* Gets the current state of the AsyncResultList.
|
|
@@ -738,30 +738,36 @@ var AsyncResultList = class {
|
|
|
738
738
|
* @returns the added AsyncResult task
|
|
739
739
|
*/
|
|
740
740
|
add(key, task, removeOnSettle = true) {
|
|
741
|
-
|
|
742
|
-
this.state = "any-loading";
|
|
741
|
+
let unsub = null;
|
|
743
742
|
if (removeOnSettle) {
|
|
744
|
-
task.listenUntilSettled((r) => {
|
|
743
|
+
unsub = task.listenUntilSettled((r) => {
|
|
745
744
|
if (r.isLoading() || r.isIdle()) return;
|
|
746
745
|
this._onTaskFinished();
|
|
747
746
|
this._list.delete(key);
|
|
748
747
|
}, true);
|
|
749
748
|
} else {
|
|
750
|
-
task.listen((r) => {
|
|
749
|
+
unsub = task.listen((r) => {
|
|
751
750
|
if (r.isLoading() || r.isIdle()) return;
|
|
752
751
|
this._onTaskFinished();
|
|
753
752
|
}, true);
|
|
754
753
|
}
|
|
754
|
+
this._list.set(key, { key, result: task, unsub });
|
|
755
|
+
this.state = "any-loading";
|
|
755
756
|
return task;
|
|
756
757
|
}
|
|
758
|
+
clear() {
|
|
759
|
+
this._list.forEach(({ unsub }) => unsub());
|
|
760
|
+
this._list.clear();
|
|
761
|
+
this.state = "all-settled";
|
|
762
|
+
}
|
|
757
763
|
// === Querying tasks ===
|
|
758
764
|
/**
|
|
759
765
|
* Checks if any task in the list is currently loading.
|
|
760
766
|
* @returns true if any task is loading, false otherwise
|
|
761
767
|
*/
|
|
762
768
|
anyLoading() {
|
|
763
|
-
for (const
|
|
764
|
-
if (
|
|
769
|
+
for (const item of this._list.values()) {
|
|
770
|
+
if (item.result.isLoading()) {
|
|
765
771
|
return true;
|
|
766
772
|
}
|
|
767
773
|
}
|
|
@@ -774,9 +780,9 @@ var AsyncResultList = class {
|
|
|
774
780
|
*/
|
|
775
781
|
getAllFiltered(predicate) {
|
|
776
782
|
const filtered = [];
|
|
777
|
-
for (const
|
|
778
|
-
if (predicate(
|
|
779
|
-
filtered.push(
|
|
783
|
+
for (const item of this._list.values()) {
|
|
784
|
+
if (predicate(item.result)) {
|
|
785
|
+
filtered.push(item.result);
|
|
780
786
|
}
|
|
781
787
|
}
|
|
782
788
|
return filtered;
|
|
@@ -789,9 +795,9 @@ var AsyncResultList = class {
|
|
|
789
795
|
*/
|
|
790
796
|
getAllFilteredAndMap(filterPredicate, mapFunc) {
|
|
791
797
|
const results = [];
|
|
792
|
-
for (const
|
|
793
|
-
if (filterPredicate(
|
|
794
|
-
results.push(mapFunc(
|
|
798
|
+
for (const item of this._list.values()) {
|
|
799
|
+
if (filterPredicate(item.result)) {
|
|
800
|
+
results.push(mapFunc(item.result));
|
|
795
801
|
}
|
|
796
802
|
}
|
|
797
803
|
return results;
|