resultar 1.4.1 → 1.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +103 -6
- package/dist/{chunk-TU4HOJKA.js → chunk-ZA6ODIRF.js} +63 -4
- package/dist/chunk-ZA6ODIRF.js.map +1 -0
- package/dist/error.d.cts +1 -1
- package/dist/error.d.ts +1 -1
- package/dist/{index-Ct3o3to5.d.cts → index-rRvCJDjp.d.cts} +81 -7
- package/dist/{index-Ct3o3to5.d.ts → index-rRvCJDjp.d.ts} +81 -7
- package/dist/index.cjs +66 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +5 -1
- package/dist/result-async.cjs +61 -2
- package/dist/result-async.cjs.map +1 -1
- package/dist/result-async.d.cts +1 -1
- package/dist/result-async.d.ts +1 -1
- package/dist/result-async.js +3 -1
- package/dist/result.cjs +61 -2
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +1 -1
- package/dist/result.d.ts +1 -1
- package/dist/result.js +3 -1
- package/dist/utils.cjs +59 -2
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +1 -1
- package/dist/utils.d.ts +1 -1
- package/dist/utils.js +1 -1
- package/package.json +25 -19
- package/dist/chunk-TU4HOJKA.js.map +0 -1
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ This package contains a `Result` type that represents either success (`Ok`) or f
|
|
|
14
14
|
|
|
15
15
|
For asynchronous tasks, `resultar` offers a `ResultAsync` class which wraps a `Promise<Result<T, E>>` and gives you the same level of expressivity and control as a regular `Result<T, E>`.
|
|
16
16
|
|
|
17
|
-
`ResultAsync` is `thenable` meaning it **behaves exactly like a native `Promise<Result>`** ... except you have access to the same methods that `Result` provides without having to `await` or `.then` the promise!
|
|
17
|
+
`ResultAsync` is `thenable` meaning it **behaves exactly like a native `Promise<Result>`** ... except you have access to the same methods that `Result` provides without having to `await` or `.then` the promise!
|
|
18
18
|
|
|
19
19
|
### Check out [the wiki](https://github.com/inaiat/resultar/wiki) for examples and best practices.
|
|
20
20
|
|
|
@@ -47,6 +47,7 @@ For asynchronous tasks, `resultar` offers a `ResultAsync` class which wraps a `P
|
|
|
47
47
|
- [`Result.combine` (static class method)](#resultcombine-static-class-method)
|
|
48
48
|
- [`Result.combineWithAllErrors` (static class method)](#resultcombinewithallerrors-static-class-method)
|
|
49
49
|
- [`Result.safeUnwrap()`](#resultsafeunwrap)
|
|
50
|
+
- [`Result.tryCatch` (static class method)](#resulttrycatch-static-class-method)
|
|
50
51
|
+ [Asynchronous API (`ResultAsync`)](#asynchronous-api-resultasync)
|
|
51
52
|
- [`okAsync`](#okasync)
|
|
52
53
|
- [`errAsync`](#errasync)
|
|
@@ -66,12 +67,15 @@ For asynchronous tasks, `resultar` offers a `ResultAsync` class which wraps a `P
|
|
|
66
67
|
- [`ResultAsync.combine` (static class method)](#resultasynccombine-static-class-method)
|
|
67
68
|
- [`ResultAsync.combineWithAllErrors` (static class method)](#resultasynccombinewithallerrors-static-class-method)
|
|
68
69
|
- [`ResultAsync.safeUnwrap()`](#resultasyncsafeunwrap)
|
|
70
|
+
- [`ResultAsync.tryCatch` (static class method)](#resultasynctrycatch-static-class-method)
|
|
69
71
|
+ [Utilities](#utilities)
|
|
70
72
|
- [`fromThrowable`](#fromthrowable)
|
|
71
73
|
- [`fromThrowableAsync`](#fromthrowableasync)
|
|
72
74
|
- [`fromPromise`](#frompromise)
|
|
73
75
|
- [`fromSafePromise`](#fromsafepromise)
|
|
74
76
|
- [`safeTry`](#safetry)
|
|
77
|
+
- [`tryCatch`](#trycatch)
|
|
78
|
+
- [`tryCatchAsync`](#trycatchasync)
|
|
75
79
|
+ [Testing](#testing)
|
|
76
80
|
* [A note on the Package Name](#a-note-on-the-package-name)
|
|
77
81
|
|
|
@@ -423,9 +427,9 @@ const updatedQueryResult = dbQueryResult.orElse((dbError) =>
|
|
|
423
427
|
//
|
|
424
428
|
// err() can be called with a value of any new type that you want
|
|
425
429
|
// it could also be called with the same error value
|
|
426
|
-
//
|
|
430
|
+
//
|
|
427
431
|
// err(dbError)
|
|
428
|
-
: err(500)
|
|
432
|
+
: err(500)
|
|
429
433
|
)
|
|
430
434
|
```
|
|
431
435
|
|
|
@@ -534,7 +538,7 @@ const asyncRes = parseHeaders(rawHeader)
|
|
|
534
538
|
```
|
|
535
539
|
|
|
536
540
|
Note that in the above example if `parseHeaders` returns an `Err` then `.map` and `.asyncMap` will not be invoked, and `asyncRes` variable will resolve to an `Err` when turned into a `Result` using `await` or `.then()`.
|
|
537
|
-
|
|
541
|
+
|
|
538
542
|
[⬆️ Back to top](#toc)
|
|
539
543
|
|
|
540
544
|
---
|
|
@@ -667,6 +671,42 @@ const result = Result.combineWithAllErrors(resultList)
|
|
|
667
671
|
|
|
668
672
|
Allows for unwrapping a `Result` or returning an `Err` implicitly, thereby reducing boilerplate.
|
|
669
673
|
|
|
674
|
+
[⬆️ Back to top](#toc)
|
|
675
|
+
|
|
676
|
+
#### `Result.tryCatch()` (static class method)
|
|
677
|
+
|
|
678
|
+
Provides a convenient way to handle errors in a procedural style, similar to Go's error handling pattern. It wraps a synchronous function call in a try-catch block and returns a Result that can be destructured to access the value or error.
|
|
679
|
+
|
|
680
|
+
**Signature:**
|
|
681
|
+
```typescript
|
|
682
|
+
static tryCatch<T, E>(fn: () => Exclude<T, Promise<any>>, errorFn?: (e: unknown) => E): Result<T, E>
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
**Example:**
|
|
686
|
+
```typescript
|
|
687
|
+
const divide = (a: number, b: number) => {
|
|
688
|
+
if (b === 0) throw new Error("Cannot divide by zero");
|
|
689
|
+
return a / b;
|
|
690
|
+
};
|
|
691
|
+
|
|
692
|
+
// Using destructuring to handle errors procedurally
|
|
693
|
+
const { value, error } = Result.tryCatch(() => divide(10, 2));
|
|
694
|
+
if (error) {
|
|
695
|
+
console.error("Division failed:", error);
|
|
696
|
+
} else {
|
|
697
|
+
console.log("Result:", value); // Result: 5
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// With custom error handling
|
|
701
|
+
const result = Result.tryCatch(
|
|
702
|
+
() => divide(10, 0),
|
|
703
|
+
(e) => `Division error: ${e.message}`
|
|
704
|
+
);
|
|
705
|
+
if (result.isErr()) {
|
|
706
|
+
console.error(result.error); // Division error: Cannot divide by zero
|
|
707
|
+
}
|
|
708
|
+
```
|
|
709
|
+
|
|
670
710
|
|
|
671
711
|
[⬆️ Back to top](#toc)
|
|
672
712
|
|
|
@@ -978,7 +1018,7 @@ usersInCanada.then((usersResult: Result<Array<User>, string>) => {
|
|
|
978
1018
|
|
|
979
1019
|
#### `ResultAsync.unwrapOr` (method)
|
|
980
1020
|
|
|
981
|
-
Unwrap the `Ok` value, or return the default if there is an `Err`.
|
|
1021
|
+
Unwrap the `Ok` value, or return the default if there is an `Err`.
|
|
982
1022
|
Works just like `Result.unwrapOr` but returns a `Promise<T>` instead of `T`.
|
|
983
1023
|
|
|
984
1024
|
**Signature:**
|
|
@@ -1394,6 +1434,45 @@ Allows for unwrapping a `Result` or returning an `Err` implicitly, thereby reduc
|
|
|
1394
1434
|
|
|
1395
1435
|
[⬆️ Back to top](#toc)
|
|
1396
1436
|
|
|
1437
|
+
#### `ResultAsync.tryCatch()` (static class method)
|
|
1438
|
+
|
|
1439
|
+
Similar to `Result.tryCatch`, but for handling asynchronous operations. It wraps a Promise in a try-catch block and returns a ResultAsync that can be awaited and destructured to access the value or error.
|
|
1440
|
+
|
|
1441
|
+
**Signature:**
|
|
1442
|
+
```typescript
|
|
1443
|
+
static tryCatch<T, E>(fn: Promise<T>, errorFn?: (e: unknown) => E): ResultAsync<T, E>
|
|
1444
|
+
```
|
|
1445
|
+
|
|
1446
|
+
**Example:**
|
|
1447
|
+
```typescript
|
|
1448
|
+
const divideAsync = async (a: number, b: number) => {
|
|
1449
|
+
await new Promise(resolve => setTimeout(resolve, 100)); // Simulate async operation
|
|
1450
|
+
if (b === 0) throw new Error("Cannot divide by zero");
|
|
1451
|
+
return a / b;
|
|
1452
|
+
};
|
|
1453
|
+
|
|
1454
|
+
// Using async/await with destructuring
|
|
1455
|
+
const { value, error } = await ResultAsync.tryCatch(divideAsync(10, 2));
|
|
1456
|
+
if (error) {
|
|
1457
|
+
console.error("Async division failed:", error);
|
|
1458
|
+
} else {
|
|
1459
|
+
console.log("Result:", value); // Result: 5
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
// With custom error handling
|
|
1463
|
+
const result = await ResultAsync.tryCatch(
|
|
1464
|
+
divideAsync(10, 0),
|
|
1465
|
+
(e) => `Async division error: ${e.message}`
|
|
1466
|
+
);
|
|
1467
|
+
if (result.isErr()) {
|
|
1468
|
+
console.error(result.error); // Async division error: Cannot divide by zero
|
|
1469
|
+
}
|
|
1470
|
+
```
|
|
1471
|
+
|
|
1472
|
+
The `tryCatch` methods provide a more familiar error handling pattern for developers coming from languages like Go, while still maintaining the type safety and composability of the Result type.
|
|
1473
|
+
|
|
1474
|
+
[⬆️ Back to top](#toc)
|
|
1475
|
+
|
|
1397
1476
|
---
|
|
1398
1477
|
|
|
1399
1478
|
### Utilities
|
|
@@ -1423,10 +1502,28 @@ Please find documentation at [ResultAsync.fromPromise](#resultasyncfrompromise-s
|
|
|
1423
1502
|
|
|
1424
1503
|
[⬆️ Back to top](#toc)
|
|
1425
1504
|
|
|
1505
|
+
---
|
|
1506
|
+
|
|
1507
|
+
#### `tryCatch`
|
|
1508
|
+
|
|
1509
|
+
Top level export of `Result.tryCatch`.
|
|
1510
|
+
Please find documentation at [Result.tryCatch](#resulttrycatch-static-class-method)
|
|
1511
|
+
|
|
1512
|
+
[⬆️ Back to top](#toc)
|
|
1513
|
+
|
|
1514
|
+
---
|
|
1515
|
+
|
|
1516
|
+
#### `tryCatchAsync`
|
|
1517
|
+
|
|
1518
|
+
Top level export of `ResultAsync.tryCatch`.
|
|
1519
|
+
Please find documentation at [ResultAsync.tryCatch](#resultasynctrycatch-static-class-method)
|
|
1520
|
+
|
|
1521
|
+
[⬆️ Back to top](#toc)
|
|
1522
|
+
|
|
1426
1523
|
#### `fromSafePromise`
|
|
1427
1524
|
|
|
1428
1525
|
Top level export of `ResultAsync.fromSafePromise`.
|
|
1429
|
-
Please find documentation at [ResultAsync.fromSafePromise](#
|
|
1526
|
+
Please find documentation at [ResultAsync.fromSafePromise](#resulttasyncfromsafepromise-static-class-method)
|
|
1430
1527
|
|
|
1431
1528
|
[⬆️ Back to top](#toc)
|
|
1432
1529
|
|
|
@@ -26,6 +26,25 @@ var Result = class _Result {
|
|
|
26
26
|
this.value = void 0;
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Creates a `Result` by running a function that might throw.
|
|
31
|
+
* If the function throws, the error will be caught and returned as an `Err`.
|
|
32
|
+
* If the function succeeds, the value will be wrapped in an `Ok`.
|
|
33
|
+
*
|
|
34
|
+
* @param fn - The function to execute, which might throw an error
|
|
35
|
+
* @param errorFn - Optional function to transform the thrown error before wrapping in `Err`
|
|
36
|
+
* @returns A `Result` containing either the function's return value or the caught error
|
|
37
|
+
*/
|
|
38
|
+
static tryCatch(fn, errorFn) {
|
|
39
|
+
try {
|
|
40
|
+
return ok(fn());
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (errorFn) {
|
|
43
|
+
return err(errorFn(error));
|
|
44
|
+
}
|
|
45
|
+
return err(error);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
29
48
|
/**
|
|
30
49
|
* Wraps a function with a try catch, creating a new function with the same
|
|
31
50
|
* arguments but returning `Ok` if successful, `Err` if the function throws
|
|
@@ -71,7 +90,9 @@ var Result = class _Result {
|
|
|
71
90
|
return combineResultList(resultList);
|
|
72
91
|
}
|
|
73
92
|
static combineWithAllErrors(resultList) {
|
|
74
|
-
return combineResultListWithAllErrors(
|
|
93
|
+
return combineResultListWithAllErrors(
|
|
94
|
+
resultList
|
|
95
|
+
);
|
|
75
96
|
}
|
|
76
97
|
value;
|
|
77
98
|
error;
|
|
@@ -285,7 +306,11 @@ var Result = class _Result {
|
|
|
285
306
|
*/
|
|
286
307
|
_unsafeUnwrapErr(config) {
|
|
287
308
|
if (this.state.ok) {
|
|
288
|
-
throw createResultarError(
|
|
309
|
+
throw createResultarError(
|
|
310
|
+
"Called `_unsafeUnwrapErr` on an Ok",
|
|
311
|
+
this,
|
|
312
|
+
config
|
|
313
|
+
);
|
|
289
314
|
}
|
|
290
315
|
return this.error;
|
|
291
316
|
}
|
|
@@ -352,6 +377,7 @@ var ok = Result.ok;
|
|
|
352
377
|
var err = Result.err;
|
|
353
378
|
var fromThrowable = Result.fromThrowable;
|
|
354
379
|
var unit = Result.unit;
|
|
380
|
+
var tryCatch = Result.tryCatch;
|
|
355
381
|
|
|
356
382
|
// src/result-async.ts
|
|
357
383
|
var DisposableResultAsync = class {
|
|
@@ -390,6 +416,36 @@ var ResultAsync = class _ResultAsync {
|
|
|
390
416
|
static errAsync(error) {
|
|
391
417
|
return new _ResultAsync(Promise.resolve(Result.err(error)));
|
|
392
418
|
}
|
|
419
|
+
/**
|
|
420
|
+
* Creates a ResultAsync from a Promise, catching any errors that occur during its execution.
|
|
421
|
+
*
|
|
422
|
+
* @param fn - The Promise to be wrapped in a ResultAsync.
|
|
423
|
+
* @param errorFn - Optional function to transform the caught error into a specific error type.
|
|
424
|
+
* If not provided, the original error will be used.
|
|
425
|
+
* @returns A ResultAsync that will resolve to Ok with the promise's value if successful,
|
|
426
|
+
* or Err with either the transformed error (if errorFn is provided) or the original error.
|
|
427
|
+
*
|
|
428
|
+
* @example
|
|
429
|
+
* ```typescript
|
|
430
|
+
* // Without error transformer
|
|
431
|
+
* const result = ResultAsync.tryCatch(Promise.resolve(42));
|
|
432
|
+
*
|
|
433
|
+
* // With error transformer
|
|
434
|
+
* const result = ResultAsync.tryCatch(
|
|
435
|
+
* fetch('https://api.example.com'),
|
|
436
|
+
* (error) => new CustomError('API request failed')
|
|
437
|
+
* );
|
|
438
|
+
* ```
|
|
439
|
+
*/
|
|
440
|
+
static tryCatch(fn, errorFn) {
|
|
441
|
+
const newPromise = fn.then((value) => Result.ok(value)).catch((error) => {
|
|
442
|
+
if (errorFn) {
|
|
443
|
+
return Result.err(errorFn(error));
|
|
444
|
+
}
|
|
445
|
+
return Result.err(error);
|
|
446
|
+
});
|
|
447
|
+
return new _ResultAsync(newPromise);
|
|
448
|
+
}
|
|
393
449
|
static fromSafePromise(promise) {
|
|
394
450
|
const newPromise = promise.then((value) => Result.ok(value));
|
|
395
451
|
return new _ResultAsync(newPromise);
|
|
@@ -617,6 +673,7 @@ var fromPromise = ResultAsync.fromPromise;
|
|
|
617
673
|
var fromSafePromise = ResultAsync.fromSafePromise;
|
|
618
674
|
var unitAsync = ResultAsync.unitAsync;
|
|
619
675
|
var fromThrowableAsync = ResultAsync.fromThrowable;
|
|
676
|
+
var tryCatchAsync = ResultAsync.tryCatch;
|
|
620
677
|
|
|
621
678
|
// src/utils.ts
|
|
622
679
|
var combineResultList = (resultList) => {
|
|
@@ -663,6 +720,7 @@ export {
|
|
|
663
720
|
err,
|
|
664
721
|
fromThrowable,
|
|
665
722
|
unit,
|
|
723
|
+
tryCatch,
|
|
666
724
|
DisposableResultAsync,
|
|
667
725
|
ResultAsync,
|
|
668
726
|
safeTryAsync,
|
|
@@ -671,6 +729,7 @@ export {
|
|
|
671
729
|
fromPromise,
|
|
672
730
|
fromSafePromise,
|
|
673
731
|
unitAsync,
|
|
674
|
-
fromThrowableAsync
|
|
732
|
+
fromThrowableAsync,
|
|
733
|
+
tryCatchAsync
|
|
675
734
|
};
|
|
676
|
-
//# sourceMappingURL=chunk-
|
|
735
|
+
//# sourceMappingURL=chunk-ZA6ODIRF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/result.ts","../src/result-async.ts","../src/utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport type { ErrorConfig } from './error.js'\nimport { createResultarError } from './error.js'\nimport { errAsync, ResultAsync } from './result-async.js'\nimport type { ExtractErrTypes, ExtractOkTypes, InferErrTypes, InferOkTypes } from './utils.js'\nimport { combineResultList, combineResultListWithAllErrors } from './utils.js'\nclass Ok<T> {\n readonly ok = true\n constructor(public readonly value: T) {}\n}\n\nclass Err<E> {\n readonly ok = false\n constructor(public readonly error: E) {}\n}\n\n/**\n * A Result interface that is used to define the methods that are available on a\n * `Result` object.\n *\n * The immutability of the `Result` object is maintained by the interface.\n */\ninterface Resultable<T, E> {\n get value(): T\n get error(): E\n\n /**\n * Used to check if a `Result` is an `OK`\n *\n * @returns `true` if the result is an `OK` variant of Result\n */\n isOk(): boolean\n\n /**\n * Used to check if a `Result` is an `Err`\n *\n * @returns `true` if the result is an `Err` variant of Result\n */\n isErr(): boolean\n /**\n * Unwrap the `Ok` value, or return the default if there is an `Err`\n *\n * @param v the default value to return if there is an `Err`\n */\n\n unwrapOr<A>(defaultValue: A): T | A\n\n // safeUnwrap(): Generator<Result<never, E>, T>\n\n /**\n * **This method is unsafe, and should only be used in a test environments**\n *\n * Takes a `Result<T, E>` and returns a `T` when the result is an `Ok`, otherwise it throws a custom object.\n *\n * @param config\n */\n _unsafeUnwrap(config?: ErrorConfig): T\n\n /**\n * **This method is unsafe, and should only be used in a test environments**\n *\n * takes a `Result<T, E>` and returns a `E` when the result is an `Err`,\n * otherwise it throws a custom object.\n *\n * @param config\n */\n _unsafeUnwrapErr(config?: ErrorConfig): E\n}\n\n/**\n * A `Result` is a type that represents either success (`Ok`) or failure (`Err`).\n * It is often used to replace exceptions or `null` returns.\n * `Result` is often used to handle errors in a functional way.\n * The `Result` type is often used to handle errors in a functional way.\n */\nexport class Result<T, E> implements Resultable<T, E> {\n /**\n * Creates a `Result` by running a function that might throw.\n * If the function throws, the error will be caught and returned as an `Err`.\n * If the function succeeds, the value will be wrapped in an `Ok`.\n *\n * @param fn - The function to execute, which might throw an error\n * @param errorFn - Optional function to transform the thrown error before wrapping in `Err`\n * @returns A `Result` containing either the function's return value or the caught error\n */\n static tryCatch<T, E>(\n fn: () => Exclude<T, Promise<unknown>>,\n errorFn?: (e: unknown) => E,\n ): Result<T, E> {\n try {\n return ok(fn())\n } catch (error) {\n if (errorFn) {\n return err(errorFn(error))\n }\n return err(error as E)\n }\n }\n\n /**\n * Wraps a function with a try catch, creating a new function with the same\n * arguments but returning `Ok` if successful, `Err` if the function throws\n *\n * @param fn function to wrap with ok on success or err on failure\n * @param errorFn when an error is thrown, this will wrap the error result if provided\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static fromThrowable<Fn extends (...args: readonly any[]) => unknown, E>(\n fn: Fn,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n errorFn?: (e: any) => E,\n ): (...args: Parameters<Fn>) => Result<ReturnType<Fn>, E> {\n return (...args) => {\n try {\n const result = fn(...args)\n return ok(result as ReturnType<Fn>)\n } catch (error) {\n if (errorFn) {\n return err(errorFn(error))\n }\n\n return err(error as E)\n }\n }\n }\n\n /**\n * Creates a new `Result` instance representing a successful operation.\n *\n * @param {T} value - The value to be wrapped in the `Result` instance.\n * @return {Result<T, E>} A new `Result` instance with the provided value.\n */\n static ok<T, E = never>(value: T): Result<T, E> {\n return new Result<T, E>(new Ok(value))\n }\n\n /**\n * Creates a new `Result` instance representing a successful operation with an undefined value.\n *\n * @return {Result<undefined, E>} A new `Result` instance with an undefined value.\n */\n static unit<E = never>(): Result<undefined, E> {\n return new Result<undefined, E>(new Ok(undefined))\n }\n\n static err<T = never, E = unknown>(error: E): Result<T, E> {\n return new Result<T, E>(new Err(error))\n }\n\n static combine<\n T extends readonly [\n Result<unknown, unknown>,\n ...Result<unknown, unknown>[],\n ],\n >(resultList: T): CombineResults<T>\n static combine<T extends readonly Result<unknown, unknown>[]>(\n resultList: T,\n ): CombineResults<T>\n static combine<\n T extends readonly [\n Result<unknown, unknown>,\n ...Result<unknown, unknown>[],\n ],\n >(resultList: T): CombineResults<T> {\n return combineResultList(resultList) as CombineResults<T>\n }\n\n static combineWithAllErrors<\n T extends readonly [\n Result<unknown, unknown>,\n ...Result<unknown, unknown>[],\n ],\n >(resultList: T): CombineResultsWithAllErrorsArray<T>\n static combineWithAllErrors<T extends readonly Result<unknown, unknown>[]>(\n resultList: T,\n ): CombineResultsWithAllErrorsArray<T>\n static combineWithAllErrors<T extends readonly Result<unknown, unknown>[]>(\n resultList: T,\n ): CombineResultsWithAllErrorsArray<T> {\n return combineResultListWithAllErrors(\n resultList,\n ) as CombineResultsWithAllErrorsArray<T>\n }\n\n readonly value: T\n readonly error: E\n\n private constructor(private readonly state: Ok<T> | Err<E>) {\n if (state.ok) {\n this.value = state.value\n this.error = undefined as E\n } else {\n this.error = state.error\n this.value = undefined as T\n }\n }\n\n /**\n * Used to check if a `Result` is an `OK`\n *\n * @returns `true` if the result is an `OK` variant of Result\n */\n isOk(): boolean {\n return this.state.ok\n }\n\n /**\n * Used to check if a `Result` is an `Err`\n *\n * @returns `true` if the result is an `Err` variant of Result\n */\n isErr(): boolean {\n return !this.state.ok\n }\n\n /**\n * Maps a `Result<T, E>` to `Result<U, E>`\n * by applying a function to a contained `Ok` value, leaving an `Err` value\n * untouched.\n *\n * @param f The function to apply an `OK` value\n * @returns the result of applying `f` or an `Err` untouched\n */\n map<X>(f: (t: T) => X): Result<X, E> {\n if (this.state.ok) {\n const value = f(this.value)\n return ok(value)\n }\n\n return err(this.error)\n }\n\n /**\n * Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a\n * contained `Err` value, leaving an `Ok` value untouched.\n *\n * This function can be used to pass through a successful result while\n * handling an error.\n *\n * @param f a function to apply to the error `Err` value\n */\n mapErr<X>(fn: (t: E) => X): Result<T, X> {\n if (this.state.ok) {\n return ok(this.value)\n }\n\n return err(fn(this.error))\n }\n\n /**\n * Similar to `map` Except you must return a new `Result`.\n *\n * This is useful for when you need to do a subsequent computation using the\n * inner `T` value, but that computation might fail.\n * Additionally, `andThen` is really useful as a tool to flatten a\n * `Result<Result<A, E2>, E1>` into a `Result<A, E2>` (see example below).\n *\n * @param f The function to apply to the current value\n */\n andThen<X, Y>(f: (t: T) => Result<X, Y>): Result<X, E | Y> {\n if (this.state.ok) {\n return f(this.value)\n }\n\n return err(this.error)\n }\n\n if(fCondition: (t: T) => boolean): {\n true: <X1, Y1>(fTrue: (t: T) => Result<X1, Y1>) => {\n false: <X2, Y2>(\n fFalse: (t: T) => Result<X2, Y2>,\n ) => Result<X1 | X2, Y1 | Y2 | E>\n }\n } {\n return {\n true: <X1, Y1>(fTrue: (t: T) => Result<X1, Y1>) => ({\n false: <X2, Y2>(\n fFalse: (t: T) => Result<X2, Y2>,\n ): Result<X1 | X2, Y1 | Y2 | E> => {\n if (this.state.ok) {\n const condition = fCondition(this.value)\n return condition ? fTrue(this.value) : fFalse(this.value)\n }\n\n return err(this.error)\n },\n }),\n }\n }\n\n /**\n * Takes an `Err` value and maps it to a `Result<T, SomeNewType>`.\n *\n * This is useful for error recovery.\n *\n * @param f A function to apply to an `Err` value, leaving `Ok` values\n * untouched.\n */\n orElse<R extends Result<unknown, unknown>>(\n f: (e: E) => R,\n ): Result<InferOkTypes<R> | T, InferErrTypes<R>>\n orElse<U, A>(f: (e: E) => Result<U, A>): Result<U | T, A> {\n if (this.state.ok) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return ok(this.value as Exclude<T, Promise<any>>)\n }\n\n return f(this.error)\n }\n\n /**\n * Similar to `map` Except you must return a new `Result`.\n *\n * This is useful for when you need to do a subsequent async computation using\n * the inner `T` value, but that computation might fail. Must return a ResultAsync\n *\n * @param f The function that returns a `ResultAsync` to apply to the current\n * value\n */\n asyncAndThen<X, Y>(f: (t: T) => ResultAsync<X, Y>): ResultAsync<X, E | Y>\n asyncAndThen<X, Y>(f: (t: T) => ResultAsync<X, E>): ResultAsync<X, E | Y> {\n if (this.state.ok) {\n return f(this.value)\n }\n\n return errAsync(this.error)\n }\n\n /**\n * Maps a `Result<T, E>` to `ResultAsync<U, E>`\n * by applying an async function to a contained `Ok` value, leaving an `Err`\n * value untouched.\n *\n * @param f An async function to apply an `OK` value\n */\n asyncMap<X>(f: (t: T) => Promise<X>): ResultAsync<X, E> {\n if (this.state.ok) {\n return ResultAsync.fromSafePromise(f(this.value))\n }\n\n return errAsync(this.error)\n }\n\n /**\n * Unwrap the `Ok` value, or return the default if there is an `Err`\n *\n * @param v the default value to return if there is an `Err`\n */\n unwrapOr<A>(defaultValue: A): T | A {\n if (this.state.ok) {\n return this.value\n }\n\n return defaultValue\n }\n\n /**\n * Given 2 functions (one for the `Ok` variant and one for the `Err` variant)\n * execute the function that matches the `Result` variant.\n *\n * Match callbacks do not necessitate to return a `Result`, however you can\n * return a `Result` if you want to.\n *\n * `match` is like chaining `map` and `mapErr`, with the distinction that\n * with `match` both functions must have the same return type.\n *\n * @param ok\n * @param err\n */\n match<A, B = A>(fnOk: (t: T) => A, fnErr: (e: E) => B): A | B {\n if (this.state.ok) {\n return fnOk(this.value)\n }\n\n return fnErr(this.error)\n }\n\n /**\n * Performs a side effect for the `Ok` or `Err` variant of `Result`.\n *\n * @param fn The function to apply an `OK` value\n * @returns the result of applying `f` or an `Err` untouched\n */\n log(fn: (t?: T, e?: E) => void): this {\n try {\n fn(this.value, this.error)\n } catch { /* empty */ }\n\n return this\n }\n\n /**\n * Performs a side effect for the `Ok` variant of `Result`.\n *\n * @param fn The function to apply an `OK` value\n * @returns the result of applying `f` or an `Err` untouched\n */\n tap(fn: (t: T) => void): this {\n if (this.state.ok) {\n try {\n fn(this.value)\n } catch { /* empty */ }\n }\n\n return this\n }\n\n /**\n * Performs a side effect for the `Err` variant of `Result`.\n *\n * @param fn The function to apply an `Err` value\n * @returns the result of applying `f` or an `Ok` untouched\n */\n tapError(fn: (e: E) => void): this {\n if (!this.state.ok) {\n try {\n fn(this.error)\n } catch { /* empty */ }\n }\n\n return this\n }\n\n /**\n * This method is used to clean up and release any resources that the `Result`\n * @param f The function that will be called to clean up the resources\n */\n finally<X = T, Y = E>(\n f: (value: X, error: Y) => void,\n ): DisposableResult<X, Y>\n finally(f: (value: T, error: E) => void): DisposableResult<T, E> {\n const resultDisposable = new DisposableResult(this, f)\n try {\n return resultDisposable\n } finally {\n resultDisposable[Symbol.dispose]()\n }\n }\n\n unwrapOrThrow(): T {\n if (this.state.ok) {\n return this.value\n }\n\n // eslint-disable-next-line @typescript-eslint/only-throw-error\n throw this.error\n }\n\n /**\n * **This method is unsafe, and should only be used in a test environments**\n *\n * Takes a `Result<T, E>` and returns a `T` when the result is an `Ok`, otherwise it throws a custom object.\n *\n * @param config\n */\n _unsafeUnwrap(config?: ErrorConfig): T {\n if (this.state.ok) {\n return this.value\n }\n\n throw createResultarError('Called `_unsafeUnwrap` on an Err', this, config)\n }\n\n /**\n * **This method is unsafe, and should only be used in a test environments**\n *\n * takes a `Result<T, E>` and returns a `E` when the result is an `Err`,\n * otherwise it throws a custom object.\n *\n * @param config\n */\n _unsafeUnwrapErr(config?: ErrorConfig): E {\n if (this.state.ok) {\n throw createResultarError(\n 'Called `_unsafeUnwrapErr` on an Ok',\n this,\n config,\n )\n }\n\n return this.error\n }\n\n *[Symbol.iterator](): Generator<Result<never, E>, T> {\n if (this.state.ok) {\n return this.value\n }\n\n // eslint-disable-next-line unicorn/no-this-assignment, @typescript-eslint/no-this-alias\n const self: Result<T, E> = this\n yield self as Result<never, E>\n return self as T\n }\n\n safeUnwrap(): Generator<Result<never, E>, T> {\n if (this.state.ok) {\n const { value } = this\n /* eslint-disable-next-line require-yield */\n return (function*() {\n return value\n })()\n }\n\n const { error } = this\n return (function*() {\n yield err(error)\n\n throw new Error('Do not use this generator out of `safeTry`')\n })()\n }\n}\n\n/**\n * A `Disposable` is an object that has a `dispose` method that can be used to\n * clean up resources.\n */\nexport class DisposableResult<T, E> implements Resultable<T, E>, Disposable {\n constructor(\n readonly result: Resultable<T, E>,\n private readonly finalizer: (value: T, error: E) => void,\n ) {}\n\n get value(): T {\n return this.result.value\n }\n\n get error(): E {\n return this.result.error\n }\n\n _unsafeUnwrap(config?: ErrorConfig): T {\n return this.result._unsafeUnwrap(config)\n }\n\n _unsafeUnwrapErr(config?: ErrorConfig): E {\n return this.result._unsafeUnwrapErr(config)\n }\n\n isOk(): boolean {\n return this.result.isOk()\n }\n\n isErr(): boolean {\n return this.result.isErr()\n }\n\n unwrapOr<A>(defaultValue: A): T | A {\n return this.result.unwrapOr(defaultValue)\n }\n\n [Symbol.dispose](): void {\n this.finalizer(this.result.value, this.result.error)\n }\n}\n\n/**\n * Evaluates the given generator to a Result returned or an Err yielded from it,\n * whichever comes first.\n *\n * This function, in combination with `Result.safeUnwrap()`, is intended to emulate\n * Rust's ? operator.\n * See `/tests/safeTry.test.ts` for examples.\n *\n * @param body - What is evaluated. In body, `yield* result.safeUnwrap()` works as\n * Rust's `result?` expression.\n * @returns The first occurence of either an yielded Err or a returned Result.\n */\nexport function safeTry<T, E>(\n body: () => Generator<Result<never, E>, Result<T, E>>,\n): Result<T, E>\nexport function safeTry<\n YieldErr extends Result<never, unknown>,\n GeneratorReturnResult extends Result<unknown, unknown>,\n>(\n body: () => Generator<YieldErr, GeneratorReturnResult>,\n): Result<\n InferOkTypes<GeneratorReturnResult>,\n InferErrTypes<YieldErr> | InferErrTypes<GeneratorReturnResult>\n>\n\n/**\n * Evaluates the given generator to a Result returned or an Err yielded from it,\n * whichever comes first.\n *\n * This function, in combination with `Result.safeUnwrap()`, is intended to emulate\n * Rust's ? operator.\n * See `/tests/safeTry.test.ts` for examples.\n *\n * @param body - What is evaluated. In body, `yield* result.safeUnwrap()` and\n * `yield* resultAsync.safeUnwrap()` work as Rust's `result?` expression.\n * @returns The first occurence of either an yielded Err or a returned Result.\n */\nexport function safeTry<T, E>(\n body: () => AsyncGenerator<Result<never, E>, Result<T, E>>,\n): ResultAsync<T, E>\nexport function safeTry<\n YieldErr extends Result<never, unknown>,\n GeneratorReturnResult extends Result<unknown, unknown>,\n>(\n body: () => AsyncGenerator<YieldErr, GeneratorReturnResult>,\n): ResultAsync<\n InferOkTypes<GeneratorReturnResult>,\n InferErrTypes<YieldErr> | InferErrTypes<GeneratorReturnResult>\n>\nexport function safeTry<T, E>(\n body:\n | (() => Generator<Result<never, E>, Result<T, E>>)\n | (() => AsyncGenerator<Result<never, E>, Result<T, E>>),\n): Result<T, E> | ResultAsync<T, E> {\n const n = body().next()\n if (n instanceof Promise) {\n return new ResultAsync(n.then((r) => r.value))\n }\n\n return n.value\n}\n\nexport const ok = Result.ok\nexport const err = Result.err\nexport const fromThrowable = Result.fromThrowable\nexport const unit = Result.unit\nexport const tryCatch = Result.tryCatch\n\n// #region Combine - Types\n\n// This is a helper type to prevent infinite recursion in typing rules.\n//\n// Use this with your `depth` variable in your types.\ntype Prev = [\n never,\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 14,\n 15,\n 16,\n 17,\n 18,\n 19,\n 20,\n 21,\n 22,\n 23,\n 24,\n 25,\n 26,\n 27,\n 28,\n 29,\n 30,\n 31,\n 32,\n 33,\n 34,\n 35,\n 36,\n 37,\n 38,\n 39,\n 40,\n 41,\n 42,\n 43,\n 44,\n 45,\n 46,\n 47,\n 48,\n 49,\n ...0[],\n]\n\n// Collects the results array into separate tuple array.\n//\n// T - The array of the results\n// Collected - The collected tuples.\n// Depth - The maximum depth.\ntype CollectResults<\n T,\n Collected extends unknown[] = [],\n Depth extends number = 50,\n> = [\n Depth,\n] extends [never] ? []\n : T extends [infer H, ...infer Rest]\n // And test whether the head of the list is a result\n ? H extends Result<infer L, infer R>\n // Continue collecting...\n ? CollectResults<\n // the rest of the elements\n Rest,\n // The collected\n [...Collected, [L, R]],\n // and one less of the current depth\n Prev[Depth]\n >\n : never // Impossible\n : Collected\n\n// Transposes an array\n//\n// A - The array source\n// Transposed - The collected transposed array\n// Depth - The maximum depth.\nexport type Transpose<\n A,\n Transposed extends unknown[][] = [],\n Depth extends number = 10,\n> = A extends [infer T, ...infer Rest]\n ? T extends [infer L, infer R]\n ? Transposed extends [infer PL, infer PR]\n ? PL extends unknown[] ? PR extends unknown[] ? Transpose<Rest, [[...PL, L], [...PR, R]], Prev[Depth]>\n : never\n : never\n : Transpose<Rest, [[L], [R]], Prev[Depth]>\n : Transposed\n : Transposed\n\n// Combines the both sides of the array of the results into a tuple of the\n// union of the ok types and the union of the err types.\n//\n// T - The array of the results\n// Depth - The maximum depth.\nexport type Combine<T, Depth extends number = 5> = Transpose<CollectResults<T>, [], Depth> extends [\n infer L,\n infer R,\n] ? [UnknownMembersToNever<L>, UnknownMembersToNever<R>]\n : Transpose<CollectResults<T>, [], Depth> extends [] ? [[], []]\n : never\n\n// Deduplicates the result, as the result type is a union of Err and Ok types.\nexport type Dedup<T> = T extends Result<infer RL, infer RR> ? Result<RL, RR>\n : T\n\n// Given a union, this gives the array of the union members.\nexport type MemberListOf<T> = (\n (T extends unknown ? (t: T) => T : never) extends infer U\n ? (U extends unknown ? (u: U) => unknown : never) extends (v: infer V) => unknown ? V\n : never\n : never\n) extends (_: unknown) => infer W ? [...MemberListOf<Exclude<T, W>>, W]\n : []\n\n// Converts an empty array to never.\n//\n// The second type parameter here will affect how to behave to `never[]`s.\n// If a precise type is required, pass `1` here so that it will resolve\n// a literal array such as `[ never, never ]`. Otherwise, set `0` or the default\n// type value will cause this to resolve the arrays containing only `never`\n// items as `never` only.\nexport type EmptyArrayToNever<T, NeverArrayToNever extends number = 0> = T extends [] ? never\n : NeverArrayToNever extends 1 ? T extends [never, ...infer Rest] ? [EmptyArrayToNever<Rest>] extends [never] ? never\n : T\n : T\n : T\n\n// Converts the `unknown` items of an array to `never`s.\ntype UnknownMembersToNever<T> = T extends [infer H, ...infer R]\n ? [[unknown] extends [H] ? never : H, ...UnknownMembersToNever<R>]\n : T\n\n// Gets the member type of the array or never.\nexport type MembersToUnion<T> = T extends unknown[] ? T[number] : never\n\n// Checks if the given type is a literal array.\nexport type IsLiteralArray<T> = T extends { length: infer L } ? L extends number ? number extends L ? 0\n : 1\n : 0\n : 0\n\n// Traverses an array of results and returns a single result containing\n// the oks and errs union-ed/combined.\ntype Traverse<T, Depth extends number = 5> = Combine<T, Depth> extends [infer Oks, infer Errs]\n ? Result<EmptyArrayToNever<Oks, 1>, MembersToUnion<Errs>>\n : never\n\n// Traverses an array of results and returns a single result containing\n// the oks combined and the array of errors combined.\ntype TraverseWithAllErrors<T, Depth extends number = 5> = Traverse<T, Depth> extends Result<\n infer Oks,\n infer Errs\n> ? Result<Oks, Errs[]>\n : never\n\n// Combines the array of results into one result.\nexport type CombineResults<\n T extends readonly Result<unknown, unknown>[],\n> = IsLiteralArray<T> extends 1 ? Traverse<T>\n : Result<ExtractOkTypes<T>, ExtractErrTypes<T>[number]>\n\n// Combines the array of results into one result with all errors.\nexport type CombineResultsWithAllErrorsArray<\n T extends readonly Result<unknown, unknown>[],\n> = IsLiteralArray<T> extends 1 ? TraverseWithAllErrors<T>\n : Result<ExtractOkTypes<T>, ExtractErrTypes<T>[number][]>\n\n// #endregion\n","/* eslint-disable @typescript-eslint/unbound-method */\nimport type { Combine, Dedup, EmptyArrayToNever, IsLiteralArray, MemberListOf, MembersToUnion } from './result.js'\nimport { Result } from './result.js'\nimport type {\n ExtractErrAsyncTypes,\n ExtractOkAsyncTypes,\n InferAsyncErrTypes,\n InferAsyncOkTypes,\n InferErrTypes,\n InferOkTypes,\n} from './utils.js'\nimport { combineResultAsyncList, combineResultAsyncListWithAllErrors } from './utils.js'\n\nexport class DisposableResultAsync<T, E> implements PromiseLike<Result<T, E>> {\n private readonly innerPromise: Promise<Result<T, E>>\n\n constructor(res: Promise<Result<T, E>>) {\n this.innerPromise = res\n }\n\n then<A, B>( // eslint-disable-line unicorn/no-thenable\n successCallback?: (res: Result<T, E>) => A | PromiseLike<A>,\n failureCallback?: (reason: unknown) => B | PromiseLike<B>,\n ): PromiseLike<A | B> {\n return this.innerPromise.then(successCallback, failureCallback)\n }\n}\n\n/**\n * Represents an asynchronous Result type that wraps a Promise of a Result<T, E>.\n * This class provides a way to handle asynchronous operations that may succeed with a value of type T\n * or fail with an error of type E.\n *\n * @template T - The type of the success value\n * @template E - The type of the error value\n *\n * @implements {PromiseLike<Result<T, E>>}\n *\n * @example\n * ```typescript\n * // Create a successful async result\n * const okAsync = ResultAsync.okAsync(42);\n *\n * // Create a failed async result\n * const errAsync = ResultAsync.errAsync(new Error(\"Something went wrong\"));\n *\n * // Transform a Promise into a ResultAsync\n * const resultFromPromise = ResultAsync.fromPromise(\n * fetch(\"https://api.example.com/data\"),\n * (error) => new Error(`API call failed: ${error}`)\n * );\n * ```\n *\n * @remarks\n * ResultAsync implements the PromiseLike interface, allowing it to be used with async/await syntax.\n * It provides various utility methods for transforming and combining results, similar to the Result type,\n * but operating in an asynchronous context.\n *\n * The class includes methods for:\n * - Creating ResultAsync instances (okAsync, errAsync, fromPromise)\n * - Transforming values (map, mapErr)\n * - Chaining operations (andThen, orElse)\n * - Error handling (tapError)\n * - Conditional branching (if)\n * - Combining multiple ResultAsync instances (combine, combineWithAllErrors)\n */\nexport class ResultAsync<T, E> implements PromiseLike<Result<T, E>> {\n /**\n * Returns a ResultAsync instance that is immediately resolved with a Result.ok(value).\n *\n * @param {T} value - The value to be wrapped in a Result.ok.\n * @return {ResultAsync<T, E>} A ResultAsync instance with the given value and error type E.\n */\n static okAsync<T, E = never>(value: T): ResultAsync<T, E> {\n return new ResultAsync<T, E>(Promise.resolve(Result.ok(value)))\n }\n\n /**\n * Returns a ResultAsync that is immediately resolved with a Result.ok(undefined) value.\n *\n * @return {ResultAsync<undefined, E>} A ResultAsync instance with undefined as the value type and E as the error type.\n */\n static unitAsync<E = never>(): ResultAsync<undefined, E> {\n return new ResultAsync<undefined, E>(Promise.resolve(Result.unit()))\n }\n\n /**\n * Returns a ResultAsync instance that is immediately resolved with a Result.err(error).\n *\n * @param {E} error - The error to be wrapped in a Result.err.\n * @return {ResultAsync<T, E>} A ResultAsync instance with the given error and value type T.\n */\n static errAsync<T = never, E = unknown>(error: E): ResultAsync<T, E> {\n return new ResultAsync<T, E>(Promise.resolve(Result.err(error)))\n }\n\n /**\n * Creates a ResultAsync from a Promise, catching any errors that occur during its execution.\n *\n * @param fn - The Promise to be wrapped in a ResultAsync.\n * @param errorFn - Optional function to transform the caught error into a specific error type.\n * If not provided, the original error will be used.\n * @returns A ResultAsync that will resolve to Ok with the promise's value if successful,\n * or Err with either the transformed error (if errorFn is provided) or the original error.\n *\n * @example\n * ```typescript\n * // Without error transformer\n * const result = ResultAsync.tryCatch(Promise.resolve(42));\n *\n * // With error transformer\n * const result = ResultAsync.tryCatch(\n * fetch('https://api.example.com'),\n * (error) => new CustomError('API request failed')\n * );\n * ```\n */\n static tryCatch<T, E>(fn: Promise<T>, errorFn?: (e: unknown) => E): ResultAsync<T, E> {\n const newPromise = fn\n .then((value: T) => Result.ok(value))\n .catch(error => {\n if (errorFn) {\n return Result.err(errorFn(error))\n }\n return Result.err(error)\n })\n return new ResultAsync<T, E>(newPromise)\n }\n\n /**\n * Returns a ResultAsync instance that is resolved with a Result.ok(value) or Result.err(error)\n * based on the provided promise.\n *\n * @param {Promise<T>} promise - The promise to be wrapped in a ResultAsync.\n * @return {ResultAsync<T, E>} A ResultAsync instance with the given promise and error type E.\n */\n static fromSafePromise<T, E = never>(promise: PromiseLike<T>): ResultAsync<T, E>\n static fromSafePromise<T, E = never>(promise: Promise<T>): ResultAsync<T, E> {\n const newPromise = promise\n .then((value: T) => Result.ok(value))\n\n return new ResultAsync<T, E>(newPromise)\n }\n\n /**\n * Returns a ResultAsync instance that is resolved with a Result.ok(value) or Result.err(error)\n * based on the provided promise.\n *\n * @param {Promise<T>} promise - The promise to be wrapped in a ResultAsync.\n * @param {(e: unknown) => E} errorFn - A function that transforms the error from the promise into the error type E.\n * @return {ResultAsync<T, E>} A ResultAsync instance with the given promise and error type E.\n */\n static fromPromise<T, E>(promise: PromiseLike<T>, errorFn: (e: unknown) => E): ResultAsync<T, E>\n static fromPromise<T, E>(promise: Promise<T>, errorFn: (e: unknown) => E): ResultAsync<T, E> {\n const newPromise = promise\n .then((value: T) => Result.ok(value))\n .catch(error => Result.err(errorFn(error)))\n\n return new ResultAsync<T, E>(newPromise)\n }\n\n static combine<\n T extends readonly [ResultAsync<unknown, unknown>, ...ResultAsync<unknown, unknown>[]],\n >(asyncResultList: T): CombineResultAsyncs<T>\n static combine<T extends readonly ResultAsync<unknown, unknown>[]>(\n asyncResultList: T,\n ): CombineResultAsyncs<T>\n static combine<T extends readonly ResultAsync<unknown, unknown>[]>(\n asyncResultList: T,\n ): CombineResultAsyncs<T> {\n return (combineResultAsyncList(asyncResultList) as unknown) as CombineResultAsyncs<T>\n }\n\n static combineWithAllErrors<\n T extends readonly [ResultAsync<unknown, unknown>, ...ResultAsync<unknown, unknown>[]],\n >(asyncResultList: T): CombineResultsWithAllErrorsArrayAsync<T>\n static combineWithAllErrors<T extends readonly ResultAsync<unknown, unknown>[]>(\n asyncResultList: T,\n ): CombineResultsWithAllErrorsArrayAsync<T>\n static combineWithAllErrors<T extends readonly ResultAsync<unknown, unknown>[]>(\n asyncResultList: T,\n ): CombineResultsWithAllErrorsArrayAsync<T> {\n return combineResultAsyncListWithAllErrors(\n asyncResultList,\n ) as CombineResultsWithAllErrorsArrayAsync<T>\n }\n\n /**\n * Wraps a async function with a try catch, creating a new function with the same\n * arguments but returning `Ok` if successful, `Err` if the function throws\n *\n * @param fn function to wrap with ok on success or err on failure\n * @param errorFn when an error is thrown, this will wrap the error result if provided\n * @returns a new function that returns a `ResultAsync`\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static fromThrowable<A extends readonly any[], T, E>(\n fn: (...args: A) => Promise<T>,\n errorFn?: (err: unknown) => E,\n ): (...args: A) => ResultAsync<T, E> {\n return (...args) =>\n new ResultAsync<T, E>(\n (async () => {\n try {\n const v = await fn(...args)\n return Result.ok(v)\n } catch (error) {\n const e = errorFn ? errorFn(error) : error\n return Result.err(e as E)\n }\n })(),\n )\n }\n\n private readonly innerPromise: Promise<Result<T, E>>\n\n constructor(res: Promise<Result<T, E>>) {\n this.innerPromise = res\n }\n\n then<A, B>( // eslint-disable-line unicorn/no-thenable\n successCallback?: (res: Result<T, E>) => A | PromiseLike<A>,\n failureCallback?: (reason: unknown) => B | PromiseLike<B>,\n ): PromiseLike<A | B> {\n return this.innerPromise.then(successCallback, failureCallback)\n }\n\n mapErr<U>(f: (t: E) => U | Promise<U>): ResultAsync<T, U> {\n return new ResultAsync<T, U>(this.innerPromise.then(async res => {\n if (res.isOk()) {\n return okAsync(res.value)\n }\n\n return errAsync(await f(res.error))\n }))\n }\n\n map<X>(f: (t: T) => X | Promise<X>): ResultAsync<X, E> {\n const x = new ResultAsync(\n this.innerPromise.then(async (res: Result<T, E>) => {\n if (res.isErr()) {\n return errAsync(res.error)\n }\n\n return okAsync(await f(res.value))\n }),\n )\n\n return x\n }\n\n andThen<R extends Result<unknown, unknown>>(\n f: (t: T) => R,\n ): ResultAsync<InferOkTypes<R>, InferErrTypes<R> | E>\n andThen<R extends ResultAsync<unknown, unknown>>(\n f: (t: T) => R,\n ): ResultAsync<InferAsyncOkTypes<R>, InferAsyncErrTypes<R> | E>\n andThen<U, F>(f: (t: T) => Result<U, F> | ResultAsync<U, F>): ResultAsync<U, E | F>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n andThen(f: any): any {\n return new ResultAsync(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.innerPromise.then(async res => {\n if (res.isErr()) {\n return errAsync(res.error)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n const newValue = f(res.value) // eslint-disable-line @typescript-eslint/no-unsafe-assignment\n return newValue instanceof ResultAsync ? newValue.innerPromise : newValue // eslint-disable-line @typescript-eslint/no-unsafe-return\n }),\n )\n }\n\n if(fCondition: (t: T) => boolean): {\n true: <X1, Y1>(fTrue: (t: T) => ResultAsync<X1, Y1>) => {\n false: <X2, Y2>(fFalse: (t: T) => ResultAsync<X2, Y2>) => ResultAsync<X1 | X2, Y1 | Y2 | E>\n }\n } {\n return {\n true: <X1, Y1>(fTrue: (t: T) => ResultAsync<X1, Y1>) => ({\n false: <X2, Y2>(fFalse: (t: T) => ResultAsync<X2, Y2>): ResultAsync<X1 | X2, Y1 | Y2 | E> =>\n new ResultAsync(this.innerPromise.then(async res => {\n if (res.isOk()) {\n const condition = fCondition(res.value)\n return condition ? fTrue(res.value) : fFalse(res.value)\n }\n\n return errAsync(res.error)\n })),\n }),\n }\n }\n\n orElse<R extends Result<unknown, unknown>>(\n f: (e: E) => R,\n ): ResultAsync<InferOkTypes<R> | T, InferErrTypes<R>>\n orElse<R extends ResultAsync<unknown, unknown>>(\n f: (e: E) => R,\n ): ResultAsync<InferAsyncOkTypes<R> | T, InferAsyncErrTypes<R>>\n orElse<U, A>(f: (e: E) => Result<U, A> | ResultAsync<U, A>): ResultAsync<U | T, A>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n orElse(f: any): any {\n return new ResultAsync(\n this.innerPromise.then(async (res: Result<T, E>) => { // eslint-disable-line @typescript-eslint/no-unsafe-argument\n if (res.isErr()) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n return f(res.error) // eslint-disable-line @typescript-eslint/no-unsafe-return\n }\n\n return okAsync(res.value)\n }),\n )\n }\n\n async match<A, B = A>(ok: (t: T) => A, fnErr: (e: E) => B): Promise<A | B> {\n return this.innerPromise.then(res => res.match(ok, fnErr))\n }\n\n async unwrapOr<A>(t: A): Promise<T | A> {\n return this.innerPromise.then(res => res.unwrapOr(t))\n }\n\n async unwrapOrThrow(): Promise<T> {\n return this.innerPromise.then(res => res.unwrapOrThrow())\n }\n\n /**\n * Performs a side effect for the `Ok` variant of `ResultAsync`.\n * This function can be used for control flow based on result values.\n * @param f The function to call if the result is `Ok`\n * @returns `self` if the result is `Err`, otherwise the result of `f`\n */\n log(f: (t?: T, e?: E) => void | Promise<void>): ResultAsync<T, E> {\n return new ResultAsync(\n this.innerPromise.then(async res => {\n if (res.isOk()) {\n try {\n await f(res.value)\n } catch { /* empty */ }\n\n return okAsync(res.value)\n }\n\n try {\n await f(undefined, res.error)\n } catch { /* empty */ }\n\n return errAsync(res.error)\n }),\n )\n }\n\n /**\n * Performs a side effect for the `Ok` variant of `ResultAsync`.\n * This function can be used for control flow based on result values.\n * @param f The function to call if the result is `Ok`\n * @returns `self` if the result is `Err`, otherwise the result of `f`\n */\n tap(f: (t: T) => void | Promise<void>): ResultAsync<T, E> {\n return new ResultAsync(\n this.innerPromise.then(async res => {\n if (res.isErr()) {\n return errAsync(res.error)\n }\n\n try {\n await f(res.value)\n } catch { /* empty */ }\n\n return okAsync(res.value)\n }),\n )\n }\n\n /**\n * Performs a side effect for the `Err` variant of `ResultAsync`.\n * This function can be used for control flow based on result values.\n * @param f The function to call if the result is `Err`\n * @returns `self` if the result is `Ok`, otherwise the result of `f`\n * @example\n */\n tapError(f: (e: E) => void | Promise<void>): ResultAsync<T, E> {\n return new ResultAsync(\n this.innerPromise.then(async res => {\n if (res.isErr()) {\n try {\n await f(res.error)\n } catch { /* empty */ }\n\n return errAsync(res.error)\n }\n\n return okAsync(res.value)\n }),\n )\n }\n\n finally(f: (value: T, error: E) => void): DisposableResultAsync<T, E> {\n return new DisposableResultAsync(\n // eslint-disable-next-line @typescript-eslint/require-await\n this.innerPromise.then(async res => {\n try {\n res.finally(f)\n } catch {\n // Dont do anything. Its just a finally\n }\n\n return res\n }),\n )\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<Result<never, E>, T> {\n const result = await this.innerPromise\n\n if (result.isErr()) {\n yield errAsync(result.error)\n }\n\n return result.value\n }\n\n /**\n * @deprecated will be removed in 2.0.0.\n *\n * You can use `safeTry` without this method.\n * @example\n * ```typescript\n * safeTry(async function* () {\n * const okValue = yield* yourResult\n * })\n * ```\n * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.\n */\n async *safeUnwrap(): AsyncGenerator<Result<never, E>, T> {\n return yield* await this.innerPromise.then(res => res.safeUnwrap())\n }\n}\n\n/**\n * @deprecated Use `safeTry` instead.\n * @see `safeTry`\n *\n * This will be removed in the next major version.\n */\nexport function safeTryAsync<T, E>(\n body: () => AsyncGenerator<Result<never, E>, Result<T, E>>,\n): ResultAsync<T, E> {\n return new ResultAsync<T, E>(\n (async () => {\n const n = await body().next()\n if (n.value.isOk()) {\n return okAsync(n.value.value)\n }\n\n return errAsync(n.value.error)\n })(),\n )\n}\n\nexport const okAsync = ResultAsync.okAsync\nexport const errAsync = ResultAsync.errAsync\nexport const fromPromise = ResultAsync.fromPromise\nexport const fromSafePromise = ResultAsync.fromSafePromise\nexport const unitAsync = ResultAsync.unitAsync\nexport const fromThrowableAsync = ResultAsync.fromThrowable\nexport const tryCatchAsync = ResultAsync.tryCatch\n\n// Combines the array of async results into one result.\nexport type CombineResultAsyncs<\n T extends readonly ResultAsync<unknown, unknown>[],\n> = IsLiteralArray<T> extends 1 ? TraverseAsync<UnwrapAsync<T>>\n : ResultAsync<ExtractOkAsyncTypes<T>, ExtractErrAsyncTypes<T>[number]>\n\n// Combines the array of async results into one result with all errors.\nexport type CombineResultsWithAllErrorsArrayAsync<\n T extends readonly ResultAsync<unknown, unknown>[],\n> = IsLiteralArray<T> extends 1 ? TraverseWithAllErrorsAsync<UnwrapAsync<T>>\n : ResultAsync<ExtractOkAsyncTypes<T>, ExtractErrAsyncTypes<T>[number][]>\n\n// Unwraps the inner `Result` from a `ResultAsync` for all elements.\ntype UnwrapAsync<T> = IsLiteralArray<T> extends 1\n ? Writable<T> extends [infer H, ...infer Rest]\n ? H extends PromiseLike<infer HI> ? HI extends Result<unknown, unknown> ? [Dedup<HI>, ...UnwrapAsync<Rest>]\n : never\n : never\n : []\n // If we got something too general such as ResultAsync<X, Y>[] then we\n // simply need to map it to ResultAsync<X[], Y[]>. Yet `ResultAsync`\n // itself is a union therefore it would be enough to cast it to Ok.\n : T extends (infer A)[] ? A extends PromiseLike<infer HI> ? HI extends Result<infer L, infer R> ? Result<L, R>[]\n : never\n : never\n : never\n\n// Traverse through the tuples of the async results and create one\n// `ResultAsync` where the collected tuples are merged.\ntype TraverseAsync<T, Depth extends number = 5> = IsLiteralArray<T> extends 1\n ? Combine<T, Depth> extends [infer Oks, infer Errs] ? ResultAsync<EmptyArrayToNever<Oks>, MembersToUnion<Errs>>\n : never\n // The following check is important if we somehow reach to the point of\n // checking something similar to ResultAsync<X, Y>[]. In this case we don't\n // know the length of the elements, therefore we need to traverse the X and Y\n // in a way that the result should contain X[] and Y[].\n : T extends (infer I)[]\n // The MemberListOf<I> here is to include all possible types. Therefore\n // if we face (ResultAsync<X, Y> | ResultAsync<A, B>)[] this type should\n // handle the case.\n ? Combine<MemberListOf<I>, Depth> extends [infer Oks, infer Errs]\n // The following `extends unknown[]` checks are just to satisfy the TS.\n // we already expect them to be an array.\n ? Oks extends unknown[]\n ? Errs extends unknown[] ? ResultAsync<EmptyArrayToNever<Oks[number][]>, MembersToUnion<Errs[number][]>>\n : ResultAsync<EmptyArrayToNever<Oks[number][]>, Errs>\n // The rest of the conditions are to satisfy the TS and support\n // the edge cases which are not really expected to happen.\n : Errs extends unknown[] ? ResultAsync<Oks, MembersToUnion<Errs[number][]>>\n : ResultAsync<Oks, Errs>\n : never\n : never\n\n// This type is similar to the `TraverseAsync` while the errors are also\n// collected in a list. For the checks/conditions made here, see that type\n// for the documentation.\ntype TraverseWithAllErrorsAsync<T, Depth extends number = 5> = TraverseAsync<\n T,\n Depth\n> extends ResultAsync<infer Oks, infer Errs> ? ResultAsync<Oks, Errs[]>\n : never\n\n// Converts a reaodnly array into a writable array\ntype Writable<T> = T extends readonly unknown[] ? [...T] : T\n","import { ResultAsync } from './result-async.js'\nimport type { Result } from './result.js'\nimport { err, ok } from './result.js'\n\n// Given a list of Results, this extracts all the different `T` types from that list\nexport type ExtractOkTypes<T extends readonly Result<unknown, unknown>[]> = {\n [idx in keyof T]: T[idx] extends Result<infer U, unknown> ? U : never\n}\n\n// Given a list of ResultAsyncs, this extracts all the different `T` types from that list\nexport type ExtractOkAsyncTypes<T extends readonly ResultAsync<unknown, unknown>[]> = {\n [idx in keyof T]: T[idx] extends ResultAsync<infer U, unknown> ? U : never\n}\n\n// Given a list of Results, this extracts all the different `E` types from that list\nexport type ExtractErrTypes<T extends readonly Result<unknown, unknown>[]> = {\n [idx in keyof T]: T[idx] extends Result<unknown, infer E> ? E : never\n}\n\n// Given a list of ResultAsyncs, this extracts all the different `E` types from that list\nexport type ExtractErrAsyncTypes<T extends readonly ResultAsync<unknown, unknown>[]> = {\n [idx in keyof T]: T[idx] extends ResultAsync<unknown, infer E> ? E : never\n}\n\nexport type InferOkTypes<R> = R extends Result<infer T, unknown> ? T : never\nexport type InferErrTypes<R> = R extends Result<unknown, infer E> ? E : never\n\nexport type InferAsyncOkTypes<R> = R extends ResultAsync<infer T, unknown> ? T : never\nexport type InferAsyncErrTypes<R> = R extends ResultAsync<unknown, infer E> ? E : never\n\n/**\n * Short circuits on the FIRST Err value that we find\n */\nexport const combineResultList = <T, E>(\n resultList: readonly Result<T, E>[],\n): Result<readonly T[], E> => {\n let acc = ok([]) as Result<T[], E>\n\n for (const result of resultList) {\n if (result.isErr()) {\n acc = err(result.error)\n break\n } else {\n acc.map((list) => list.push(result.value))\n }\n }\n return acc\n}\n\n/* This is the typesafe version of Promise.all\n *\n * Takes a list of ResultAsync<T, E> and success if all inner results are Ok values\n * or fails if one (or more) of the inner results are Err values\n */\nexport const combineResultAsyncList = <T, E>(\n asyncResultList: readonly ResultAsync<T, E>[],\n): ResultAsync<readonly T[], E> =>\n ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(\n combineResultList,\n ) as ResultAsync<T[], E>\n\n/**\n * Give a list of all the errors we find\n */\nexport const combineResultListWithAllErrors = <T, E>(\n resultList: readonly Result<T, E>[],\n): Result<readonly T[], E[]> => {\n let acc = ok([]) as Result<T[], E[]>\n\n for (const result of resultList) {\n if (result.isErr() && acc.isErr()) {\n acc.error.push(result.error)\n } else if (result.isErr() && acc.isOk()) {\n acc = err([result.error])\n } else if (result.isOk() && acc.isOk()) {\n acc.value.push(result.value)\n }\n // do nothing when result.isOk() && acc.isErr()\n }\n return acc\n}\n\nexport const combineResultAsyncListWithAllErrors = <T, E>(\n asyncResultList: readonly ResultAsync<T, E>[],\n): ResultAsync<readonly T[], E[]> =>\n ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(\n combineResultListWithAllErrors,\n ) as ResultAsync<T[], E[]>\n"],"mappings":";;;;;AAMA,IAAM,KAAN,MAAY;AAAA,EAEV,YAA4B,OAAU;AAAV;AAAA,EAAW;AAAA,EAD9B,KAAK;AAEhB;AAEA,IAAM,MAAN,MAAa;AAAA,EAEX,YAA4B,OAAU;AAAV;AAAA,EAAW;AAAA,EAD9B,KAAK;AAEhB;AA6DO,IAAM,SAAN,MAAM,QAAyC;AAAA,EAgH5C,YAA6B,OAAuB;AAAvB;AACnC,QAAI,MAAM,IAAI;AACZ,WAAK,QAAQ,MAAM;AACnB,WAAK,QAAQ;AAAA,IACf,OAAO;AACL,WAAK,QAAQ,MAAM;AACnB,WAAK,QAAQ;AAAA,IACf;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA9GA,OAAO,SACL,IACA,SACc;AACd,QAAI;AACF,aAAO,GAAG,GAAG,CAAC;AAAA,IAChB,SAAS,OAAO;AACd,UAAI,SAAS;AACX,eAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,MAC3B;AACA,aAAO,IAAI,KAAU;AAAA,IACvB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,cACL,IAEA,SACwD;AACxD,WAAO,IAAI,SAAS;AAClB,UAAI;AACF,cAAM,SAAS,GAAG,GAAG,IAAI;AACzB,eAAO,GAAG,MAAwB;AAAA,MACpC,SAAS,OAAO;AACd,YAAI,SAAS;AACX,iBAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,QAC3B;AAEA,e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,MAAI,MAAM,GAAG,CAAC,CAAC;AAEf,aAAW,UAAU,YAAY;AAC/B,QAAI,OAAO,MAAM,GAAG;AAClB,YAAM,IAAI,OAAO,KAAK;AACtB;AAAA,IACF,OAAO;AACL,UAAI,IAAI,CAAC,SAAS,KAAK,KAAK,OAAO,KAAK,CAAC;AAAA,IAC3C;AAAA,EACF;AACA,SAAO;AACT;AAOO,IAAM,yBAAyB,CACpC,oBAEA,YAAY,gBAAgB,QAAQ,IAAI,eAAe,CAAC,EAAE;AAAA,EACxD;AACF;AAKK,IAAM,iCAAiC,CAC5C,eAC8B;AAC9B,MAAI,MAAM,GAAG,CAAC,CAAC;AAEf,aAAW,UAAU,YAAY;AAC/B,QAAI,OAAO,MAAM,KAAK,IAAI,MAAM,GAAG;AACjC,UAAI,MAAM,KAAK,OAAO,KAAK;AAAA,IAC7B,WAAW,OAAO,MAAM,KAAK,IAAI,KAAK,GAAG;AACvC,YAAM,IAAI,CAAC,OAAO,KAAK,CAAC;AAAA,IAC1B,WAAW,OAAO,KAAK,KAAK,IAAI,KAAK,GAAG;AACtC,UAAI,MAAM,KAAK,OAAO,KAAK;AAAA,IAC7B;AAAA,EAEF;AACA,SAAO;AACT;AAEO,IAAM,sCAAsC,CACjD,oBAEA,YAAY,gBAAgB,QAAQ,IAAI,eAAe,CAAC,EAAE;AAAA,EACxD;AACF;","names":["ok"]}
|
package/dist/error.d.cts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { N as ErrorConfig, O as createResultarError } from './index-rRvCJDjp.cjs';
|
package/dist/error.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { N as ErrorConfig, O as createResultarError } from './index-rRvCJDjp.js';
|
|
@@ -32,8 +32,42 @@ declare class DisposableResultAsync<T, E> implements PromiseLike<Result<T, E>> {
|
|
|
32
32
|
successCallback?: (res: Result<T, E>) => A | PromiseLike<A>, failureCallback?: (reason: unknown) => B | PromiseLike<B>): PromiseLike<A | B>;
|
|
33
33
|
}
|
|
34
34
|
/**
|
|
35
|
-
*
|
|
36
|
-
* This
|
|
35
|
+
* Represents an asynchronous Result type that wraps a Promise of a Result<T, E>.
|
|
36
|
+
* This class provides a way to handle asynchronous operations that may succeed with a value of type T
|
|
37
|
+
* or fail with an error of type E.
|
|
38
|
+
*
|
|
39
|
+
* @template T - The type of the success value
|
|
40
|
+
* @template E - The type of the error value
|
|
41
|
+
*
|
|
42
|
+
* @implements {PromiseLike<Result<T, E>>}
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```typescript
|
|
46
|
+
* // Create a successful async result
|
|
47
|
+
* const okAsync = ResultAsync.okAsync(42);
|
|
48
|
+
*
|
|
49
|
+
* // Create a failed async result
|
|
50
|
+
* const errAsync = ResultAsync.errAsync(new Error("Something went wrong"));
|
|
51
|
+
*
|
|
52
|
+
* // Transform a Promise into a ResultAsync
|
|
53
|
+
* const resultFromPromise = ResultAsync.fromPromise(
|
|
54
|
+
* fetch("https://api.example.com/data"),
|
|
55
|
+
* (error) => new Error(`API call failed: ${error}`)
|
|
56
|
+
* );
|
|
57
|
+
* ```
|
|
58
|
+
*
|
|
59
|
+
* @remarks
|
|
60
|
+
* ResultAsync implements the PromiseLike interface, allowing it to be used with async/await syntax.
|
|
61
|
+
* It provides various utility methods for transforming and combining results, similar to the Result type,
|
|
62
|
+
* but operating in an asynchronous context.
|
|
63
|
+
*
|
|
64
|
+
* The class includes methods for:
|
|
65
|
+
* - Creating ResultAsync instances (okAsync, errAsync, fromPromise)
|
|
66
|
+
* - Transforming values (map, mapErr)
|
|
67
|
+
* - Chaining operations (andThen, orElse)
|
|
68
|
+
* - Error handling (tapError)
|
|
69
|
+
* - Conditional branching (if)
|
|
70
|
+
* - Combining multiple ResultAsync instances (combine, combineWithAllErrors)
|
|
37
71
|
*/
|
|
38
72
|
declare class ResultAsync<T, E> implements PromiseLike<Result<T, E>> {
|
|
39
73
|
/**
|
|
@@ -56,6 +90,28 @@ declare class ResultAsync<T, E> implements PromiseLike<Result<T, E>> {
|
|
|
56
90
|
* @return {ResultAsync<T, E>} A ResultAsync instance with the given error and value type T.
|
|
57
91
|
*/
|
|
58
92
|
static errAsync<T = never, E = unknown>(error: E): ResultAsync<T, E>;
|
|
93
|
+
/**
|
|
94
|
+
* Creates a ResultAsync from a Promise, catching any errors that occur during its execution.
|
|
95
|
+
*
|
|
96
|
+
* @param fn - The Promise to be wrapped in a ResultAsync.
|
|
97
|
+
* @param errorFn - Optional function to transform the caught error into a specific error type.
|
|
98
|
+
* If not provided, the original error will be used.
|
|
99
|
+
* @returns A ResultAsync that will resolve to Ok with the promise's value if successful,
|
|
100
|
+
* or Err with either the transformed error (if errorFn is provided) or the original error.
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```typescript
|
|
104
|
+
* // Without error transformer
|
|
105
|
+
* const result = ResultAsync.tryCatch(Promise.resolve(42));
|
|
106
|
+
*
|
|
107
|
+
* // With error transformer
|
|
108
|
+
* const result = ResultAsync.tryCatch(
|
|
109
|
+
* fetch('https://api.example.com'),
|
|
110
|
+
* (error) => new CustomError('API request failed')
|
|
111
|
+
* );
|
|
112
|
+
* ```
|
|
113
|
+
*/
|
|
114
|
+
static tryCatch<T, E>(fn: Promise<T>, errorFn?: (e: unknown) => E): ResultAsync<T, E>;
|
|
59
115
|
/**
|
|
60
116
|
* Returns a ResultAsync instance that is resolved with a Result.ok(value) or Result.err(error)
|
|
61
117
|
* based on the provided promise.
|
|
@@ -105,7 +161,7 @@ declare class ResultAsync<T, E> implements PromiseLike<Result<T, E>> {
|
|
|
105
161
|
orElse<U, A>(f: (e: E) => Result<U, A> | ResultAsync<U, A>): ResultAsync<U | T, A>;
|
|
106
162
|
match<A, B = A>(ok: (t: T) => A, fnErr: (e: E) => B): Promise<A | B>;
|
|
107
163
|
unwrapOr<A>(t: A): Promise<T | A>;
|
|
108
|
-
unwrapOrThrow(): Promise<T
|
|
164
|
+
unwrapOrThrow(): Promise<T>;
|
|
109
165
|
/**
|
|
110
166
|
* Performs a side effect for the `Ok` variant of `ResultAsync`.
|
|
111
167
|
* This function can be used for control flow based on result values.
|
|
@@ -157,6 +213,7 @@ declare const fromPromise: typeof ResultAsync.fromPromise;
|
|
|
157
213
|
declare const fromSafePromise: typeof ResultAsync.fromSafePromise;
|
|
158
214
|
declare const unitAsync: typeof ResultAsync.unitAsync;
|
|
159
215
|
declare const fromThrowableAsync: typeof ResultAsync.fromThrowable;
|
|
216
|
+
declare const tryCatchAsync: typeof ResultAsync.tryCatch;
|
|
160
217
|
type CombineResultAsyncs<T extends readonly ResultAsync<unknown, unknown>[]> = IsLiteralArray<T> extends 1 ? TraverseAsync<UnwrapAsync<T>> : ResultAsync<ExtractOkAsyncTypes<T>, ExtractErrAsyncTypes<T>[number]>;
|
|
161
218
|
type CombineResultsWithAllErrorsArrayAsync<T extends readonly ResultAsync<unknown, unknown>[]> = IsLiteralArray<T> extends 1 ? TraverseWithAllErrorsAsync<UnwrapAsync<T>> : ResultAsync<ExtractOkAsyncTypes<T>, ExtractErrAsyncTypes<T>[number][]>;
|
|
162
219
|
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;
|
|
@@ -217,6 +274,16 @@ interface Resultable<T, E> {
|
|
|
217
274
|
*/
|
|
218
275
|
declare class Result<T, E> implements Resultable<T, E> {
|
|
219
276
|
private readonly state;
|
|
277
|
+
/**
|
|
278
|
+
* Creates a `Result` by running a function that might throw.
|
|
279
|
+
* If the function throws, the error will be caught and returned as an `Err`.
|
|
280
|
+
* If the function succeeds, the value will be wrapped in an `Ok`.
|
|
281
|
+
*
|
|
282
|
+
* @param fn - The function to execute, which might throw an error
|
|
283
|
+
* @param errorFn - Optional function to transform the thrown error before wrapping in `Err`
|
|
284
|
+
* @returns A `Result` containing either the function's return value or the caught error
|
|
285
|
+
*/
|
|
286
|
+
static tryCatch<T, E>(fn: () => Exclude<T, Promise<unknown>>, errorFn?: (e: unknown) => E): Result<T, E>;
|
|
220
287
|
/**
|
|
221
288
|
* Wraps a function with a try catch, creating a new function with the same
|
|
222
289
|
* arguments but returning `Ok` if successful, `Err` if the function throws
|
|
@@ -239,9 +306,15 @@ declare class Result<T, E> implements Resultable<T, E> {
|
|
|
239
306
|
*/
|
|
240
307
|
static unit<E = never>(): Result<undefined, E>;
|
|
241
308
|
static err<T = never, E = unknown>(error: E): Result<T, E>;
|
|
242
|
-
static combine<T extends readonly [
|
|
309
|
+
static combine<T extends readonly [
|
|
310
|
+
Result<unknown, unknown>,
|
|
311
|
+
...Result<unknown, unknown>[]
|
|
312
|
+
]>(resultList: T): CombineResults<T>;
|
|
243
313
|
static combine<T extends readonly Result<unknown, unknown>[]>(resultList: T): CombineResults<T>;
|
|
244
|
-
static combineWithAllErrors<T extends readonly [
|
|
314
|
+
static combineWithAllErrors<T extends readonly [
|
|
315
|
+
Result<unknown, unknown>,
|
|
316
|
+
...Result<unknown, unknown>[]
|
|
317
|
+
]>(resultList: T): CombineResultsWithAllErrorsArray<T>;
|
|
245
318
|
static combineWithAllErrors<T extends readonly Result<unknown, unknown>[]>(resultList: T): CombineResultsWithAllErrorsArray<T>;
|
|
246
319
|
readonly value: T;
|
|
247
320
|
readonly error: E;
|
|
@@ -366,7 +439,7 @@ declare class Result<T, E> implements Resultable<T, E> {
|
|
|
366
439
|
* @param f The function that will be called to clean up the resources
|
|
367
440
|
*/
|
|
368
441
|
finally<X = T, Y = E>(f: (value: X, error: Y) => void): DisposableResult<X, Y>;
|
|
369
|
-
unwrapOrThrow(): T
|
|
442
|
+
unwrapOrThrow(): T;
|
|
370
443
|
/**
|
|
371
444
|
* **This method is unsafe, and should only be used in a test environments**
|
|
372
445
|
*
|
|
@@ -436,6 +509,7 @@ declare const ok: typeof Result.ok;
|
|
|
436
509
|
declare const err: typeof Result.err;
|
|
437
510
|
declare const fromThrowable: typeof Result.fromThrowable;
|
|
438
511
|
declare const unit: typeof Result.unit;
|
|
512
|
+
declare const tryCatch: typeof Result.tryCatch;
|
|
439
513
|
type Prev = [
|
|
440
514
|
never,
|
|
441
515
|
0,
|
|
@@ -530,4 +604,4 @@ interface ResultarError<T, E> extends Error {
|
|
|
530
604
|
}
|
|
531
605
|
declare const createResultarError: <T, E>(message: string, result: Result<T, E>, config?: ErrorConfig) => ResultarError<T, E>;
|
|
532
606
|
|
|
533
|
-
export {
|
|
607
|
+
export { tryCatch as A, type Combine as B, type CombineResultAsyncs as C, DisposableResultAsync as D, type ExtractOkTypes as E, type Dedup as F, type EmptyArrayToNever as G, type MembersToUnion as H, type InferOkTypes as I, type IsLiteralArray as J, type CombineResults as K, type CombineResultsWithAllErrorsArray as L, type MemberListOf as M, type ErrorConfig as N, createResultarError as O, ResultAsync as R, type Transpose as T, type ExtractOkAsyncTypes as a, type ExtractErrTypes as b, type ExtractErrAsyncTypes as c, type InferErrTypes as d, type InferAsyncOkTypes as e, type InferAsyncErrTypes as f, combineResultList as g, combineResultAsyncList as h, combineResultListWithAllErrors as i, combineResultAsyncListWithAllErrors as j, errAsync as k, fromPromise as l, fromSafePromise as m, fromThrowableAsync as n, okAsync as o, type CombineResultsWithAllErrorsArrayAsync as p, Result as q, DisposableResult as r, safeTryAsync as s, tryCatchAsync as t, unitAsync as u, safeTry as v, ok as w, err as x, fromThrowable as y, unit as z };
|