unwrapped 0.1.0 → 0.1.1

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 CHANGED
@@ -1,5 +1,11 @@
1
1
  # unwrapped
2
2
 
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 2606226: added files tin .npmignore
8
+
3
9
  ## 0.1.0
4
10
 
5
11
  ### Minor Changes
@@ -0,0 +1,105 @@
1
+ declare class ErrorBase {
2
+ code: string;
3
+ message?: string | undefined;
4
+ thrownError?: any;
5
+ constructor(code: string, message?: string, thrownError?: any, log?: boolean);
6
+ toString(): string;
7
+ logError(): void;
8
+ }
9
+
10
+ type ResultState<T, E = ErrorBase> = {
11
+ status: 'success';
12
+ value: T;
13
+ } | {
14
+ status: 'error';
15
+ error: E;
16
+ };
17
+ declare class Result<T, E = ErrorBase> {
18
+ private _state;
19
+ constructor(state: ResultState<T, E>);
20
+ get state(): ResultState<T, E>;
21
+ static ok<T, E = ErrorBase>(value: T): Result<T, E>;
22
+ static err<E>(error: E): Result<never, E>;
23
+ static errTag(code: string, message?: string): Result<never, ErrorBase>;
24
+ unwrapOrNull(): T | null;
25
+ unwrapOrThrow(): T;
26
+ unwrapOr<O>(defaultValue: O): T | O;
27
+ isSuccess(): boolean;
28
+ isError(): boolean;
29
+ static tryPromise<T, E>(promise: Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>>;
30
+ static tryFunction<T, E extends ErrorBase = ErrorBase>(fn: () => Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>>;
31
+ chain<O, E2>(fn: (input: T) => ResultState<O, E | E2>): Result<O, E | E2>;
32
+ [Symbol.iterator](): Generator<Result<T, E>, T, any>;
33
+ static run<T, E>(generator: () => Generator<Result<any, E>, T, any>): Result<T, E>;
34
+ }
35
+
36
+ type AsyncResultState<T, E> = {
37
+ status: 'idle';
38
+ } | {
39
+ status: 'loading';
40
+ promise: Promise<Result<T, E>>;
41
+ } | ResultState<T, E>;
42
+ type ChainFunction<I, O, E> = (input: I) => Result<O, E> | Promise<Result<O, E>>;
43
+ type FlatChainFunction<I, O, E> = (input: I) => AsyncResult<O, E>;
44
+ type AsyncResultListener<T, E> = (result: AsyncResult<T, E>) => any;
45
+ declare class AsyncResult<T, E = ErrorBase> {
46
+ private _state;
47
+ private _listeners;
48
+ constructor(state?: AsyncResultState<T, E>);
49
+ get state(): AsyncResultState<T, E>;
50
+ private set state(value);
51
+ static ok<T>(value: T): AsyncResult<T, never>;
52
+ static err<E>(error: E): AsyncResult<never, E>;
53
+ isSuccess(): boolean;
54
+ isError(): boolean;
55
+ isLoading(): boolean;
56
+ listen(listener: AsyncResultListener<T, E>, immediate?: boolean): () => void;
57
+ listenUntilSettled(listener: AsyncResultListener<T, E>, immediate?: boolean): () => void;
58
+ setState(newState: AsyncResultState<T, E>): void;
59
+ copyOnceSettled(other: AsyncResult<T, E>): void;
60
+ update(newState: AsyncResultState<T, E>): void;
61
+ updateToValue(value: T): void;
62
+ updateToError(error: E): void;
63
+ updateFromResultPromise(promise: Promise<Result<T, E>>): void;
64
+ static fromResultPromise<T, E>(promise: Promise<Result<T, E>>): AsyncResult<T, E>;
65
+ updateFromValuePromise(promise: Promise<T>): void;
66
+ static fromValuePromise<T, E>(promise: Promise<T>): AsyncResult<T, E>;
67
+ waitForSettled(): Promise<AsyncResult<T, E>>;
68
+ waitForSettledResult(): Promise<Result<T, E>>;
69
+ toResultPromise(): Promise<Result<T, E>>;
70
+ toValuePromiseThrow(): Promise<T>;
71
+ toValueOrNullPromise(): Promise<T | null>;
72
+ unwrapOrNull(): T | null;
73
+ unwrapOrNullOnceSettled(): Promise<T | null>;
74
+ unwrapOrThrow(): T;
75
+ unwrapOrThrowOnceSettled(): Promise<T>;
76
+ chain<O, E2>(fn: ChainFunction<T, O, E | E2>): AsyncResult<O, E | E2>;
77
+ flatChain<O, E2>(fn: FlatChainFunction<T, O, E | E2>): AsyncResult<O, E | E2>;
78
+ mirror(other: AsyncResult<T, E>): () => void;
79
+ mirrorUntilSettled(other: AsyncResult<T, E>): () => void;
80
+ static ensureAvailable<R extends readonly AsyncResult<any, any>[]>(results: R): AsyncResult<{
81
+ [K in keyof R]: R[K] extends AsyncResult<infer T, any> ? T : never;
82
+ }, R[number] extends AsyncResult<any, infer E> ? E : never>;
83
+ [Symbol.iterator](): Generator<AsyncResult<T, E>, T, any>;
84
+ private static _runGeneratorProcessor;
85
+ static run<T, E = ErrorBase>(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): AsyncResult<T, E>;
86
+ runInPlace(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): void;
87
+ }
88
+
89
+ type KeyedAsyncCacheRefetchOptions = {
90
+ policy: 'refetch' | 'if-error' | 'no-refetch';
91
+ };
92
+ declare class KeyedAsyncCache<P, V, E = ErrorBase> {
93
+ private _cache;
94
+ private _fetcher;
95
+ private _paramsToKey;
96
+ constructor(fetcher: ChainFunction<P, V, E>, paramsToKey?: (params: P) => string);
97
+ private makeCacheItem;
98
+ private shouldRefetch;
99
+ get(params: P, refetch?: KeyedAsyncCacheRefetchOptions): AsyncResult<V, E>;
100
+ getSettledState(params: P, refetch?: KeyedAsyncCacheRefetchOptions): Promise<AsyncResultState<V, E>>;
101
+ anyLoading(): boolean;
102
+ clear(): void;
103
+ }
104
+
105
+ export { AsyncResult, type AsyncResultListener, type AsyncResultState, type ChainFunction, ErrorBase, type FlatChainFunction, KeyedAsyncCache, Result, type ResultState };
@@ -0,0 +1,105 @@
1
+ declare class ErrorBase {
2
+ code: string;
3
+ message?: string | undefined;
4
+ thrownError?: any;
5
+ constructor(code: string, message?: string, thrownError?: any, log?: boolean);
6
+ toString(): string;
7
+ logError(): void;
8
+ }
9
+
10
+ type ResultState<T, E = ErrorBase> = {
11
+ status: 'success';
12
+ value: T;
13
+ } | {
14
+ status: 'error';
15
+ error: E;
16
+ };
17
+ declare class Result<T, E = ErrorBase> {
18
+ private _state;
19
+ constructor(state: ResultState<T, E>);
20
+ get state(): ResultState<T, E>;
21
+ static ok<T, E = ErrorBase>(value: T): Result<T, E>;
22
+ static err<E>(error: E): Result<never, E>;
23
+ static errTag(code: string, message?: string): Result<never, ErrorBase>;
24
+ unwrapOrNull(): T | null;
25
+ unwrapOrThrow(): T;
26
+ unwrapOr<O>(defaultValue: O): T | O;
27
+ isSuccess(): boolean;
28
+ isError(): boolean;
29
+ static tryPromise<T, E>(promise: Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>>;
30
+ static tryFunction<T, E extends ErrorBase = ErrorBase>(fn: () => Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>>;
31
+ chain<O, E2>(fn: (input: T) => ResultState<O, E | E2>): Result<O, E | E2>;
32
+ [Symbol.iterator](): Generator<Result<T, E>, T, any>;
33
+ static run<T, E>(generator: () => Generator<Result<any, E>, T, any>): Result<T, E>;
34
+ }
35
+
36
+ type AsyncResultState<T, E> = {
37
+ status: 'idle';
38
+ } | {
39
+ status: 'loading';
40
+ promise: Promise<Result<T, E>>;
41
+ } | ResultState<T, E>;
42
+ type ChainFunction<I, O, E> = (input: I) => Result<O, E> | Promise<Result<O, E>>;
43
+ type FlatChainFunction<I, O, E> = (input: I) => AsyncResult<O, E>;
44
+ type AsyncResultListener<T, E> = (result: AsyncResult<T, E>) => any;
45
+ declare class AsyncResult<T, E = ErrorBase> {
46
+ private _state;
47
+ private _listeners;
48
+ constructor(state?: AsyncResultState<T, E>);
49
+ get state(): AsyncResultState<T, E>;
50
+ private set state(value);
51
+ static ok<T>(value: T): AsyncResult<T, never>;
52
+ static err<E>(error: E): AsyncResult<never, E>;
53
+ isSuccess(): boolean;
54
+ isError(): boolean;
55
+ isLoading(): boolean;
56
+ listen(listener: AsyncResultListener<T, E>, immediate?: boolean): () => void;
57
+ listenUntilSettled(listener: AsyncResultListener<T, E>, immediate?: boolean): () => void;
58
+ setState(newState: AsyncResultState<T, E>): void;
59
+ copyOnceSettled(other: AsyncResult<T, E>): void;
60
+ update(newState: AsyncResultState<T, E>): void;
61
+ updateToValue(value: T): void;
62
+ updateToError(error: E): void;
63
+ updateFromResultPromise(promise: Promise<Result<T, E>>): void;
64
+ static fromResultPromise<T, E>(promise: Promise<Result<T, E>>): AsyncResult<T, E>;
65
+ updateFromValuePromise(promise: Promise<T>): void;
66
+ static fromValuePromise<T, E>(promise: Promise<T>): AsyncResult<T, E>;
67
+ waitForSettled(): Promise<AsyncResult<T, E>>;
68
+ waitForSettledResult(): Promise<Result<T, E>>;
69
+ toResultPromise(): Promise<Result<T, E>>;
70
+ toValuePromiseThrow(): Promise<T>;
71
+ toValueOrNullPromise(): Promise<T | null>;
72
+ unwrapOrNull(): T | null;
73
+ unwrapOrNullOnceSettled(): Promise<T | null>;
74
+ unwrapOrThrow(): T;
75
+ unwrapOrThrowOnceSettled(): Promise<T>;
76
+ chain<O, E2>(fn: ChainFunction<T, O, E | E2>): AsyncResult<O, E | E2>;
77
+ flatChain<O, E2>(fn: FlatChainFunction<T, O, E | E2>): AsyncResult<O, E | E2>;
78
+ mirror(other: AsyncResult<T, E>): () => void;
79
+ mirrorUntilSettled(other: AsyncResult<T, E>): () => void;
80
+ static ensureAvailable<R extends readonly AsyncResult<any, any>[]>(results: R): AsyncResult<{
81
+ [K in keyof R]: R[K] extends AsyncResult<infer T, any> ? T : never;
82
+ }, R[number] extends AsyncResult<any, infer E> ? E : never>;
83
+ [Symbol.iterator](): Generator<AsyncResult<T, E>, T, any>;
84
+ private static _runGeneratorProcessor;
85
+ static run<T, E = ErrorBase>(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): AsyncResult<T, E>;
86
+ runInPlace(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): void;
87
+ }
88
+
89
+ type KeyedAsyncCacheRefetchOptions = {
90
+ policy: 'refetch' | 'if-error' | 'no-refetch';
91
+ };
92
+ declare class KeyedAsyncCache<P, V, E = ErrorBase> {
93
+ private _cache;
94
+ private _fetcher;
95
+ private _paramsToKey;
96
+ constructor(fetcher: ChainFunction<P, V, E>, paramsToKey?: (params: P) => string);
97
+ private makeCacheItem;
98
+ private shouldRefetch;
99
+ get(params: P, refetch?: KeyedAsyncCacheRefetchOptions): AsyncResult<V, E>;
100
+ getSettledState(params: P, refetch?: KeyedAsyncCacheRefetchOptions): Promise<AsyncResultState<V, E>>;
101
+ anyLoading(): boolean;
102
+ clear(): void;
103
+ }
104
+
105
+ export { AsyncResult, type AsyncResultListener, type AsyncResultState, type ChainFunction, ErrorBase, type FlatChainFunction, KeyedAsyncCache, Result, type ResultState };
@@ -0,0 +1,434 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/core/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AsyncResult: () => AsyncResult,
24
+ ErrorBase: () => ErrorBase,
25
+ KeyedAsyncCache: () => KeyedAsyncCache,
26
+ Result: () => Result
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+
30
+ // src/core/error.ts
31
+ var ErrorBase = class {
32
+ code;
33
+ message;
34
+ thrownError;
35
+ constructor(code, message, thrownError, log = true) {
36
+ this.code = code;
37
+ this.message = message;
38
+ this.thrownError = thrownError;
39
+ if (log) {
40
+ this.logError();
41
+ }
42
+ }
43
+ toString() {
44
+ return `Error ${this.code}: ${this.message ?? ""}`;
45
+ }
46
+ logError() {
47
+ console.error(this.toString(), this.thrownError);
48
+ }
49
+ };
50
+
51
+ // src/core/result.ts
52
+ var Result = class _Result {
53
+ _state;
54
+ constructor(state) {
55
+ this._state = state;
56
+ }
57
+ get state() {
58
+ return this._state;
59
+ }
60
+ static ok(value) {
61
+ return new _Result({ status: "success", value });
62
+ }
63
+ static err(error) {
64
+ return new _Result({ status: "error", error });
65
+ }
66
+ static errTag(code, message) {
67
+ return _Result.err(new ErrorBase(code, message));
68
+ }
69
+ unwrapOrNull() {
70
+ if (this._state.status === "success") {
71
+ return this._state.value;
72
+ }
73
+ return null;
74
+ }
75
+ unwrapOrThrow() {
76
+ if (this._state.status === "success") {
77
+ return this._state.value;
78
+ }
79
+ throw new Error("Tried to unwrap a Result that is not successful");
80
+ }
81
+ unwrapOr(defaultValue) {
82
+ if (this._state.status === "success") {
83
+ return this._state.value;
84
+ }
85
+ return defaultValue;
86
+ }
87
+ isSuccess() {
88
+ return this._state.status === "success";
89
+ }
90
+ isError() {
91
+ return this._state.status === "error";
92
+ }
93
+ static tryPromise(promise, errorMapper) {
94
+ return promise.then((value) => _Result.ok(value)).catch((error) => _Result.err(errorMapper(error)));
95
+ }
96
+ static tryFunction(fn, errorMapper) {
97
+ return _Result.tryPromise(fn(), errorMapper);
98
+ }
99
+ chain(fn) {
100
+ if (this._state.status === "success") {
101
+ return new _Result(fn(this._state.value));
102
+ }
103
+ return _Result.err(this._state.error);
104
+ }
105
+ *[Symbol.iterator]() {
106
+ yield this;
107
+ if (this._state.status === "success") {
108
+ return this._state.value;
109
+ }
110
+ return void 0;
111
+ }
112
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
113
+ static run(generator) {
114
+ const iterator = generator();
115
+ let result = iterator.next();
116
+ while (!result.done) {
117
+ const yielded = result.value;
118
+ if (yielded._state.status === "error") {
119
+ return _Result.err(yielded._state.error);
120
+ }
121
+ result = iterator.next(yielded._state.value);
122
+ }
123
+ return _Result.ok(result.value);
124
+ }
125
+ };
126
+
127
+ // src/core/asyncResult.ts
128
+ var AsyncResult = class _AsyncResult {
129
+ _state;
130
+ _listeners = /* @__PURE__ */ new Set();
131
+ constructor(state) {
132
+ this._state = state || { status: "idle" };
133
+ }
134
+ get state() {
135
+ return this._state;
136
+ }
137
+ set state(newState) {
138
+ this._state = newState;
139
+ this._listeners.forEach((listener) => listener(this));
140
+ }
141
+ static ok(value) {
142
+ return new _AsyncResult({ status: "success", value });
143
+ }
144
+ static err(error) {
145
+ return new _AsyncResult({ status: "error", error });
146
+ }
147
+ isSuccess() {
148
+ return this._state.status === "success";
149
+ }
150
+ isError() {
151
+ return this._state.status === "error";
152
+ }
153
+ isLoading() {
154
+ return this._state.status === "loading";
155
+ }
156
+ listen(listener, immediate = true) {
157
+ this._listeners.add(listener);
158
+ if (immediate) {
159
+ listener(this);
160
+ }
161
+ return () => {
162
+ this._listeners.delete(listener);
163
+ };
164
+ }
165
+ listenUntilSettled(listener, immediate = true) {
166
+ const unsub = this.listen((result) => {
167
+ listener(result);
168
+ if (result.state.status === "success" || result.state.status === "error") {
169
+ unsub();
170
+ }
171
+ }, immediate);
172
+ return unsub;
173
+ }
174
+ setState(newState) {
175
+ this.state = newState;
176
+ }
177
+ copyOnceSettled(other) {
178
+ this.updateFromResultPromise(other.toResultPromise());
179
+ }
180
+ update(newState) {
181
+ this.state = newState;
182
+ }
183
+ updateToValue(value) {
184
+ this.state = { status: "success", value };
185
+ }
186
+ updateToError(error) {
187
+ this.state = { status: "error", error };
188
+ }
189
+ updateFromResultPromise(promise) {
190
+ this.state = { status: "loading", promise };
191
+ promise.then((res) => {
192
+ this.state = res.state;
193
+ }).catch((error) => {
194
+ this.state = { status: "error", error };
195
+ });
196
+ }
197
+ static fromResultPromise(promise) {
198
+ const result = new _AsyncResult();
199
+ result.updateFromResultPromise(promise);
200
+ return result;
201
+ }
202
+ updateFromValuePromise(promise) {
203
+ const resultStatePromise = async () => {
204
+ try {
205
+ const value = await promise;
206
+ return Result.ok(value);
207
+ } catch (error) {
208
+ return Result.err(error);
209
+ }
210
+ };
211
+ this.updateFromResultPromise(resultStatePromise());
212
+ }
213
+ static fromValuePromise(promise) {
214
+ const result = new _AsyncResult();
215
+ result.updateFromValuePromise(promise);
216
+ return result;
217
+ }
218
+ async waitForSettled() {
219
+ if (this._state.status === "loading") {
220
+ try {
221
+ const value = await this._state.promise;
222
+ this._state = value.state;
223
+ } catch (error) {
224
+ this._state = { status: "error", error };
225
+ }
226
+ }
227
+ return this;
228
+ }
229
+ async waitForSettledResult() {
230
+ const settled = await this.waitForSettled();
231
+ if (settled.state.status === "idle" || settled.state.status === "loading") {
232
+ throw new Error("Cannot convert idle or loading AsyncResult to ResultState");
233
+ }
234
+ if (settled.state.status === "error") {
235
+ return Result.err(settled.state.error);
236
+ }
237
+ return Result.ok(settled.state.value);
238
+ }
239
+ async toResultPromise() {
240
+ if (this._state.status === "idle") {
241
+ throw new Error("Cannot convert idle AsyncResult to ResultState");
242
+ }
243
+ if (this._state.status === "loading") {
244
+ try {
245
+ const value = await this._state.promise;
246
+ this._state = value.state;
247
+ } catch (error) {
248
+ this._state = { status: "error", error };
249
+ }
250
+ }
251
+ return new Result(this._state);
252
+ }
253
+ async toValuePromiseThrow() {
254
+ const settled = await this.waitForSettled();
255
+ return settled.unwrapOrThrow();
256
+ }
257
+ async toValueOrNullPromise() {
258
+ const settled = await this.waitForSettled();
259
+ return settled.unwrapOrNull();
260
+ }
261
+ unwrapOrNull() {
262
+ if (this._state.status === "success") {
263
+ return this._state.value;
264
+ }
265
+ return null;
266
+ }
267
+ async unwrapOrNullOnceSettled() {
268
+ return (await this.waitForSettled()).unwrapOrNull();
269
+ }
270
+ unwrapOrThrow() {
271
+ if (this._state.status === "success") {
272
+ return this._state.value;
273
+ }
274
+ throw new Error("Tried to unwrap an AsyncResult that is not successful");
275
+ }
276
+ async unwrapOrThrowOnceSettled() {
277
+ return (await this.waitForSettled()).unwrapOrThrow();
278
+ }
279
+ chain(fn) {
280
+ const newResultBuilder = async () => {
281
+ const settled = await this.waitForSettled();
282
+ if (settled.state.status === "loading" || settled.state.status === "idle") {
283
+ throw new Error("Unexpected state after waitForSettled");
284
+ }
285
+ if (settled.state.status === "error") {
286
+ return Result.err(settled.state.error);
287
+ }
288
+ return fn(settled.state.value);
289
+ };
290
+ return _AsyncResult.fromResultPromise(newResultBuilder());
291
+ }
292
+ flatChain(fn) {
293
+ const newResultBuilder = async () => {
294
+ const settled = await this.waitForSettledResult();
295
+ if (settled.state.status === "error") {
296
+ return Result.err(settled.state.error);
297
+ }
298
+ const nextAsyncResult = fn(settled.state.value);
299
+ const nextSettled = await nextAsyncResult.waitForSettledResult();
300
+ return nextSettled;
301
+ };
302
+ return _AsyncResult.fromResultPromise(newResultBuilder());
303
+ }
304
+ // pipeParallel PipeFunction[] -> AsyncResult<T, E>[]
305
+ // pipeParallelAndCollapse PipeFunction[] -> AsyncResult<T[], E>
306
+ mirror(other) {
307
+ return other.listen((newState) => {
308
+ this.setState(newState.state);
309
+ }, true);
310
+ }
311
+ mirrorUntilSettled(other) {
312
+ return other.listenUntilSettled((newState) => {
313
+ this.setState(newState.state);
314
+ }, true);
315
+ }
316
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
317
+ static ensureAvailable(results) {
318
+ if (results.length === 0) {
319
+ return _AsyncResult.ok(void 0);
320
+ }
321
+ const promise = Promise.all(results.map((r) => r.waitForSettled())).then(
322
+ (settledResults) => {
323
+ for (const res of settledResults) {
324
+ if (res.state.status === "error") {
325
+ return Result.err(res.state.error);
326
+ }
327
+ }
328
+ const values = settledResults.map((r) => r.unwrapOrNull());
329
+ return Result.ok(values);
330
+ }
331
+ );
332
+ return _AsyncResult.fromResultPromise(promise);
333
+ }
334
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
335
+ *[Symbol.iterator]() {
336
+ yield this;
337
+ if (this._state.status === "success") {
338
+ return this._state.value;
339
+ }
340
+ return void 0;
341
+ }
342
+ static _runGeneratorProcessor(iterator) {
343
+ return async () => {
344
+ let result = iterator.next();
345
+ while (!result.done) {
346
+ const yielded = result.value;
347
+ const settled = await yielded.waitForSettledResult();
348
+ if (settled.state.status === "error") {
349
+ return Result.err(settled.state.error);
350
+ }
351
+ result = iterator.next(settled.state.value);
352
+ }
353
+ return Result.ok(result.value);
354
+ };
355
+ }
356
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
357
+ static run(generatorFunc) {
358
+ const iterator = generatorFunc();
359
+ return _AsyncResult.fromResultPromise(_AsyncResult._runGeneratorProcessor(iterator)());
360
+ }
361
+ runInPlace(generatorFunc) {
362
+ const iterator = generatorFunc();
363
+ this.updateFromResultPromise(_AsyncResult._runGeneratorProcessor(iterator)());
364
+ }
365
+ };
366
+
367
+ // src/core/cache.ts
368
+ var _defaultRefetchOptions = { policy: "no-refetch" };
369
+ function defaultParamsToKey(params) {
370
+ if (typeof params === "object") {
371
+ return JSON.stringify(params);
372
+ }
373
+ return String(params);
374
+ }
375
+ var KeyedAsyncCache = class {
376
+ _cache = /* @__PURE__ */ new Map();
377
+ _fetcher;
378
+ _paramsToKey;
379
+ constructor(fetcher, paramsToKey = defaultParamsToKey) {
380
+ this._fetcher = fetcher;
381
+ this._paramsToKey = paramsToKey;
382
+ }
383
+ makeCacheItem(result, fetcherParams) {
384
+ return { result, fetcherParams };
385
+ }
386
+ shouldRefetch(existingResult, refetch) {
387
+ if (refetch.policy === "refetch") {
388
+ return true;
389
+ }
390
+ if (refetch.policy === "if-error") {
391
+ return existingResult.result.state.status === "error";
392
+ }
393
+ return false;
394
+ }
395
+ get(params, refetch = _defaultRefetchOptions) {
396
+ const key = this._paramsToKey(params);
397
+ if (this._cache.has(key)) {
398
+ const cacheItem = this._cache.get(key);
399
+ if (!this.shouldRefetch(cacheItem, refetch)) {
400
+ return cacheItem.result;
401
+ } else {
402
+ cacheItem.result.updateFromResultPromise(Promise.resolve(this._fetcher(cacheItem.fetcherParams)));
403
+ return cacheItem.result;
404
+ }
405
+ }
406
+ const asyncResult = AsyncResult.fromResultPromise(Promise.resolve(this._fetcher(params)));
407
+ this._cache.set(key, this.makeCacheItem(asyncResult, params));
408
+ return asyncResult;
409
+ }
410
+ async getSettledState(params, refetch = _defaultRefetchOptions) {
411
+ const asyncResult = this.get(params, refetch);
412
+ await asyncResult.waitForSettled();
413
+ return asyncResult.state;
414
+ }
415
+ anyLoading() {
416
+ for (const cacheItem of this._cache.values()) {
417
+ if (cacheItem.result.isLoading()) {
418
+ return true;
419
+ }
420
+ }
421
+ return false;
422
+ }
423
+ clear() {
424
+ this._cache.clear();
425
+ }
426
+ };
427
+ // Annotate the CommonJS export names for ESM import in node:
428
+ 0 && (module.exports = {
429
+ AsyncResult,
430
+ ErrorBase,
431
+ KeyedAsyncCache,
432
+ Result
433
+ });
434
+ //# sourceMappingURL=index.js.map