resultar 2.0.0-beta.1 → 2.0.0-beta.2

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/dist/index.d.ts CHANGED
@@ -1,470 +1,15 @@
1
- //#region src/error.d.ts
2
- interface ErrorConfig {
3
- withStackTrace: boolean;
4
- }
5
- //#endregion
6
- //#region src/utils.d.ts
7
- type ExtractOkTypes<T extends readonly Result<unknown, unknown>[]> = { [idx in keyof T]: T[idx] extends Result<infer U, unknown> ? U : never };
8
- type ExtractOkAsyncTypes<T extends readonly ResultAsync<unknown, unknown>[]> = { [idx in keyof T]: T[idx] extends ResultAsync<infer U, unknown> ? U : never };
9
- type ExtractErrTypes<T extends readonly Result<unknown, unknown>[]> = { [idx in keyof T]: T[idx] extends Result<unknown, infer E> ? E : never };
10
- type ExtractErrAsyncTypes<T extends readonly ResultAsync<unknown, unknown>[]> = { [idx in keyof T]: T[idx] extends ResultAsync<unknown, infer E> ? E : never };
11
- type InferOkTypes<R> = R extends Result<infer T, unknown> ? T : never;
12
- type InferErrTypes<R> = R extends Result<unknown, infer E> ? E : never;
13
- type InferAsyncOkTypes<R> = R extends ResultAsync<infer T, unknown> ? T : never;
14
- type InferAsyncErrTypes<R> = R extends ResultAsync<unknown, infer E> ? E : never;
15
- //#endregion
16
- //#region src/result.d.ts
17
- type TaggedValue$1 = {
18
- readonly _tag: string;
19
- };
20
- type TaggedErrorValue$1 = Error & TaggedValue$1;
21
- type TagsOf$1<E> = Extract<E, TaggedValue$1>['_tag'];
22
- type ErrorTagsOf$1<E> = Extract<E, TaggedErrorValue$1>['_tag'];
23
- type ErrorForTag$2<E, Tag extends string> = Extract<E, {
24
- readonly _tag: Tag;
25
- }>;
26
- type ExcludeTag$1<E, Tag extends string> = Exclude<E, {
27
- readonly _tag: Tag;
28
- }>;
29
- type UntaggedError$2<E> = Exclude<Extract<E, Error>, TaggedErrorValue$1>;
30
- type CatchTagHandlerResult$1<Handlers> = { readonly [Key in keyof Handlers]: Handlers[Key] extends ((...args: infer _Args) => infer R) ? R : never }[keyof Handlers];
31
- type MatchTagHandlerResult$1<Handlers> = { readonly [Key in keyof Handlers]: Handlers[Key] extends ((...args: infer _Args) => infer R) ? R : never }[keyof Handlers];
32
- type CatchTagHandlers$1<E, Handlers> = { readonly [Tag in keyof Handlers]: Tag extends TagsOf$1<E> ? (error: ErrorForTag$2<E, Tag & string>) => Result<unknown, unknown> : never };
33
- type MatchTagHandlers$1<E, Handlers> = { readonly [Tag in ErrorTagsOf$1<E>]: (error: ErrorForTag$2<E, Tag>) => unknown } & ([UntaggedError$2<E>] extends [never] ? {
34
- readonly Error?: (error: Error) => unknown;
35
- } : {
36
- readonly Error: (error: UntaggedError$2<E>) => unknown;
37
- }) & { readonly [Tag in keyof Handlers]: Tag extends ErrorTagsOf$1<E> | 'Error' ? Handlers[Tag] : never };
38
- type PartialMatchTagHandlers$1<E, Handlers> = { readonly [Tag in keyof Handlers]: Tag extends ErrorTagsOf$1<E> ? (error: ErrorForTag$2<E, Tag & string>) => unknown : Tag extends 'Error' ? (error: Extract<E, Error>) => unknown : never };
39
- type PipeFn$1<Input, Output> = (input: Input) => Output;
40
- /**
41
- * A Result interface that is used to define the methods that are available on a
42
- * `Result` object.
43
- *
44
- * The immutability of the `Result` object is maintained by the interface.
45
- */
46
- interface Resultable<T, E> {
47
- get value(): T;
48
- get error(): E;
49
- /**
50
- * Used to check if a `Result` is an `OK`
51
- *
52
- * @returns `true` if the result is an `OK` variant of Result
53
- */
54
- isOk(): boolean;
55
- /**
56
- * Used to check if a `Result` is an `Err`
57
- *
58
- * @returns `true` if the result is an `Err` variant of Result
59
- */
60
- isErr(): boolean;
61
- /**
62
- * Unwrap the `Ok` value, or return the default if there is an `Err`
63
- *
64
- * @param v the default value to return if there is an `Err`
65
- */
66
- unwrapOr<A>(defaultValue: A): T | A;
67
- /**
68
- * **This method is unsafe, and should only be used in a test environments**
69
- *
70
- * Takes a `Result<T, E>` and returns a `T` when the result is an `Ok`, otherwise it throws a custom object.
71
- *
72
- * @param config
73
- */
74
- _unsafeUnwrap(config?: ErrorConfig): T;
75
- /**
76
- * **This method is unsafe, and should only be used in a test environments**
77
- *
78
- * takes a `Result<T, E>` and returns a `E` when the result is an `Err`,
79
- * otherwise it throws a custom object.
80
- *
81
- * @param config
82
- */
83
- _unsafeUnwrapErr(config?: ErrorConfig): E;
84
- }
85
- interface ResultOperations<T, E> {
86
- isOk(): this is OkResult<T, E>;
87
- isErr(): this is ErrResult<T, E>;
88
- unwrapOr<A>(defaultValue: A): T | A;
89
- _unsafeUnwrap(config?: ErrorConfig): T;
90
- _unsafeUnwrapErr(config?: ErrorConfig): E;
91
- map<X>(f: (t: T) => X): Result<X, E>;
92
- filterOrElse<U extends T, F>(predicate: (value: T) => value is U, onFalse: (value: T) => F): Result<U, E | F>;
93
- filterOrElse<F>(predicate: (value: T) => boolean, onFalse: (value: T) => F): Result<T, E | F>;
94
- mapErr<X>(fn: (t: E) => X): Result<T, X>;
95
- andThen<X, Y>(f: (t: T) => Result<X, Y>): Result<X, E | Y>;
96
- if(fCondition: (t: T) => boolean): {
97
- true: <X1, Y1>(fTrue: (t: T) => Result<X1, Y1>) => {
98
- false: <X2, Y2>(fFalse: (t: T) => Result<X2, Y2>) => Result<X1 | X2, Y1 | Y2 | E>;
99
- };
100
- };
101
- orElse<R extends Result<unknown, unknown>>(f: (e: E) => R): Result<InferOkTypes<R> | T, InferErrTypes<R>>;
102
- catchTag<const Tag extends TagsOf$1<E>, R extends Result<unknown, unknown>>(tag: Tag, f: (error: ErrorForTag$2<E, Tag>) => R): Result<T | InferOkTypes<R>, ExcludeTag$1<E, Tag> | InferErrTypes<R>>;
103
- catchTags<const Handlers extends object>(handlers: Handlers & CatchTagHandlers$1<E, Handlers>): Result<T | InferOkTypes<CatchTagHandlerResult$1<Handlers>>, ExcludeTag$1<E, keyof Handlers & string> | InferErrTypes<CatchTagHandlerResult$1<Handlers>>>;
104
- asyncAndThen<X, Y>(f: (t: T) => ResultAsync<X, Y>): ResultAsync<X, E | Y>;
105
- asyncMap<X>(f: (t: T) => Promise<X>): ResultAsync<X, E>;
106
- match<A, B = A>(fnOk: (t: T) => A, fnErr: (e: E) => B): A | B;
107
- matchTags<A, const Handlers extends object>(fnOk: (t: T) => A, handlers: Handlers & MatchTagHandlers$1<E, Handlers>): A | MatchTagHandlerResult$1<Handlers>;
108
- matchTagsPartial<A, B, const Handlers extends object>(fnOk: (t: T) => A, handlers: Handlers & PartialMatchTagHandlers$1<E, Handlers>, fallback: (error: E) => B): A | MatchTagHandlerResult$1<Handlers> | B;
109
- pipe<A>(ab: PipeFn$1<Result<T, E>, A>): A;
110
- pipe<A, B>(ab: PipeFn$1<Result<T, E>, A>, bc: PipeFn$1<A, B>): B;
111
- pipe<A, B, C>(ab: PipeFn$1<Result<T, E>, A>, bc: PipeFn$1<A, B>, cd: PipeFn$1<B, C>): C;
112
- log(fn: (t?: T, e?: E) => void): this;
113
- tap(fn: (t: T) => void): this;
114
- tapError(fn: (e: E) => void): this;
115
- finally<X = T, Y = E>(f: (value: X, error: Y) => void): DisposableResult<X, Y>;
116
- unwrapOrThrow(): T;
117
- [Symbol.iterator](): Generator<Result<never, E>, T>;
118
- safeUnwrap(): Generator<Result<never, E>, T>;
119
- }
120
- interface OkResult<T, E> extends ResultOperations<T, E> {
121
- readonly value: T;
122
- }
123
- interface ErrResult<T, E> extends ResultOperations<T, E> {
124
- readonly error: E;
125
- }
126
- type Result<T, E> = OkResult<T, E> | ErrResult<T, E>;
127
- type StrictResult<T, E extends Error = Error> = Result<T, E>;
128
- interface ResultStatic {
129
- [Symbol.hasInstance](value: unknown): boolean;
130
- tryCatch<T, E>(fn: () => Exclude<T, Promise<unknown>>, errorFn?: (e: unknown) => E): Result<T, E>;
131
- fromThrowable<Fn extends (...args: readonly any[]) => unknown, E>(fn: Fn, errorFn?: (e: any) => E): (...args: Parameters<Fn>) => Result<ReturnType<Fn>, E>;
132
- ok<T, E = never>(value: T): OkResult<T, E>;
133
- ok<E = never>(value: void): OkResult<void, E>;
134
- unit<E = never>(): Result<undefined, E>;
135
- err<T = never, E extends string = string>(err: E): ErrResult<T, E>;
136
- err<T = never, E = unknown>(err: E): ErrResult<T, E>;
137
- err<T = never>(err: void): ErrResult<T, void>;
138
- combine<T extends readonly [Result<unknown, unknown>, ...Result<unknown, unknown>[]]>(resultList: T): CombineResults<T>;
139
- combine<T extends readonly Result<unknown, unknown>[]>(resultList: T): CombineResults<T>;
140
- combineWithAllErrors<T extends readonly [Result<unknown, unknown>, ...Result<unknown, unknown>[]]>(resultList: T): CombineResultsWithAllErrorsArray<T>;
141
- combineWithAllErrors<T extends readonly Result<unknown, unknown>[]>(resultList: T): CombineResultsWithAllErrorsArray<T>;
142
- }
143
- declare const Result: ResultStatic;
144
- /**
145
- * A `Disposable` is an object that has a `dispose` method that can be used to
146
- * clean up resources.
147
- */
148
- declare class DisposableResult<T, E> implements Resultable<T, E>, Disposable {
149
- readonly result: Result<T, E>;
150
- private readonly finalizer;
151
- constructor(result: Result<T, E>, finalizer: (value: T, error: E) => void);
152
- get value(): T;
153
- get error(): E;
154
- _unsafeUnwrap(config?: ErrorConfig): T;
155
- _unsafeUnwrapErr(config?: ErrorConfig): E;
156
- isOk(): boolean;
157
- isErr(): boolean;
158
- unwrapOr<A>(defaultValue: A): T | A;
159
- [Symbol.dispose](): void;
160
- }
161
- /**
162
- * Evaluates the given generator to a Result returned or an Err yielded from it,
163
- * whichever comes first.
164
- *
165
- * This function, in combination with `Result.safeUnwrap()`, is intended to emulate
166
- * Rust's ? operator.
167
- * See `/tests/safeTry.test.ts` for examples.
168
- *
169
- * @param body - What is evaluated. In body, `yield* result.safeUnwrap()` works as
170
- * Rust's `result?` expression.
171
- * @returns The first occurence of either an yielded Err or a returned Result.
172
- */
173
- declare function safeTry<T, E>(body: () => Generator<Result<never, E>, Result<T, E>>): Result<T, E>;
174
- declare function safeTry<YieldErr extends Result<never, unknown>, GeneratorReturnResult extends Result<unknown, unknown>>(body: () => Generator<YieldErr, GeneratorReturnResult>): Result<InferOkTypes<GeneratorReturnResult>, InferErrTypes<YieldErr> | InferErrTypes<GeneratorReturnResult>>;
175
- /**
176
- * Evaluates the given generator to a Result returned or an Err yielded from it,
177
- * whichever comes first.
178
- *
179
- * This function, in combination with `Result.safeUnwrap()`, is intended to emulate
180
- * Rust's ? operator.
181
- * See `/tests/safeTry.test.ts` for examples.
182
- *
183
- * @param body - What is evaluated. In body, `yield* result.safeUnwrap()` and
184
- * `yield* resultAsync.safeUnwrap()` work as Rust's `result?` expression.
185
- * @returns The first occurence of either an yielded Err or a returned Result.
186
- */
187
- declare function safeTry<T, E>(body: () => AsyncGenerator<Result<never, E>, Result<T, E>>): ResultAsync<T, E>;
188
- declare function safeTry<YieldErr extends Result<never, unknown>, GeneratorReturnResult extends Result<unknown, unknown>>(body: () => AsyncGenerator<YieldErr, GeneratorReturnResult>): ResultAsync<InferOkTypes<GeneratorReturnResult>, InferErrTypes<YieldErr> | InferErrTypes<GeneratorReturnResult>>;
189
- declare function ok<T, E = never>(value: T): OkResult<T, E>;
190
- declare function ok<E = never>(value: void): OkResult<void, E>;
191
- declare function err<T = never, E extends string = string>(err: E): ErrResult<T, E>;
192
- declare function err<T = never, E = unknown>(err: E): ErrResult<T, E>;
193
- declare function err<T = never>(err: void): ErrResult<T, void>;
194
- declare const fromThrowable: <Fn extends (...args: readonly any[]) => unknown, E>(fn: Fn, errorFn?: (e: any) => E) => (...args: Parameters<Fn>) => Result<ReturnType<Fn>, E>;
195
- declare function unit<E = never>(): OkResult<undefined, E>;
196
- declare const tryCatch: <T, E>(fn: () => Exclude<T, Promise<unknown>>, errorFn?: (e: unknown) => E) => Result<T, E>;
197
- type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, ...0[]];
198
- type CollectResults<T, Collected extends unknown[] = [], Depth extends number = 50> = [Depth] extends [never] ? [] : T extends [infer H, ...infer Rest] ? H extends Result<infer L, infer R> ? CollectResults<Rest, [...Collected, [L, R]], Prev[Depth]> : never : Collected;
199
- type Transpose<A, Transposed extends unknown[][] = [], Depth extends number = 10> = A extends [infer T, ...infer Rest] ? T extends [infer L, infer R] ? Transposed extends [infer PL, infer PR] ? PL extends unknown[] ? PR extends unknown[] ? Transpose<Rest, [[...PL, L], [...PR, R]], Prev[Depth]> : never : never : Transpose<Rest, [[L], [R]], Prev[Depth]> : Transposed : Transposed;
200
- type Combine<T, Depth extends number = 5> = Transpose<CollectResults<T>, [], Depth> extends [infer L, infer R] ? [UnknownMembersToNever<L>, UnknownMembersToNever<R>] : Transpose<CollectResults<T>, [], Depth> extends [] ? [[], []] : never;
201
- type Dedup<T> = T extends Result<infer RL, infer RR> ? Result<RL, RR> : T;
202
- type MemberListOf<T> = ((T extends unknown ? (t: T) => T : never) extends infer U ? (U extends unknown ? (u: U) => unknown : never) extends ((v: infer V) => unknown) ? V : never : never) extends ((_: unknown) => infer W) ? [...MemberListOf<Exclude<T, W>>, W] : [];
203
- type EmptyArrayToNever<T, NeverArrayToNever extends number = 0> = T extends [] ? never : NeverArrayToNever extends 1 ? T extends [never, ...infer Rest] ? [EmptyArrayToNever<Rest>] extends [never] ? never : T : T : T;
204
- type UnknownMembersToNever<T> = T extends [infer H, ...infer R] ? [[unknown] extends [H] ? never : H, ...UnknownMembersToNever<R>] : T;
205
- type MembersToUnion<T> = T extends unknown[] ? T[number] : never;
206
- type IsLiteralArray<T> = T extends {
207
- length: infer L;
208
- } ? L extends number ? number extends L ? 0 : 1 : 0 : 0;
209
- type Traverse<T, Depth extends number = 5> = Combine<T, Depth> extends [infer Oks, infer Errs] ? Result<EmptyArrayToNever<Oks, 1>, MembersToUnion<Errs>> : never;
210
- type TraverseWithAllErrors<T, Depth extends number = 5> = Traverse<T, Depth> extends Result<infer Oks, infer Errs> ? Result<Oks, Errs[]> : never;
211
- type CombineResults<T extends readonly Result<unknown, unknown>[]> = IsLiteralArray<T> extends 1 ? Traverse<T> : Result<ExtractOkTypes<T>, ExtractErrTypes<T>[number]>;
212
- type CombineResultsWithAllErrorsArray<T extends readonly Result<unknown, unknown>[]> = IsLiteralArray<T> extends 1 ? TraverseWithAllErrors<T> : Result<ExtractOkTypes<T>, ExtractErrTypes<T>[number][]>;
213
- //#endregion
214
- //#region src/result-async.d.ts
215
- type TaggedValue = {
216
- readonly _tag: string;
217
- };
218
- type TaggedErrorValue = Error & TaggedValue;
219
- type TagsOf<E> = Extract<E, TaggedValue>['_tag'];
220
- type ErrorTagsOf<E> = Extract<E, TaggedErrorValue>['_tag'];
221
- type ErrorForTag$1<E, Tag extends string> = Extract<E, {
222
- readonly _tag: Tag;
223
- }>;
224
- type ExcludeTag<E, Tag extends string> = Exclude<E, {
225
- readonly _tag: Tag;
226
- }>;
227
- type UntaggedError$1<E> = Exclude<Extract<E, Error>, TaggedErrorValue>;
228
- type CatchTagHandlerResult<Handlers> = { readonly [Key in keyof Handlers]: Handlers[Key] extends ((...args: infer _Args) => infer R) ? R : never }[keyof Handlers];
229
- type MatchTagHandlerResult<Handlers> = { readonly [Key in keyof Handlers]: Handlers[Key] extends ((...args: infer _Args) => infer R) ? R : never }[keyof Handlers];
230
- type CatchTagHandlers<E, Handlers> = { readonly [Tag in keyof Handlers]: Tag extends TagsOf<E> ? (error: ErrorForTag$1<E, Tag & string>) => Result<unknown, unknown> | ResultAsync<unknown, unknown> : never };
231
- type MatchTagHandlers<E, Handlers> = { readonly [Tag in ErrorTagsOf<E>]: (error: ErrorForTag$1<E, Tag>) => unknown } & ([UntaggedError$1<E>] extends [never] ? {
232
- readonly Error?: (error: Error) => unknown;
233
- } : {
234
- readonly Error: (error: UntaggedError$1<E>) => unknown;
235
- }) & { readonly [Tag in keyof Handlers]: Tag extends ErrorTagsOf<E> | 'Error' ? Handlers[Tag] : never };
236
- type PartialMatchTagHandlers<E, Handlers> = { readonly [Tag in keyof Handlers]: Tag extends ErrorTagsOf<E> ? (error: ErrorForTag$1<E, Tag & string>) => unknown : Tag extends 'Error' ? (error: Extract<E, Error>) => unknown : never };
237
- type PipeFn<Input, Output> = (input: Input) => Output;
238
- type HandlerOk<R> = InferOkTypes<R> | InferAsyncOkTypes<R>;
239
- type HandlerErr<R> = InferErrTypes<R> | InferAsyncErrTypes<R>;
240
- declare class DisposableResultAsync<T, E> implements PromiseLike<Result<T, E>> {
241
- private readonly innerPromise;
242
- constructor(res: Promise<Result<T, E>>);
243
- then<A, B>(successCallback?: (res: Result<T, E>) => A | PromiseLike<A>, failureCallback?: (reason: unknown) => B | PromiseLike<B>): PromiseLike<A | B>;
244
- }
245
- /**
246
- * Represents an asynchronous Result type that wraps a Promise of a Result<T, E>.
247
- * This class provides a way to handle asynchronous operations that may succeed with a value of type T
248
- * or fail with an error of type E.
249
- *
250
- * @template T - The type of the success value
251
- * @template E - The type of the error value
252
- *
253
- * @implements {PromiseLike<Result<T, E>>}
254
- *
255
- * @example
256
- * ```typescript
257
- * // Create a successful async result
258
- * const okAsync = ResultAsync.okAsync(42);
259
- *
260
- * // Create a failed async result
261
- * const errAsync = ResultAsync.errAsync(new Error("Something went wrong"));
262
- *
263
- * // Transform a Promise into a ResultAsync
264
- * const resultFromPromise = ResultAsync.fromPromise(
265
- * fetch("https://api.example.com/data"),
266
- * (error) => new Error(`API call failed: ${error}`)
267
- * );
268
- * ```
269
- *
270
- * @remarks
271
- * ResultAsync implements the PromiseLike interface, allowing it to be used with async/await syntax.
272
- * It provides various utility methods for transforming and combining results, similar to the Result type,
273
- * but operating in an asynchronous context.
274
- *
275
- * The class includes methods for:
276
- * - Creating ResultAsync instances (okAsync, errAsync, fromPromise)
277
- * - Transforming values (map, mapErr)
278
- * - Chaining operations (andThen, orElse)
279
- * - Error handling (tapError)
280
- * - Conditional branching (if)
281
- * - Combining multiple ResultAsync instances (combine, combineWithAllErrors)
282
- */
283
- declare class ResultAsync<T, E> implements PromiseLike<Result<T, E>> {
284
- /**
285
- * Returns a ResultAsync instance that is immediately resolved with a Result.ok(value).
286
- *
287
- * @param {T} value - The value to be wrapped in a Result.ok.
288
- * @return {ResultAsync<T, E>} A ResultAsync instance with the given value and error type E.
289
- */
290
- static okAsync<T, E = never>(value: T): ResultAsync<T, E>;
291
- static okAsync<E = never>(value: void): ResultAsync<void, E>;
292
- /**
293
- * Returns a ResultAsync that is immediately resolved with a Result.ok(undefined) value.
294
- *
295
- * @return {ResultAsync<undefined, E>} A ResultAsync instance with undefined as the value type and E as the error type.
296
- */
297
- static unitAsync<E = never>(): ResultAsync<undefined, E>;
298
- /**
299
- * Returns a ResultAsync instance that is immediately resolved with a Result.err(error).
300
- *
301
- * @param {E} error - The error to be wrapped in a Result.err.
302
- * @return {ResultAsync<T, E>} A ResultAsync instance with the given error and value type T.
303
- */
304
- static errAsync<T = never, E = unknown>(err: E): ResultAsync<T, E>;
305
- static errAsync<T = never>(err: void): ResultAsync<T, void>;
306
- /**
307
- * Creates a ResultAsync from a Promise, catching any errors that occur during its execution.
308
- *
309
- * @param fn - The Promise or a function returning a Promise to be wrapped in a ResultAsync.
310
- * @param errorFn - Optional function to transform the caught error into a specific error type.
311
- * If not provided, the original error will be used.
312
- * @returns A ResultAsync that will resolve to Ok with the promise's value if successful,
313
- * or Err with either the transformed error (if errorFn is provided) or the original error.
314
- *
315
- * @example
316
- * ```typescript
317
- * // Without error transformer
318
- * const result = ResultAsync.tryCatch(Promise.resolve(42));
319
- *
320
- * // With error transformer
321
- * const result = ResultAsync.tryCatch(
322
- * fetch('https://api.example.com'),
323
- * (error) => new CustomError('API request failed')
324
- * );
325
- * ```
326
- */
327
- static tryCatch<T>(fn: Promise<T> | (() => Promise<T>)): ResultAsync<T, unknown>;
328
- static tryCatch<T, E>(fn: Promise<T> | (() => Promise<T>), errorFn: (e: unknown) => E): ResultAsync<T, E>;
329
- /**
330
- * Returns a ResultAsync instance that is resolved with a Result.ok(value) or Result.err(error)
331
- * based on the provided promise.
332
- *
333
- * @param {Promise<T>} promise - The promise to be wrapped in a ResultAsync.
334
- * @return {ResultAsync<T, E>} A ResultAsync instance with the given promise and error type E.
335
- */
336
- static fromSafePromise<T, E = never>(promise: PromiseLike<T>): ResultAsync<T, E>;
337
- /**
338
- * Returns a ResultAsync instance that is resolved with a Result.ok(value) or Result.err(error)
339
- * based on the provided promise.
340
- *
341
- * @param {Promise<T>} promise - The promise to be wrapped in a ResultAsync.
342
- * @param {(e: unknown) => E} errorFn - A function that transforms the error from the promise into the error type E.
343
- * @return {ResultAsync<T, E>} A ResultAsync instance with the given promise and error type E.
344
- */
345
- static fromPromise<T, E>(promise: PromiseLike<T>, errorFn: (e: unknown) => E): ResultAsync<T, E>;
346
- static combine<T extends readonly [ResultAsync<unknown, unknown>, ...ResultAsync<unknown, unknown>[]]>(asyncResultList: T): CombineResultAsyncs<T>;
347
- static combine<T extends readonly ResultAsync<unknown, unknown>[]>(asyncResultList: T): CombineResultAsyncs<T>;
348
- static combineWithAllErrors<T extends readonly [ResultAsync<unknown, unknown>, ...ResultAsync<unknown, unknown>[]]>(asyncResultList: T): CombineResultsWithAllErrorsArrayAsync<T>;
349
- static combineWithAllErrors<T extends readonly ResultAsync<unknown, unknown>[]>(asyncResultList: T): CombineResultsWithAllErrorsArrayAsync<T>;
350
- /**
351
- * Wraps a async function with a try catch, creating a new function with the same
352
- * arguments but returning `Ok` if successful, `Err` if the function throws
353
- *
354
- * @param fn function to wrap with ok on success or err on failure
355
- * @param errorFn when an error is thrown, this will wrap the error result if provided
356
- * @returns a new function that returns a `ResultAsync`
357
- */
358
- static fromThrowable<A extends readonly unknown[], T, E>(fn: (...args: A) => Promise<T>, errorFn?: (err: unknown) => E): (...args: A) => ResultAsync<T, E>;
359
- private readonly innerPromise;
360
- constructor(res: Promise<Result<T, E>>);
361
- then<A, B>(successCallback?: (res: Result<T, E>) => A | PromiseLike<A>, failureCallback?: (reason: unknown) => B | PromiseLike<B>): PromiseLike<A | B>;
362
- mapErr<U>(f: (t: E) => U | Promise<U>): ResultAsync<T, U>;
363
- map<X>(f: (t: T) => X | Promise<X>): ResultAsync<X, E>;
364
- filterOrElse<U extends T, F>(predicate: (value: T) => value is U, onFalse: (value: T) => F | Promise<F>): ResultAsync<U, E | F>;
365
- filterOrElse<F>(predicate: (value: T) => boolean | Promise<boolean>, onFalse: (value: T) => F | Promise<F>): ResultAsync<T, E | F>;
366
- andThen<R extends Result<unknown, unknown>>(f: (t: T) => R): ResultAsync<InferOkTypes<R>, InferErrTypes<R> | E>;
367
- andThen<R extends ResultAsync<unknown, unknown>>(f: (t: T) => R): ResultAsync<InferAsyncOkTypes<R>, InferAsyncErrTypes<R> | E>;
368
- andThen<U, F>(f: (t: T) => Result<U, F> | ResultAsync<U, F>): ResultAsync<U, E | F>;
369
- if(fCondition: (t: T) => boolean): {
370
- true: <X1, Y1>(fTrue: (t: T) => ResultAsync<X1, Y1>) => {
371
- false: <X2, Y2>(fFalse: (t: T) => ResultAsync<X2, Y2>) => ResultAsync<X1 | X2, Y1 | Y2 | E>;
372
- };
373
- };
374
- orElse<R extends Result<unknown, unknown>>(f: (e: E) => R): ResultAsync<InferOkTypes<R> | T, InferErrTypes<R>>;
375
- orElse<R extends ResultAsync<unknown, unknown>>(f: (e: E) => R): ResultAsync<InferAsyncOkTypes<R> | T, InferAsyncErrTypes<R>>;
376
- orElse<U, A>(f: (e: E) => Result<U, A> | ResultAsync<U, A>): ResultAsync<U | T, A>;
377
- catchTag<const Tag extends TagsOf<E>, R extends Result<unknown, unknown>>(tag: Tag, f: (error: ErrorForTag$1<E, Tag>) => R): ResultAsync<T | InferOkTypes<R>, ExcludeTag<E, Tag> | InferErrTypes<R>>;
378
- catchTag<const Tag extends TagsOf<E>, R extends ResultAsync<unknown, unknown>>(tag: Tag, f: (error: ErrorForTag$1<E, Tag>) => R): ResultAsync<T | InferAsyncOkTypes<R>, ExcludeTag<E, Tag> | InferAsyncErrTypes<R>>;
379
- catchTag<U, F, const Tag extends TagsOf<E>>(tag: Tag, f: (error: ErrorForTag$1<E, Tag>) => Result<U, F> | ResultAsync<U, F>): ResultAsync<T | U, ExcludeTag<E, Tag> | F>;
380
- catchTags<const Handlers extends object>(handlers: Handlers & CatchTagHandlers<E, Handlers>): ResultAsync<T | HandlerOk<CatchTagHandlerResult<Handlers>>, ExcludeTag<E, keyof Handlers & string> | HandlerErr<CatchTagHandlerResult<Handlers>>>;
381
- match<A, B = A>(ok: (t: T) => A, fnErr: (e: E) => B): Promise<A | B>;
382
- matchTags<A, const Handlers extends object>(ok: (t: T) => A, handlers: Handlers & MatchTagHandlers<E, Handlers>): Promise<A | MatchTagHandlerResult<Handlers>>;
383
- matchTagsPartial<A, B, const Handlers extends object>(ok: (t: T) => A, handlers: Handlers & PartialMatchTagHandlers<E, Handlers>, fallback: (error: E) => B): Promise<A | MatchTagHandlerResult<Handlers> | B>;
384
- unwrapOr<A>(t: A): Promise<T | A>;
385
- unwrapOrThrow(): Promise<T>;
386
- pipe<A>(ab: PipeFn<this, A>): A;
387
- pipe<A, B>(ab: PipeFn<this, A>, bc: PipeFn<A, B>): B;
388
- pipe<A, B, C>(ab: PipeFn<this, A>, bc: PipeFn<A, B>, cd: PipeFn<B, C>): C;
389
- /**
390
- * Runs a side effect for either variant and preserves the original async result.
391
- *
392
- * For `Ok`, the callback receives `(value, undefined)`.
393
- * For `Err`, the callback receives `(undefined, error)`.
394
- * Callback errors and rejected callback promises are intentionally ignored.
395
- *
396
- * Use `map`, `mapErr`, `andThen`, or `orElse` when the callback should
397
- * transform the result.
398
- */
399
- log(f: (t?: T, e?: E) => void | Promise<void>): ResultAsync<T, E>;
400
- /**
401
- * Runs a side effect only for the `Ok` variant and preserves the original async result.
402
- *
403
- * Callback errors and rejected callback promises are intentionally ignored.
404
- * Use `map` or `andThen` when the callback should transform the value.
405
- */
406
- tap(f: (t: T) => void | Promise<void>): ResultAsync<T, E>;
407
- /**
408
- * Runs a side effect only for the `Err` variant and preserves the original async result.
409
- *
410
- * Callback errors and rejected callback promises are intentionally ignored.
411
- * Use `mapErr` or `orElse` when the callback should transform the error.
412
- */
413
- tapError(f: (e: E) => void | Promise<void>): ResultAsync<T, E>;
414
- /**
415
- * Runs a cleanup side effect with `(value, error)` after the inner promise
416
- * settles to a `Result`, then preserves the original async result.
417
- *
418
- * Callback errors and rejected callback promises are intentionally ignored.
419
- */
420
- finally(f: (value: T, error: E) => void | Promise<void>): DisposableResultAsync<T, E>;
421
- [Symbol.asyncIterator](): AsyncGenerator<Result<never, E>, T>;
422
- /**
423
- * @deprecated will be removed in 2.0.0.
424
- *
425
- * You can use `safeTry` without this method.
426
- * @example
427
- * ```typescript
428
- * safeTry(async function* () {
429
- * const okValue = yield* yourResult
430
- * })
431
- * ```
432
- * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
433
- */
434
- safeUnwrap(): AsyncGenerator<Result<never, E>, T>;
435
- }
436
- type StrictResultAsync<T, E extends Error = Error> = ResultAsync<T, E>;
437
- /**
438
- * @deprecated Use `safeTry` instead.
439
- * @see `safeTry`
440
- *
441
- * This will be removed in the next major version.
442
- */
443
- declare function safeTryAsync<T, E>(body: () => AsyncGenerator<Result<never, E>, Result<T, E>>): ResultAsync<T, E>;
444
- declare const okAsync: typeof ResultAsync.okAsync;
445
- declare const errAsync: typeof ResultAsync.errAsync;
446
- declare const fromPromise: typeof ResultAsync.fromPromise;
447
- declare const fromSafePromise: typeof ResultAsync.fromSafePromise;
448
- declare const unitAsync: typeof ResultAsync.unitAsync;
449
- declare const fromThrowableAsync: typeof ResultAsync.fromThrowable;
450
- declare const tryCatchAsync: typeof ResultAsync.tryCatch;
451
- type CombineResultAsyncs<T extends readonly ResultAsync<unknown, unknown>[]> = IsLiteralArray<T> extends 1 ? TraverseAsync<UnwrapAsync<T>> : ResultAsync<ExtractOkAsyncTypes<T>, ExtractErrAsyncTypes<T>[number]>;
452
- type CombineResultsWithAllErrorsArrayAsync<T extends readonly ResultAsync<unknown, unknown>[]> = IsLiteralArray<T> extends 1 ? TraverseWithAllErrorsAsync<UnwrapAsync<T>> : ResultAsync<ExtractOkAsyncTypes<T>, ExtractErrAsyncTypes<T>[number][]>;
453
- type UnwrapAsync<T> = IsLiteralArray<T> extends 1 ? Writable<T> extends [infer H, ...infer Rest] ? H extends PromiseLike<infer HI> ? HI extends Result<unknown, unknown> ? [Dedup<HI>, ...UnwrapAsync<Rest>] : never : never : [] : T extends (infer A)[] ? A extends PromiseLike<infer HI> ? HI extends Result<infer L, infer R> ? Result<L, R>[] : never : never : never;
454
- type TraverseAsync<T, Depth extends number = 5> = IsLiteralArray<T> extends 1 ? Combine<T, Depth> extends [infer Oks, infer Errs] ? ResultAsync<EmptyArrayToNever<Oks>, MembersToUnion<Errs>> : never : T extends (infer I)[] ? Combine<MemberListOf<I>, Depth> extends [infer Oks, infer Errs] ? Oks extends unknown[] ? Errs extends unknown[] ? ResultAsync<EmptyArrayToNever<Oks[number][]>, MembersToUnion<Errs[number][]>> : ResultAsync<EmptyArrayToNever<Oks[number][]>, Errs> : Errs extends unknown[] ? ResultAsync<Oks, MembersToUnion<Errs[number][]>> : ResultAsync<Oks, Errs> : never : never;
455
- type TraverseWithAllErrorsAsync<T, Depth extends number = 5> = TraverseAsync<T, Depth> extends ResultAsync<infer Oks, infer Errs> ? ResultAsync<Oks, Errs[]> : never;
456
- type Writable<T> = T extends readonly unknown[] ? [...T] : T;
457
- //#endregion
1
+ import { S as unit, _ as err, a as fromPromise, b as safeTry, c as okAsync, d as DisposableResult, f as ErrResult, g as StrictResult, h as ResultOperations, i as errAsync, l as tryCatchAsync, m as Result, n as ResultAsync, o as fromSafePromise, p as OkResult, r as StrictResultAsync, s as fromThrowableAsync, t as DisposableResultAsync, u as unitAsync, v as fromThrowable, x as tryCatch, y as ok } from "./result-async-CxGBicja.js";
2
+
458
3
  //#region src/tagged-error.d.ts
459
- type Alpha = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | '_';
460
- type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
4
+ type Alpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" | "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" | "_";
5
+ type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
461
6
  type AlphaNumeric = Alpha | Digit;
462
- type ReservedTemplateVariable = '_tag' | 'cause' | 'fingerprint' | 'message' | 'messageTemplate' | 'name' | 'stack';
463
- type ConsumeTemplateVariable<Template extends string, Accumulator extends string = ''> = Template extends `${infer Character}${infer Rest}` ? Character extends AlphaNumeric ? ConsumeTemplateVariable<Rest, `${Accumulator}${Character}`> : {
7
+ type ReservedTemplateVariable = "_tag" | "cause" | "fingerprint" | "message" | "messageTemplate" | "name" | "stack";
8
+ type ConsumeTemplateVariable<Template extends string, Accumulator extends string = ""> = Template extends `${infer Character}${infer Rest}` ? Character extends AlphaNumeric ? ConsumeTemplateVariable<Rest, `${Accumulator}${Character}`> : {
464
9
  readonly rest: Template;
465
10
  readonly variable: Accumulator;
466
11
  } : {
467
- readonly rest: '';
12
+ readonly rest: "";
468
13
  readonly variable: Accumulator;
469
14
  };
470
15
  type ExtractTemplateVariables<Template extends string> = Template extends `${string}$${infer AfterDollar}` ? AfterDollar extends `${Alpha}${string}` ? ConsumeTemplateVariable<AfterDollar> extends {
@@ -507,7 +52,7 @@ type TaggedEnum<Members extends Record<string, Record<PropertyKey, unknown>>> =
507
52
  type TaggedErrorLike = Error & {
508
53
  readonly _tag: string;
509
54
  };
510
- type TaggedErrorTags<ErrorType extends Error> = Extract<ErrorType, TaggedErrorLike>['_tag'];
55
+ type TaggedErrorTags<ErrorType extends Error> = Extract<ErrorType, TaggedErrorLike>["_tag"];
511
56
  type ErrorForTag<ErrorType extends Error, Tag extends string> = Extract<ErrorType, {
512
57
  readonly _tag: Tag;
513
58
  }>;
@@ -522,11 +67,11 @@ declare const defaultMessageTemplate = "$message";
522
67
  declare function isError(value: unknown): value is Error;
523
68
  declare function isError<Value>(value: Value): value is Extract<Value, Error>;
524
69
  declare const findCause: <T extends Error>(error: Error, ErrorClass: ErrorClass<T>) => T | undefined;
525
- declare function createTaggedError<const Tag extends string, const MessageTemplate extends string = typeof defaultMessageTemplate, Base extends Error = Error>(options: Omit<TaggedErrorOptions<Tag, MessageTemplate, Base>, 'message'> & {
70
+ declare function createTaggedError<const Tag extends string, const MessageTemplate extends string = typeof defaultMessageTemplate, Base extends Error = Error>(options: Omit<TaggedErrorOptions<Tag, MessageTemplate, Base>, "message"> & {
526
71
  readonly message?: RejectReservedTemplateVariables<MessageTemplate>;
527
72
  }): TaggedErrorClass<Tag, MessageTemplate, Base>;
528
73
  declare const matchError: <ErrorType extends Error, ReturnType>(error: ErrorType, handlers: MatchHandlers<ErrorType, ReturnType>) => ReturnType;
529
74
  declare const matchErrorPartial: <ErrorType extends Error, ReturnType>(error: ErrorType, handlers: PartialMatchHandlers<ErrorType, ReturnType>, fallback: (error: ErrorType) => ReturnType) => ReturnType;
530
75
  //#endregion
531
- export { type ErrResult, type OkResult, Result, ResultAsync, type ResultOperations, type StrictResult, type StrictResultAsync, type TaggedEnum, type TaggedErrorClass, type TaggedErrorInstance, type TaggedErrorOptions, createTaggedError, err, errAsync, findCause, fromPromise, fromSafePromise, fromThrowable, fromThrowableAsync, isError, matchError, matchErrorPartial, ok, okAsync, safeTry, safeTryAsync, tryCatch, tryCatchAsync, unit, unitAsync };
76
+ export { DisposableResult, DisposableResultAsync, type ErrResult, type OkResult, Result, ResultAsync, type ResultOperations, type StrictResult, type StrictResultAsync, type TaggedEnum, type TaggedErrorClass, type TaggedErrorInstance, type TaggedErrorOptions, createTaggedError, err, errAsync, findCause, fromPromise, fromSafePromise, fromThrowable, fromThrowableAsync, isError, matchError, matchErrorPartial, ok, okAsync, safeTry, tryCatch, tryCatchAsync, unit, unitAsync };
532
77
  //# sourceMappingURL=index.d.ts.map