@carbonteq/fp 0.9.1 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +326 -97
  2. package/dist/errors.cjs +2 -3
  3. package/dist/errors.cjs.map +1 -1
  4. package/dist/errors.d.cts +2 -5
  5. package/dist/errors.d.cts.map +1 -1
  6. package/dist/errors.d.mts +2 -5
  7. package/dist/errors.d.mts.map +1 -1
  8. package/dist/errors.mjs +1 -2
  9. package/dist/errors.mjs.map +1 -1
  10. package/dist/flow-experimental.cjs +332 -0
  11. package/dist/flow-experimental.cjs.map +1 -0
  12. package/dist/flow-experimental.d.cts +69 -0
  13. package/dist/flow-experimental.d.cts.map +1 -0
  14. package/dist/flow-experimental.d.mts +69 -0
  15. package/dist/flow-experimental.d.mts.map +1 -0
  16. package/dist/flow-experimental.mjs +330 -0
  17. package/dist/flow-experimental.mjs.map +1 -0
  18. package/dist/flow.cjs +340 -0
  19. package/dist/flow.cjs.map +1 -0
  20. package/dist/flow.d.cts +77 -0
  21. package/dist/flow.d.cts.map +1 -0
  22. package/dist/flow.d.mts +77 -0
  23. package/dist/flow.d.mts.map +1 -0
  24. package/dist/flow.mjs +338 -0
  25. package/dist/flow.mjs.map +1 -0
  26. package/dist/index.cjs +29 -14
  27. package/dist/index.d.cts +10 -5
  28. package/dist/index.d.mts +10 -5
  29. package/dist/index.mjs +10 -5
  30. package/dist/match.cjs +376 -3
  31. package/dist/match.cjs.map +1 -1
  32. package/dist/match.d.cts +467 -8
  33. package/dist/match.d.cts.map +1 -1
  34. package/dist/match.d.mts +467 -8
  35. package/dist/match.d.mts.map +1 -1
  36. package/dist/match.mjs +371 -3
  37. package/dist/match.mjs.map +1 -1
  38. package/dist/option-experimental.cjs +1547 -0
  39. package/dist/option-experimental.cjs.map +1 -0
  40. package/dist/option-experimental.d.cts +1380 -0
  41. package/dist/option-experimental.d.cts.map +1 -0
  42. package/dist/option-experimental.d.mts +1380 -0
  43. package/dist/option-experimental.d.mts.map +1 -0
  44. package/dist/option-experimental.mjs +1545 -0
  45. package/dist/option-experimental.mjs.map +1 -0
  46. package/dist/option.cjs +650 -71
  47. package/dist/option.cjs.map +1 -1
  48. package/dist/option.d.cts +528 -39
  49. package/dist/option.d.cts.map +1 -1
  50. package/dist/option.d.mts +528 -39
  51. package/dist/option.d.mts.map +1 -1
  52. package/dist/option.mjs +648 -70
  53. package/dist/option.mjs.map +1 -1
  54. package/dist/result-experimental.cjs +1346 -0
  55. package/dist/result-experimental.cjs.map +1 -0
  56. package/dist/result-experimental.d.cts +1127 -0
  57. package/dist/result-experimental.d.cts.map +1 -0
  58. package/dist/result-experimental.d.mts +1127 -0
  59. package/dist/result-experimental.d.mts.map +1 -0
  60. package/dist/result-experimental.mjs +1345 -0
  61. package/dist/result-experimental.mjs.map +1 -0
  62. package/dist/result.cjs +746 -81
  63. package/dist/result.cjs.map +1 -1
  64. package/dist/result.d.cts +799 -104
  65. package/dist/result.d.cts.map +1 -1
  66. package/dist/result.d.mts +799 -104
  67. package/dist/result.d.mts.map +1 -1
  68. package/dist/result.mjs +742 -73
  69. package/dist/result.mjs.map +1 -1
  70. package/dist/tuple.cjs +5 -4
  71. package/dist/tuple.cjs.map +1 -1
  72. package/dist/tuple.d.cts +9 -7
  73. package/dist/tuple.d.cts.map +1 -1
  74. package/dist/tuple.d.mts +9 -7
  75. package/dist/tuple.d.mts.map +1 -1
  76. package/dist/tuple.mjs +4 -3
  77. package/dist/tuple.mjs.map +1 -1
  78. package/dist/unit.cjs +3 -3
  79. package/dist/unit.cjs.map +1 -1
  80. package/dist/unit.d.cts +4 -5
  81. package/dist/unit.d.cts.map +1 -1
  82. package/dist/unit.d.mts +4 -5
  83. package/dist/unit.d.mts.map +1 -1
  84. package/dist/unit.mjs +2 -2
  85. package/dist/unit.mjs.map +1 -1
  86. package/dist/utils.cjs +50 -3
  87. package/dist/utils.cjs.map +1 -1
  88. package/dist/utils.d.cts +14 -4
  89. package/dist/utils.d.cts.map +1 -1
  90. package/dist/utils.d.mts +14 -4
  91. package/dist/utils.d.mts.map +1 -1
  92. package/dist/utils.mjs +46 -3
  93. package/dist/utils.mjs.map +1 -1
  94. package/examples/README.md +60 -0
  95. package/examples/flow/01-basics.ts +74 -0
  96. package/examples/flow/02-async.ts +73 -0
  97. package/examples/flow/03-recovery.ts +60 -0
  98. package/examples/flow/04-complex-backend.ts +240 -0
  99. package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
  100. package/examples/flow/index.ts +13 -0
  101. package/examples/flow-experimental/01-basics.ts +78 -0
  102. package/examples/flow-experimental/02-async.ts +77 -0
  103. package/examples/flow-experimental/03-recovery.ts +93 -0
  104. package/examples/flow-experimental/04-complex-backend.ts +244 -0
  105. package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
  106. package/examples/flow-experimental/index.ts +14 -0
  107. package/examples/match/01-stable-match.ts +154 -0
  108. package/examples/match/index.ts +19 -0
  109. package/examples/match-experimental/01-experimental-match.ts +157 -0
  110. package/examples/match-experimental/index.ts +18 -0
  111. package/examples/option/01-basics.ts +16 -0
  112. package/examples/option/02-map-flatMap.ts +36 -0
  113. package/examples/option/03-zip-flatZip.ts +23 -0
  114. package/examples/option/04-constructors.ts +21 -0
  115. package/examples/option/05-transform.ts +15 -0
  116. package/examples/option/06-aggregation.ts +14 -0
  117. package/examples/option/index.ts +49 -0
  118. package/examples/option-experimental/01-map.ts +109 -0
  119. package/examples/option-experimental/02-flatMap.ts +234 -0
  120. package/examples/option-experimental/03-zip.ts +197 -0
  121. package/examples/option-experimental/04-flatZip.ts +251 -0
  122. package/examples/option-experimental/05-gen.ts +360 -0
  123. package/examples/option-experimental/06-genAdapter.ts +463 -0
  124. package/examples/option-experimental/07-asyncGen.ts +353 -0
  125. package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
  126. package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
  127. package/examples/option-experimental/10-workflow-async.ts +378 -0
  128. package/examples/option-experimental/index.ts +341 -0
  129. package/examples/option-experimental/shared-domain.ts +325 -0
  130. package/examples/result/01-basics.ts +16 -0
  131. package/examples/result/02-map-flatMap.ts +34 -0
  132. package/examples/result/03-zip-flatZip.ts +23 -0
  133. package/examples/result/04-validation.ts +44 -0
  134. package/examples/result/05-constructors.ts +30 -0
  135. package/examples/result/06-utilities.ts +36 -0
  136. package/examples/result/index.ts +53 -0
  137. package/examples/result-experimental/01-map.ts +60 -0
  138. package/examples/result-experimental/02-flatMap.ts +169 -0
  139. package/examples/result-experimental/03-zip.ts +145 -0
  140. package/examples/result-experimental/04-flatZip.ts +252 -0
  141. package/examples/result-experimental/05-gen.ts +293 -0
  142. package/examples/result-experimental/06-genAdapter.ts +396 -0
  143. package/examples/result-experimental/07-asyncGen.ts +379 -0
  144. package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
  145. package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
  146. package/examples/result-experimental/10-workflow-async.ts +356 -0
  147. package/examples/result-experimental/index.ts +312 -0
  148. package/examples/result-experimental/shared-domain.ts +263 -0
  149. package/package.json +54 -31
package/dist/result.d.mts CHANGED
@@ -1,33 +1,67 @@
1
- import { UNIT } from "./unit.mjs";
2
1
  import { Option } from "./option.mjs";
3
-
4
- //#region src/result.d.ts
5
- type Mapper<T, U$1> = (val: T) => U$1;
6
- type FlatZipInput<_T, U$1, E$1> = Result<U$1, E$1> | Result<Promise<U$1>, E$1> | Promise<Result<U$1, E$1>> | Promise<Result<Promise<U$1>, E$1>>;
7
- type UnitResult<E$1 = never> = Result<UNIT, E$1>;
8
- type UnwrapResult<T extends Result<unknown, unknown>> = T extends Result<infer U, infer E> ? {
2
+ import { UNIT } from "./unit.mjs";
3
+ type Mapper<T, U> = (val: T) => U;
4
+ type FlatZipInput<_T, U, E> = Result<U, E> | Result<Promise<U>, E> | Promise<Result<U, E>> | Promise<Result<Promise<U>, E>>;
5
+ /** Result alias for success-without-payload operations. */
6
+ export type UnitResult<E = never> = Result<UNIT, E>;
7
+ /** Extracts `{ ok, err }` branch types from a Result type. */
8
+ export type UnwrapResult<T extends Result<unknown, unknown>> = T extends Result<infer U, infer E> ? {
9
9
  ok: U;
10
10
  err: E;
11
11
  } : never;
12
- type CombinedResultOk<T extends Result<unknown, unknown>[]> = { [K in keyof T]: UnwrapResult<T[K]>["ok"] };
13
- type CombinedResultErr<T extends Result<unknown, unknown>[]> = { [K in keyof T]: UnwrapResult<T[K]>["err"] }[number];
14
- type CombineResults<T extends Result<unknown, unknown>[]> = Result<CombinedResultOk<T>, CombinedResultErr<T>>;
15
- type UnwrapPromises<T extends Result<unknown, unknown>[]> = { [K in keyof T]: Awaited<UnwrapResult<T[K]>["ok"]> };
12
+ type CombinedResultOk<T extends Result<unknown, unknown>[]> = { [K in keyof T]: UnwrapResult<T[K]>["ok"]; };
13
+ type CombinedResultErr<T extends Result<unknown, unknown>[]> = { [K in keyof T]: UnwrapResult<T[K]>["err"]; }[number];
14
+ /** Combines a tuple of Results into one Result of tuple values. */
15
+ export type CombineResults<T extends Result<unknown, unknown>[]> = Result<CombinedResultOk<T>, CombinedResultErr<T>>;
16
+ type UnwrapPromises<T extends Result<unknown, unknown>[]> = { [K in keyof T]: Awaited<UnwrapResult<T[K]>["ok"]>; };
16
17
  type IsPromise<T> = T extends Promise<unknown> ? true : false;
17
- type HasPromise<T extends readonly Result<unknown, unknown>[]> = true extends { [K in keyof T]: IsPromise<T[K] extends Result<infer U, unknown> ? U : never> }[number] ? true : false;
18
+ type HasPromise<T extends readonly Result<unknown, unknown>[]> = true extends { [K in keyof T]: IsPromise<T[K] extends Result<infer U, unknown> ? U : never>; }[number] ? true : false;
18
19
  /** NO_ERR sentinel indicates no async error has occurred */
19
20
  declare const NO_ERR: unique symbol;
20
21
  /** Internal symbol for accessing private factory - not exported */
21
22
  declare const RESULT_INTERNAL: unique symbol;
22
23
  type NO_ERR = typeof NO_ERR;
23
- type ResultCtx<E$1> = {
24
- asyncErr: E$1 | NO_ERR;
24
+ type ResultCtx<E> = {
25
+ asyncErr: E | NO_ERR;
25
26
  };
26
- interface MatchCases<T, E$1, U$1> {
27
- Ok: (val: T) => U$1;
28
- Err: (err: E$1) => U$1;
27
+ interface MatchCases<T, E, U> {
28
+ Ok: (val: T) => U;
29
+ Err: (err: E) => U;
30
+ }
31
+ /**
32
+ * Wrapper that makes Result yieldable with proper type tracking.
33
+ * The Generator signature ensures TypeScript tracks the inner type T.
34
+ *
35
+ * @internal
36
+ */
37
+ declare class ResultYieldWrap<T, E> {
38
+ readonly result: Result<T, E>;
39
+ constructor(result: Result<T, E>);
40
+ [Symbol.iterator](): Generator<ResultYieldWrap<T, E>, T, unknown>;
29
41
  }
30
- declare class Result<T, E$1> {
42
+ /**
43
+ * Wrapper that makes Result yieldable in async generators with proper type tracking.
44
+ * Supports Promise<Result<T, E>> for async result chaining.
45
+ * Delegation returns the awaited success value, including promise-backed payloads.
46
+ *
47
+ * @internal
48
+ */
49
+ declare class AsyncResultYieldWrap<T, E> {
50
+ readonly result: Promise<Result<T, E>>;
51
+ constructor(result: Promise<Result<T, E>>);
52
+ [Symbol.asyncIterator](): AsyncGenerator<AsyncResultYieldWrap<T, E>, Awaited<T>, unknown>;
53
+ }
54
+ /** Extract error type from yielded values */
55
+ type ExtractResultError<T> = T extends ResultYieldWrap<any, infer E> ? E : never;
56
+ /** Extract error type from async yielded values */
57
+ type ExtractAsyncResultError<T> = T extends AsyncResultYieldWrap<any, infer E> ? E : never;
58
+ /** Extract error type directly from Result */
59
+ type ExtractError<T> = T extends Result<any, infer E> ? E : never;
60
+ /**
61
+ * Represents a computation that can succeed (`Ok<T>`) or fail (`Err<E>`).
62
+ * Provides composable transformations with explicit error propagation.
63
+ */
64
+ export declare class Result<T, E> {
31
65
  #private;
32
66
  /** Discriminant tag for type-level identification */
33
67
  readonly _tag: "Ok" | "Err";
@@ -40,103 +74,764 @@ declare class Result<T, E$1> {
40
74
  private getErr;
41
75
  /** Singleton UNIT_RESULT for void-success operations */
42
76
  static readonly UNIT_RESULT: Result<UNIT, never>;
43
- /** Create an Ok containing the given value */
44
- static Ok<T, E$1 = never>(this: void, val: T): Result<T, E$1>;
45
- /** Create an Err containing the given error */
46
- static Err<E$1, T = never>(this: void, err: E$1): Result<T, E$1>;
47
- /** Type guard for Ok state */
77
+ /**
78
+ * Creates an Ok containing the given value.
79
+ *
80
+ * @template T - Success value type
81
+ * @template E - Error type (defaults to never)
82
+ * @param val - Success value
83
+ * @returns Result in the Ok state
84
+ */
85
+ static Ok<T, E = never>(this: void, val: T): Result<T, E>;
86
+ /**
87
+ * Creates an Err containing the given error.
88
+ *
89
+ * @template E - Error type
90
+ * @template T - Success value type (defaults to never)
91
+ * @param err - Error value
92
+ * @returns Result in the Err state
93
+ */
94
+ static Err<E, T = never>(this: void, err: E): Result<T, E>;
95
+ /**
96
+ * Type guard for Ok state.
97
+ *
98
+ * @returns true if this Result is Ok
99
+ */
48
100
  isOk(): this is Result<T, never>;
49
- /** Type guard for Err state */
50
- isErr(): this is Result<never, E$1>;
51
- /** Type guard for Unit value */
101
+ /**
102
+ * Type guard for Err state.
103
+ *
104
+ * @returns true if this Result is Err
105
+ */
106
+ isErr(): this is Result<never, E>;
107
+ /**
108
+ * Type guard for Ok containing UNIT.
109
+ *
110
+ * @returns true if the Ok value is UNIT
111
+ */
52
112
  isUnit(): this is Result<UNIT, never>;
113
+ /**
114
+ * Returns a string representation of the Result.
115
+ *
116
+ * @returns "Result::Ok<value>" or "Result::Err<error>"
117
+ */
53
118
  toString(): string;
54
- /** Returns value or throws (re-throws if E extends Error) */
55
- unwrap(this: Result<Promise<T>, E$1>): Promise<T>;
56
- unwrap(this: Result<T, E$1>): T;
57
- /** Returns error or throws UnwrapError */
58
- unwrapErr<T, E$1>(this: Result<T, E$1>): E$1;
59
- unwrapErr<T, E$1>(this: Result<Promise<T>, E$1>): Promise<E$1>;
60
- /** Returns value or the provided default */
61
- unwrapOr<Curr = Awaited<T>>(this: Result<Promise<Curr>, E$1>, defaultValue: Curr): Promise<Curr>;
62
- unwrapOr(this: Result<T, E$1>, defaultValue: T): T;
63
- /** Returns value or calls factory with error to get default */
64
- unwrapOrElse<Curr = Awaited<T>>(this: Result<Promise<Curr>, E$1>, fn: (err: E$1) => Curr): Promise<Curr>;
65
- unwrapOrElse(this: Result<T, E$1>, fn: (err: E$1) => T): T;
66
- /** Safe unwrap - returns null for Err */
67
- safeUnwrap(this: Result<never, E$1>): null;
68
- safeUnwrap<Curr = Awaited<T>>(this: Result<Promise<Curr>, E$1>): Promise<Curr | null> | null;
69
- safeUnwrap(this: Result<T, E$1>): T | null;
70
- /** Pattern match on Result state */
71
- match<U$1>(cases: MatchCases<T, E$1, U$1>): U$1;
72
- map<T, U$1, E$1>(this: Result<Promise<T>, E$1>, fn: (val: T) => Promise<U$1>): Result<Promise<U$1>, E$1>;
73
- map<T, U$1, E$1>(this: Result<Promise<T>, E$1>, fn: (val: T) => U$1): Result<Promise<U$1>, E$1>;
74
- map<In, U$1>(this: Result<In, E$1>, fn: (val: In) => Promise<U$1>): Result<Promise<U$1>, E$1>;
75
- map<In, U$1>(this: Result<In, E$1>, fn: (val: In) => U$1): Result<U$1, E$1>;
119
+ /**
120
+ * Returns the contained value or throws.
121
+ *
122
+ * If Err and the error is an Error, re-throws it; otherwise throws
123
+ * UnwrappedOkWithErr. For async values, returns a Promise that rejects
124
+ * on error.
125
+ *
126
+ * @returns The contained value (sync or async)
127
+ * @throws Error or UnwrappedOkWithErr when Err
128
+ */
129
+ unwrap(this: Result<Promise<T>, E>): Promise<T>;
130
+ unwrap(this: Result<T, E>): T;
131
+ /**
132
+ * Returns the contained error or throws.
133
+ *
134
+ * For async values, returns a Promise resolving to the error or rejecting
135
+ * with UnwrappedErrWithOk when Ok.
136
+ *
137
+ * @returns The contained error (sync or async)
138
+ * @throws UnwrappedErrWithOk when called on Ok
139
+ */
140
+ unwrapErr<T, E>(this: Result<T, E>): E;
141
+ unwrapErr<T, E>(this: Result<Promise<T>, E>): Promise<E>;
142
+ /**
143
+ * Returns the contained value or the provided default.
144
+ *
145
+ * For async values, returns a Promise resolving to the value or default.
146
+ *
147
+ * @param defaultValue - Fallback value when Err
148
+ * @returns The contained value or default (sync or async)
149
+ */
150
+ unwrapOr<Curr = Awaited<T>>(this: Result<Promise<Curr>, E>, defaultValue: Curr): Promise<Curr>;
151
+ unwrapOr(this: Result<T, E>, defaultValue: T): T;
152
+ /**
153
+ * Returns the contained value or computes a default from the error.
154
+ *
155
+ * For async values, returns a Promise resolving to the value or computed
156
+ * default.
157
+ *
158
+ * @param fn - Function that maps the error to a fallback value
159
+ * @returns The contained value or computed default (sync or async)
160
+ */
161
+ unwrapOrElse<Curr = Awaited<T>>(this: Result<Promise<Curr>, E>, fn: (err: E) => Curr): Promise<Curr>;
162
+ unwrapOrElse(this: Result<T, E>, fn: (err: E) => T): T;
163
+ /**
164
+ * Safely unwraps the value, returning null for Err.
165
+ *
166
+ * For async values, returns a Promise resolving to the value or null.
167
+ *
168
+ * @returns The contained value or null (sync or async)
169
+ */
170
+ safeUnwrap(this: Result<never, E>): null;
171
+ safeUnwrap<Curr = Awaited<T>>(this: Result<Promise<Curr>, E>): Promise<Curr | null> | null;
172
+ safeUnwrap(this: Result<T, E>): T | null;
173
+ /**
174
+ * Exhaustive pattern match on Result state.
175
+ *
176
+ * @template U - Result type of the handlers
177
+ * @param cases - Handlers for Ok and Err
178
+ * @returns Result of the matching handler
179
+ */
180
+ match<U>(cases: MatchCases<T, E, U>): U;
181
+ /**
182
+ * Transforms the success value using the provided function.
183
+ *
184
+ * If the Result is Ok, applies the function to the value and wraps the result
185
+ * in a new Ok. If Err, propagates the error unchanged without calling the function.
186
+ *
187
+ * @param fn - Function to transform the success value
188
+ * @returns Result<U, E> with transformed value or propagated error
189
+ *
190
+ * @example
191
+ * ```ts
192
+ * Result.Ok(42).map((x) => x * 2); // Ok(84)
193
+ * Result.Err("fail").map((x) => x * 2); // Err("fail")
194
+ * ```
195
+ *
196
+ * @see flatMap
197
+ */
198
+ map<T, U, E>(this: Result<Promise<T>, E>, fn: (val: T) => Promise<U>): Result<Promise<U>, E>;
199
+ map<T, U, E>(this: Result<Promise<T>, E>, fn: (val: T) => U): Result<Promise<U>, E>;
200
+ map<In, U>(this: Result<In, E>, fn: (val: In) => Promise<U>): Result<Promise<U>, E>;
201
+ map<In, U>(this: Result<In, E>, fn: (val: In) => U): Result<U, E>;
202
+ /**
203
+ * Safely maps a promised Ok value while propagating async errors.
204
+ *
205
+ * @template In - Input value type
206
+ * @template U - Output value type
207
+ * @template E - Error type
208
+ * @param p - Promise of Ok value or ERR sentinel
209
+ * @param mapper - Transform function
210
+ * @param ctx - New async context to populate on error
211
+ * @param parentCtx - Parent async context to read error from
212
+ * @returns Promise of transformed value or ERR sentinel
213
+ */
76
214
  private static safeMap;
77
- mapErr<U$1>(fn: Mapper<E$1, U$1>): Result<T, U$1>;
78
- mapBoth<T2, E2>(fnOk: (val: T) => T2, fnErr: (val: E$1) => E2): Result<T2, E2>;
79
- mapBoth<T2, E2, In = Awaited<T2>>(fnOk: (val: In) => T2, fnErr: (val: E$1) => E2): Result<Promise<In>, E2>;
80
- mapBoth<T2, E2, In = Awaited<T2>>(this: Result<Promise<In>, E$1>, fnOk: (val: In) => Promise<T2>, fnErr: (val: E$1) => E2): Result<Promise<In>, E2>;
81
- flatMap<T, U$1, E2>(this: Result<Promise<T>, E$1>, fn: (val: T) => Result<Promise<U$1>, E2>): Result<Promise<U$1>, E$1 | E2>;
82
- flatMap<T, U$1, E2>(this: Result<Promise<T>, E$1>, fn: (val: T) => Promise<Result<Promise<U$1>, E2>>): Result<Promise<U$1>, E$1 | E2>;
83
- flatMap<T, U$1, E2>(this: Result<Promise<T>, E$1>, fn: (val: T) => Promise<Result<U$1, E2>>): Result<Promise<U$1>, E$1 | E2>;
84
- flatMap<T, U$1, E2>(this: Result<Promise<T>, E$1>, fn: (val: T) => Result<U$1, E$1 | E2>): Result<Promise<U$1>, E$1 | E2>;
85
- flatMap<T, U$1, E2>(this: Result<T, E$1>, fn: (val: T) => Promise<Result<Promise<U$1>, E$1 | E2>>): Result<Promise<U$1>, E$1 | E2>;
86
- flatMap<T, U$1, E2>(this: Result<T, E$1>, fn: (val: T) => Promise<Result<U$1, E$1 | E2>>): Result<Promise<U$1>, E$1 | E2>;
87
- flatMap<T, U$1, E2>(this: Result<T, E$1>, fn: (val: T) => Result<U$1, E2>): Result<U$1, E$1 | E2>;
88
- flatMap<T, _U, E2>(this: Result<Promise<T>, E$1>, fn: (val: T) => Promise<Result<Promise<Result<unknown, unknown>>, E2>>): never;
89
- flatMap<T, _U, E2>(this: Result<T, E$1>, fn: (val: T) => Promise<Result<Promise<Result<unknown, unknown>>, E$1 | E2>>): never;
215
+ /**
216
+ * Transforms the error value while preserving the success value.
217
+ *
218
+ * If the Result is Err, applies the function to the error. If Ok, returns
219
+ * the Ok unchanged without calling the function.
220
+ *
221
+ * @param fn - Function to transform the error
222
+ * @returns Result<T, E2> with transformed error or original Ok
223
+ *
224
+ * @example
225
+ * ```ts
226
+ * Result.Err("network error").mapErr((e) => `Network: ${e}`); // Err("Network: network error")
227
+ * Result.Ok(42).mapErr((e) => `Error: ${e}`); // Ok(42)
228
+ *
229
+ * // Add context to errors
230
+ * fetchData()
231
+ * .mapErr((e) => new ContextualError("Failed to fetch data", e));
232
+ * ```
233
+ *
234
+ * @see mapBoth
235
+ */
236
+ mapErr<U>(fn: Mapper<E, U>): Result<T, U>;
237
+ /**
238
+ * Transforms both the Ok and Err values.
239
+ *
240
+ * Applies fnOk when Ok and fnErr when Err. Supports async Ok values via
241
+ * overloads; returns Result with mapped types.
242
+ *
243
+ * @param fnOk - Mapper for Ok values
244
+ * @param fnErr - Mapper for Err values
245
+ * @returns Result with both branches transformed
246
+ */
247
+ mapBoth<T2, E2, In = Awaited<T>>(this: Result<Promise<In>, E>, fnOk: (val: In) => T2 | Promise<T2>, fnErr: (val: E) => E2): Result<Promise<T2>, E2>;
248
+ mapBoth<T2, E2>(this: Result<T, E>, fnOk: (val: T) => Promise<T2>, fnErr: (val: E) => E2): Result<Promise<T2>, E2>;
249
+ mapBoth<T2, E2>(this: Result<T, E>, fnOk: (val: T) => T2, fnErr: (val: E) => E2): Result<T2, E2>;
250
+ /**
251
+ * Chains operations that return Results, flattening nested Results.
252
+ *
253
+ * If the Result is Ok, applies the function (which returns a new Result) and
254
+ * returns that Result directly. If Err, propagates the error unchanged.
255
+ *
256
+ * Error types are unified: `Result<U, E | E2>`.
257
+ * Mapper throws propagate synchronously for sync inputs and reject the
258
+ * returned promise chain for promise inputs; they do not become Err.
259
+ *
260
+ * @param fn - Function that returns a Result
261
+ * @returns Result<U, E | E2> from the function or propagated error
262
+ *
263
+ * @example
264
+ * ```ts
265
+ * // Success chain
266
+ * Result.Ok(42)
267
+ * .flatMap((x) => Result.Ok(x + 1)) // Ok(43)
268
+ * .flatMap((x) => Result.Err("too big")); // Err("too big")
269
+ *
270
+ * // Error propagation
271
+ * Result.Err("initial").flatMap((x) => Result.Ok(x + 1)); // Err("initial")
272
+ * ```
273
+ *
274
+ * @see map
275
+ * @see flatZip
276
+ */
277
+ flatMap<T, U, E2>(this: Result<Promise<T>, E>, fn: (val: T) => Result<Promise<U>, E2>): Result<Promise<U>, E | E2>;
278
+ flatMap<T, U, E2>(this: Result<Promise<T>, E>, fn: (val: T) => Promise<Result<Promise<U>, E2>>): Result<Promise<U>, E | E2>;
279
+ flatMap<T, U, E2>(this: Result<Promise<T>, E>, fn: (val: T) => Promise<Result<U, E2>>): Result<Promise<U>, E | E2>;
280
+ flatMap<T, U, E2>(this: Result<Promise<T>, E>, fn: (val: T) => Result<U, E | E2>): Result<Promise<U>, E | E2>;
281
+ flatMap<T, U, E2>(this: Result<T, E>, fn: (val: T) => Promise<Result<Promise<U>, E | E2>>): Result<Promise<U>, E | E2>;
282
+ flatMap<T, U, E2>(this: Result<T, E>, fn: (val: T) => Promise<Result<U, E | E2>>): Result<Promise<U>, E | E2>;
283
+ flatMap<T, U, E2>(this: Result<T, E>, fn: (val: T) => Result<U, E2>): Result<U, E | E2>;
284
+ flatMap<T, _U, E2>(this: Result<Promise<T>, E>, fn: (val: T) => Promise<Result<Promise<Result<unknown, unknown>>, E2>>): never;
285
+ flatMap<T, _U, E2>(this: Result<T, E>, fn: (val: T) => Promise<Result<Promise<Result<unknown, unknown>>, E | E2>>): never;
286
+ /**
287
+ * Normalizes sync/async flatMap outputs to a value or Promise.
288
+ *
289
+ * @template U - Success value type
290
+ * @template E - Original error type
291
+ * @template E2 - Mapped error type
292
+ * @template T - Input value type
293
+ * @param mutableCtx - Mutable context for async error propagation
294
+ * @param mapped - FlatMap output (sync or async Result)
295
+ * @returns Value, Promise, or ERR sentinel
296
+ */
90
297
  private static flatMapHelper;
298
+ /**
299
+ * Extracts the inner value from a Result, updating error context on failure.
300
+ *
301
+ * @template U - Success value type
302
+ * @template E - Original error type
303
+ * @template E2 - Mapped error type
304
+ * @param mutableCtx - Mutable context for async error propagation
305
+ * @param r - Inner Result to unwrap
306
+ * @returns Value, Promise, or ERR sentinel
307
+ */
91
308
  private static flatMapInnerHelper;
92
- zip<T, U$1, In = Awaited<T>>(this: Result<Promise<In>, E$1>, fn: (val: In) => Promise<U$1>): Result<Promise<[In, U$1]>, E$1>;
93
- zip<T, U$1, In = Awaited<T>>(this: Result<Promise<In>, E$1>, fn: (val: In) => U$1): Result<Promise<[In, U$1]>, E$1>;
94
- zip<T, U$1>(this: Result<T, E$1>, fn: (val: T) => Promise<U$1>): Result<Promise<[T, U$1]>, E$1>;
95
- zip<T, U$1>(this: Result<T, E$1>, fn: (val: T) => U$1): Result<[T, U$1], E$1>;
96
- flatZip<U$1, E2, In = Awaited<T>>(this: Result<Promise<In>, E$1>, fn: (val: In) => FlatZipInput<In, U$1, E$1 | E2>): Result<Promise<[In, Awaited<U$1>]>, E$1 | E2>;
97
- flatZip<U$1, E2, In = Awaited<T>>(this: Result<In, E$1>, fn: (val: In) => Promise<Result<U$1, E2>> | Promise<Result<Promise<U$1>, E2>> | Result<Promise<U$1>, E2>): Result<Promise<[In, Awaited<U$1>]>, E$1 | E2>;
98
- flatZip<U$1, E2, In = Awaited<T>>(this: Result<In, E$1>, fn: (val: In) => Result<U$1, E2>): Result<[In, U$1], E$1 | E2>;
309
+ /**
310
+ * Pairs the original value with a derived value in a tuple.
311
+ *
312
+ * Unlike `map` which replaces the value, `zip` keeps the original and adds
313
+ * the derived value, creating `[original, derived]`.
314
+ *
315
+ * @param fn - Function to derive a value from the original
316
+ * @returns Result<[T, U], E> containing tuple of original and derived values
317
+ *
318
+ * @example
319
+ * ```ts
320
+ * Result.Ok(42).zip((x) => x * 10); // Ok([42, 420])
321
+ * Result.Err("fail").zip((x) => x * 10); // Err("fail")
322
+ *
323
+ * // Keep original while computing related value
324
+ * Result.Ok(user).zip((u) => u.permissions.length); // Ok([user, 5])
325
+ * ```
326
+ *
327
+ * @see flatZip
328
+ * @see map
329
+ */
330
+ zip<T, U, In = Awaited<T>>(this: Result<Promise<In>, E>, fn: (val: In) => Promise<U>): Result<Promise<[In, U]>, E>;
331
+ zip<T, U, In = Awaited<T>>(this: Result<Promise<In>, E>, fn: (val: In) => U): Result<Promise<[In, U]>, E>;
332
+ zip<T, U>(this: Result<T, E>, fn: (val: T) => Promise<U>): Result<Promise<[T, U]>, E>;
333
+ zip<T, U>(this: Result<T, E>, fn: (val: T) => U): Result<[T, U], E>;
334
+ /**
335
+ * Combines the current Result with another independent Result in a tuple.
336
+ *
337
+ * Unlike `zip` which derives a value from the original, `flatZip` works with
338
+ * two independent Results. If either is Err, propagates the first error.
339
+ *
340
+ * Supports both sync and async Results. Async combinations return
341
+ * `Result<Promise<[T, U]>, E | E2>`.
342
+ *
343
+ * @param fn - Function that receives the value and returns another Result
344
+ * @returns Result<[T, U], E | E2> containing tuple of both values, or error
345
+ *
346
+ * @example
347
+ * ```ts
348
+ * Result.Ok(42)
349
+ * .flatZip((x) => Result.Ok(x + 5)) // Ok([42, 47])
350
+ * .flatZip(([a, b]) => Result.Err("x")); // Err("x")
351
+ *
352
+ * Result.Ok(42).flatZip((x) => Result.Err("fail")); // Err("fail")
353
+ * Result.Err("init").flatZip((x) => Result.Ok(5)); // Err("init")
354
+ * ```
355
+ *
356
+ * @see zip
357
+ * @see flatMap
358
+ */
359
+ flatZip<U, E2, In = Awaited<T>>(this: Result<Promise<In>, E>, fn: (val: In) => FlatZipInput<In, U, E | E2>): Result<Promise<[In, Awaited<U>]>, E | E2>;
360
+ flatZip<U, E2, In = Awaited<T>>(this: Result<In, E>, fn: (val: In) => Promise<Result<U, E2>> | Promise<Result<Promise<U>, E2>> | Result<Promise<U>, E2>): Result<Promise<[In, Awaited<U>]>, E | E2>;
361
+ flatZip<U, E2, In = Awaited<T>>(this: Result<In, E>, fn: (val: In) => Result<U, E2>): Result<[In, U], E | E2>;
362
+ /**
363
+ * Normalizes sync/async flatZip outputs to a tuple or ERR sentinel.
364
+ *
365
+ * @template U - Derived value type
366
+ * @template E - Original error type
367
+ * @template E2 - Mapped error type
368
+ * @template In - Original value type
369
+ * @param mutableCtx - Mutable context for async error propagation
370
+ * @param originalVal - Original value to preserve
371
+ * @param mapped - FlatZip output (sync or async Result)
372
+ * @returns Tuple, Promise of tuple, or ERR sentinel
373
+ */
99
374
  private static flatZipHelper;
375
+ /**
376
+ * Extracts the inner value for flatZip, updating error context on failure.
377
+ *
378
+ * @template U - Derived value type
379
+ * @template E - Original error type
380
+ * @template E2 - Mapped error type
381
+ * @template In - Original value type
382
+ * @param mutableCtx - Mutable context for async error propagation
383
+ * @param originalVal - Original value to preserve
384
+ * @param r - Inner Result to unwrap
385
+ * @returns Tuple, Promise of tuple, or ERR sentinel
386
+ */
100
387
  private static flatZipInnerHelper;
101
- zipErr<E2>(this: Result<Promise<T>, E$1>, fn: (val: T) => Promise<Result<unknown, E2>>): Result<Promise<T>, E$1 | E2>;
102
- zipErr<E2>(this: Result<T, E$1>, fn: (val: T) => Promise<Result<unknown, E2>>): Result<Promise<T>, E$1 | E2>;
103
- zipErr<E2>(this: Result<T, E$1>, fn: (val: T) => Result<unknown, E2>): Result<T, E$1 | E2>;
388
+ /**
389
+ * Runs a Result-producing function and turns Ok into Err on failure.
390
+ *
391
+ * If this Result is Ok, calls fn with the value. If fn returns Err, the
392
+ * resulting Result becomes Err while the original Ok value is preserved
393
+ * when fn succeeds.
394
+ *
395
+ * @template E2 - Additional error type
396
+ * @param fn - Function producing a Result
397
+ * @returns Result with original value or combined error
398
+ */
399
+ zipErr<E2>(this: Result<Promise<T>, E>, fn: (val: T) => Promise<Result<unknown, E2>>): Result<Promise<T>, E | E2>;
400
+ zipErr<E2>(this: Result<T, E>, fn: (val: T) => Promise<Result<unknown, E2>>): Result<Promise<T>, E | E2>;
401
+ zipErr<E2>(this: Result<T, E>, fn: (val: T) => Result<unknown, E2>): Result<T, E | E2>;
402
+ /**
403
+ * Tracks errors from a Result while preserving the original value.
404
+ *
405
+ * @template In - Original value type
406
+ * @template E - Error type
407
+ * @param v - Original value to preserve
408
+ * @param r - Result to inspect for errors
409
+ * @param newCtx - Context to populate on error
410
+ * @returns Original value or Promise of value
411
+ */
104
412
  private static zipErrHelper;
105
- validate<VE extends unknown[]>(this: Result<T, E$1>, validators: { [K in keyof VE]: (val: T) => Result<unknown, VE[K]> }): Result<T, E$1 | VE[number][]>;
106
- validate<VE extends unknown[]>(this: Result<T, E$1>, validators: { [K in keyof VE]: (val: T) => Promise<Result<unknown, VE[K]>> }): Result<Promise<T>, E$1 | VE[number][]>;
107
- validate<VE extends unknown[], In = Awaited<T>>(this: Result<T, E$1> | Result<Promise<T>, E$1>, validators: { [K in keyof VE]: (val: In) => Promise<Result<unknown, VE[K]>> | Result<unknown, VE[K]> }): Result<Promise<T>, E$1 | VE[number][]>;
413
+ private static captureZipErr;
414
+ /**
415
+ * Runs multiple validators on the Ok value, collecting ALL errors.
416
+ *
417
+ * Unlike most Result methods which short-circuit on the first error,
418
+ * `validate` runs ALL validators and collects all errors together.
419
+ * This is useful for form validation where you want to show all errors at once.
420
+ *
421
+ * If the Result is Err, returns it unchanged without running validators.
422
+ *
423
+ * Supports both sync and async validators. If any validator is async,
424
+ * returns `Result<Promise<T>, E | VE[]>`.
425
+ *
426
+ * @param validators - Array of validator functions that return Result
427
+ * @returns Result<T, E | VE[]> with original value or array of all errors
428
+ *
429
+ * @example
430
+ * ```ts
431
+ * const validators = [
432
+ * (x: number) => x > 0 ? Result.Ok(true) : Result.Err("must be positive"),
433
+ * (x: number) => x < 100 ? Result.Ok(true) : Result.Err("must be < 100"),
434
+ * (x: number) => x % 2 === 0 ? Result.Ok(true) : Result.Err("must be even"),
435
+ * ];
436
+ *
437
+ * Result.Ok(42).validate(validators); // Ok(42)
438
+ * Result.Ok(101).validate(validators); // Err(["must be < 100"])
439
+ * Result.Ok(-5).validate(validators); // Err(["must be positive", "must be even"])
440
+ * Result.Err("init").validate(validators); // Err("init") - validators not run
441
+ *
442
+ * // With async validators (returns Result<Promise<T>, ...>)
443
+ * await Result.Ok(data).validate([
444
+ * async (d) => await validateEmail(d),
445
+ * async (d) => await validatePhone(d),
446
+ * ]);
447
+ * ```
448
+ *
449
+ * @see all
450
+ */
451
+ validate<VE extends unknown[]>(this: Result<T, E>, validators: { [K in keyof VE]: (val: T) => Result<unknown, VE[K]>; }): Result<T, E | VE[number][]>;
452
+ validate<VE extends unknown[]>(this: Result<T, E>, validators: { [K in keyof VE]: (val: T) => Promise<Result<unknown, VE[K]>>; }): Result<Promise<T>, E | VE[number][]>;
453
+ validate<VE extends unknown[], In = Awaited<T>>(this: Result<T, E> | Result<Promise<T>, E>, validators: { [K in keyof VE]: (val: In) => Promise<Result<unknown, VE[K]>> | Result<unknown, VE[K]>; }): Result<Promise<T>, E | VE[number][]>;
454
+ /**
455
+ * Collapses validator Results into a single value or ERR sentinel.
456
+ *
457
+ * @template Val - Success value type
458
+ * @template Err - Error type
459
+ * @param results - Validator Results to combine
460
+ * @param currCtx - Context to populate on error
461
+ * @param currVal - Original value to return on success
462
+ * @returns Original value, Promise of value, or ERR sentinel
463
+ */
108
464
  private static validateHelper;
465
+ /**
466
+ * Combines multiple Results, collecting all values or all errors.
467
+ *
468
+ * Unlike typical Result behavior which short-circuits on first error,
469
+ * `all` collects ALL errors from all Results. This is useful when you
470
+ * want to show complete validation feedback.
471
+ *
472
+ * - All Ok → `Ok([...values])` with preserved tuple types
473
+ * - Any Err → `Err([...errors])` collecting ALL errors
474
+ *
475
+ * @param results - Variable number of Results to combine
476
+ * @returns Result with tuple of all values, or array of all errors
477
+ *
478
+ * @example
479
+ * ```ts
480
+ * Result.all(Result.Ok(1), Result.Ok(2), Result.Ok(3)); // Ok([1, 2, 3])
481
+ * Result.all(Result.Ok(1), Result.Err("a"), Result.Err("b")); // Err(["a", "b"])
482
+ * Result.all(); // Ok([])
483
+ *
484
+ * // Real-world: Parallel validation
485
+ * const [user, posts, likes] = await Promise.all([
486
+ * fetchUser(id),
487
+ * fetchPosts(id),
488
+ * fetchLikes(id),
489
+ * ]);
490
+ *
491
+ * const combined = Result.all(user, posts, likes);
492
+ * // Ok([User, Post[], Like[]]) or Err([...errors])
493
+ * ```
494
+ *
495
+ * @see any
496
+ * @see validate
497
+ */
109
498
  static all<T extends Result<unknown, unknown>[]>(...results: T): HasPromise<T> extends true ? Result<Promise<UnwrapPromises<T>>, CombinedResultErr<T>[]> : Result<CombinedResultOk<T>, CombinedResultErr<T>[]>;
110
- /** Returns first Ok, or collects all errors */
111
- static any<U$1, F>(...results: Result<U$1, F>[]): Result<U$1, F[]>;
112
- /** Execute side effect for Ok, return self */
113
- tap<Curr = Awaited<T>>(this: Result<Promise<Curr>, E$1>, fn: (val: Curr) => void): Result<Promise<Curr>, E$1>;
114
- tap(this: Result<T, E$1>, fn: (val: T) => void): Result<T, E$1>;
115
- /** Execute side effect for Err, return self */
116
- tapErr(fn: (err: E$1) => void): Result<T, E$1>;
117
- /** Swap Ok and Err */
118
- flip(): Result<E$1, T>;
119
- /** Convert Result to Option (discards error info) */
499
+ /**
500
+ * Returns the first Ok, or collects all errors if all are Err.
501
+ *
502
+ * Useful for fallback chains where you want the first success, but want
503
+ * to collect all errors if everything fails.
504
+ *
505
+ * - First settled Ok in input order → Returns that Ok
506
+ * - All Err → `Err([...all errors])`
507
+ *
508
+ * For async Ok values, this waits for settlement and selects the first
509
+ * successful candidate in input order, without waiting for the suffix after success.
510
+ *
511
+ * @param results - Variable number of Results to check
512
+ * @returns First Ok found, or Err with array of all errors
513
+ *
514
+ * @example
515
+ * ```ts
516
+ * Result.any(
517
+ * Result.Err("Error 1"),
518
+ * Result.Ok("First success"),
519
+ * Result.Ok("Second success"),
520
+ * ); // Ok("First success")
521
+ *
522
+ * Result.any(
523
+ * Result.Err("Error 1"),
524
+ * Result.Err("Error 2"),
525
+ * Result.Err("Error 3"),
526
+ * ); // Err(["Error 1", "Error 2", "Error 3"])
527
+ *
528
+ * // Fallback chain
529
+ * Result.any(
530
+ * fetchFromCache(key),
531
+ * fetchFromDb(key),
532
+ * fetchFromRemote(key),
533
+ * );
534
+ * ```
535
+ *
536
+ * @see all
537
+ */
538
+ static any<U, F>(...results: Result<U, F>[]): Result<U, F[]>;
539
+ /**
540
+ * Executes a side effect function for Ok values, then returns self.
541
+ *
542
+ * Useful for logging, debugging, or executing effects without breaking the
543
+ * method chain. The function is only called if the Result is Ok.
544
+ *
545
+ * @param fn - Function to execute with the Ok value
546
+ * @returns The same Result (chainable)
547
+ *
548
+ * @example
549
+ * ```ts
550
+ * Result.Ok(42)
551
+ * .tap((x) => console.log(`Processing: ${x}`))
552
+ * .map((x) => x * 2);
553
+ * // Logs: "Processing: 42"
554
+ * // Returns: Ok(84)
555
+ *
556
+ * // Err - tap does nothing
557
+ * Result.Err("fail").tap((x) => console.log(x)); // Err("fail")
558
+ * ```
559
+ *
560
+ * @see tapErr
561
+ */
562
+ tap<Curr = Awaited<T>>(this: Result<Promise<Curr>, E>, fn: (val: Curr) => void): Result<Promise<Curr>, E>;
563
+ tap(this: Result<T, E>, fn: (val: T) => void): Result<T, E>;
564
+ /**
565
+ * Executes a side effect function for Err values, then returns self.
566
+ *
567
+ * Useful for logging errors or executing cleanup without breaking the chain.
568
+ * The function is only called if the Result is Err.
569
+ *
570
+ * @param fn - Function to execute with the error (sync or async)
571
+ * @returns The same Result (chainable)
572
+ *
573
+ * @example
574
+ * ```ts
575
+ * Result.Err("Connection failed")
576
+ * .tapErr((err) => console.error(`[Error Log] ${new Date().toISOString()}: ${err}`))
577
+ * .orElse((e) => Result.Ok(defaultValue));
578
+ * // Logs error timestamp
579
+ * // Returns: Ok(defaultValue)
580
+ *
581
+ * // Ok - tapErr does nothing
582
+ * Result.Ok(42).tapErr((e) => console.log(e)); // Ok(42)
583
+ * ```
584
+ *
585
+ * @see tap
586
+ */
587
+ tapErr(fn: (err: E) => void): Result<T, E>;
588
+ /**
589
+ * Swaps the Ok and Err states, turning success into failure and vice versa.
590
+ *
591
+ * Useful for inverting the meaning of a Result, such as converting
592
+ * validation errors to successes and valid values to errors.
593
+ *
594
+ * @returns Result<E, T> with swapped states
595
+ *
596
+ * @example
597
+ * ```ts
598
+ * Result.Ok("Success value").flip(); // Err("Success value")
599
+ * Result.Err("Error value").flip(); // Ok("Error value")
600
+ *
601
+ * // Invert validation (fail if value is in blacklist)
602
+ * const blacklist = ["admin", "root"];
603
+ * const isBlacklisted = (name: string) =>
604
+ * Result.fromPredicate(name, (n) => !blacklist.includes(n), "blacklisted")
605
+ * .flip(); // Ok if blacklisted, Err if not
606
+ * ```
607
+ */
608
+ flip(): Result<E, T>;
609
+ /**
610
+ * Converts Result to Option, discarding error information.
611
+ *
612
+ * - Ok(value) → Some(value)
613
+ * - Err(error) → None
614
+ *
615
+ * Use when you only care about presence/absence of a value, not the error.
616
+ * Promise-backed Results preserve settled failure and propagate rejections.
617
+ *
618
+ * @returns Option<T> - Some if Ok, None if Err
619
+ *
620
+ * @example
621
+ * ```ts
622
+ * Result.Ok(42).toOption(); // Some(42)
623
+ * Result.Err("fail").toOption(); // None
624
+ *
625
+ * // Safe user lookup
626
+ * const userOpt = fetchUser(id).toOption();
627
+ * // User or None, regardless of why fetch failed
628
+ * ```
629
+ *
630
+ * @see Option.toResult
631
+ */
120
632
  toOption(): Option<T>;
121
- /** Resolve inner Promise and maintain Result structure */
122
- toPromise(): Promise<Result<Awaited<T>, E$1>>;
123
- /** Map over array elements inside Result */
124
- innerMap<In, E$1, Out>(this: Result<Array<In>, E$1>, mapper: (val: NoInfer<In>) => Out): Result<Array<Out>, E$1>;
125
- /** Recover from error by providing fallback Result */
126
- orElse<T2, E2>(fn: (err: E$1) => Result<T2, E2>): Result<T | T2, E2>;
127
- }
128
- declare namespace Result {
129
- /** Create Result from nullable value - returns Err for null/undefined */
130
- function fromNullable<T, E$1>(val: T | null | undefined, error: E$1): Result<NonNullable<T>, E$1>;
131
- /** Create Result based on predicate result */
132
- function fromPredicate<T, E$1>(val: T, pred: (v: T) => boolean, error: E$1): Result<T, E$1>;
133
- /** Wrap Promise<Result<T, E>> as Result<Promise<T>, E> */
134
- function fromPromise<U$1, F>(promise: Promise<Result<U$1, F>>): Result<Promise<U$1>, F>;
135
- /** Catches sync exceptions */
136
- function tryCatch<T, E$1 = unknown>(fn: () => T, errorMapper?: (e: unknown) => E$1): Result<T, E$1>;
137
- /** Catches async exceptions */
138
- function tryAsyncCatch<T, E$1 = unknown>(fn: () => Promise<T>, errorMapper?: (e: unknown) => E$1): Result<Promise<T>, E$1>;
633
+ /**
634
+ * Resolves the inner promise while preserving Result structure.
635
+ *
636
+ * @returns Promise of Result with awaited value or Err
637
+ */
638
+ toPromise(): Promise<Result<Awaited<T>, E>>;
639
+ /**
640
+ * Maps over array elements inside a Result<Array<T>, E>.
641
+ *
642
+ * Applies the mapper function to each element if the Result is Ok and
643
+ * contains an array. Propagates Err unchanged.
644
+ *
645
+ * @param mapper - Function to map over each array element
646
+ * @returns Result<Array<Out>, E> with mapped array or propagated error
647
+ * @throws Error if the Result is Ok but value is not an array
648
+ *
649
+ * @example
650
+ * ```ts
651
+ * Result.Ok([1, 2, 3]).innerMap((x) => x * 2); // Ok([2, 4, 6])
652
+ * Result.Err("fail").innerMap((x) => x * 2); // Err("fail")
653
+ * ```
654
+ */
655
+ innerMap<In, E, Out>(this: Result<Array<In>, E>, mapper: (val: NoInfer<In>) => Out): Result<Array<Out>, E>;
656
+ /**
657
+ * Recovers from Err by providing a fallback Result.
658
+ *
659
+ * If Ok, returns self unchanged.
660
+ *
661
+ * @template T2 - Fallback success type
662
+ * @template E2 - Fallback error type
663
+ * @param fn - Function to produce a fallback Result from the error
664
+ * @returns Original Ok or fallback Result
665
+ */
666
+ orElse<T2, E2>(fn: (err: E) => Result<T2, E2>): Result<T | T2, E2>;
667
+ /**
668
+ * Creates a Result from a nullable value.
669
+ *
670
+ * Returns Err when the value is null or undefined, otherwise Ok.
671
+ *
672
+ * @template T - Input value type
673
+ * @template E - Error type
674
+ * @param val - Value to wrap
675
+ * @param error - Error value for null/undefined
676
+ * @returns Ok with value or Err with error
677
+ */
678
+ static fromNullable<T, E>(this: void, val: T | null | undefined, error: E): Result<NonNullable<T>, E>;
679
+ /**
680
+ * Creates a Result based on a predicate.
681
+ *
682
+ * Returns Ok when predicate passes, otherwise Err.
683
+ *
684
+ * @template T - Input value type
685
+ * @template E - Error type
686
+ * @param val - Value to test
687
+ * @param pred - Predicate to decide Ok vs Err
688
+ * @param error - Error value for predicate failure
689
+ * @returns Ok with value or Err with error
690
+ */
691
+ static fromPredicate<T, E>(this: void, val: T, pred: (v: T) => boolean, error: E): Result<T, E>;
692
+ /**
693
+ * Wraps a Promise<Result<T, E>> as Result<Promise<T>, E>.
694
+ *
695
+ * Returns an optimistic `Ok(Promise<T>)`. If the inner promise fails later,
696
+ * the failure is tracked internally and surfaces when you settle/unwrap
697
+ * (`toPromise`, `unwrap`, `unwrapErr`, etc.).
698
+ * Promise-backed inner Results are settled before their failure is propagated.
699
+ *
700
+ * @template U - Success value type
701
+ * @template F - Error type
702
+ * @param promise - Promise resolving to a Result
703
+ * @returns Result containing a Promise of the success value
704
+ */
705
+ static fromPromise<U, F>(this: void, promise: Promise<Result<U, F>>): Result<Promise<U>, F>;
706
+ /**
707
+ * Catches synchronous exceptions and converts them to Err.
708
+ *
709
+ * @template T - Success value type
710
+ * @template E - Error type
711
+ * @param fn - Function that may throw
712
+ * @param errorMapper - Optional mapper for thrown errors
713
+ * @returns Ok with return value or Err with mapped error
714
+ */
715
+ static tryCatch<T, E = unknown>(this: void, fn: () => T, errorMapper?: (e: unknown) => E): Result<T, E>;
716
+ /**
717
+ * Catches async exceptions and converts them to Err.
718
+ *
719
+ * Returns an optimistic `Ok(Promise<T>)`. If the async work fails later,
720
+ * the failure is tracked internally and surfaces when you settle/unwrap
721
+ * (`toPromise`, `unwrap`, `unwrapErr`, etc.).
722
+ *
723
+ * @template T - Success value type
724
+ * @template E - Error type
725
+ * @param fn - Async function that may throw
726
+ * @param errorMapper - Optional mapper for thrown errors
727
+ * @returns Result containing a Promise of the success value
728
+ */
729
+ static tryAsyncCatch<T, E = unknown>(this: void, fn: () => Promise<T>, errorMapper?: (e: unknown) => E): Result<Promise<T>, E>;
730
+ /**
731
+ * Makes Result iterable for use with generator-based syntax.
732
+ * Yields self and returns the unwrapped value when resumed.
733
+ *
734
+ * @example
735
+ * ```ts
736
+ * const result = Result.gen(function* () {
737
+ * const value = yield* Result.Ok(42);
738
+ * return value * 2;
739
+ * });
740
+ * ```
741
+ */
742
+ [Symbol.iterator](): Generator<Result<T, E>, T, unknown>;
743
+ /**
744
+ * Makes Result iterable for use with async generator-based syntax.
745
+ * Yields self and returns the awaited unwrapped value when resumed.
746
+ *
747
+ * @example
748
+ * ```ts
749
+ * const result = await Result.asyncGen(async function* () {
750
+ * const value = yield* $(Result.Ok(42));
751
+ * return value * 2;
752
+ * });
753
+ * ```
754
+ */
755
+ [Symbol.asyncIterator](): AsyncGenerator<Result<T, E>, Awaited<T>, unknown>;
756
+ /**
757
+ * Generator-based syntax for chaining Result operations (simplified, no adapter).
758
+ * Provides imperative-style code while maintaining functional error handling.
759
+ *
760
+ * Short-circuits on first Err, returning that error. Uses iteration instead of
761
+ * recursion to avoid stack overflow on deep chains.
762
+ *
763
+ * @example
764
+ * ```ts
765
+ * const result = Result.gen(function* () {
766
+ * const a = yield* Result.Ok(1);
767
+ * const b = yield* Result.Ok(2);
768
+ * return a + b;
769
+ * });
770
+ * // Result<number, never>
771
+ * ```
772
+ */
773
+ static gen<Eff extends Result<any, any>, T>(this: void, genFn: () => Generator<Eff, T, any>): Result<T, ExtractError<Eff>>;
774
+ /**
775
+ * Generator-based syntax for chaining Result operations (with adapter).
776
+ * Uses an adapter function ($) for improved type inference.
777
+ *
778
+ * Short-circuits on first Err, returning that error. Uses iteration instead of
779
+ * recursion to avoid stack overflow on deep chains.
780
+ *
781
+ * @example
782
+ * ```ts
783
+ * const result = Result.genAdapter(function* ($) {
784
+ * const a = yield* $(Result.Ok(1));
785
+ * const b = yield* $(Result.Ok(2));
786
+ * return a + b;
787
+ * });
788
+ * // Result<number, never>
789
+ * ```
790
+ */
791
+ static genAdapter<Eff extends ResultYieldWrap<any, any>, T>(this: void, genFn: (adapter: <A, E>(result: Result<A, E>) => ResultYieldWrap<A, E>) => Generator<Eff, T, any>): Result<T, ExtractResultError<Eff>>;
792
+ /**
793
+ * Async generator-based syntax for chaining Result operations (simplified, no adapter).
794
+ * Use yield* with Result values directly. For Promise<Result<T, E>>, await first then yield*.
795
+ * Settles promise-backed Results before checking for Err; raw rejections propagate.
796
+ *
797
+ * Short-circuits on first Err, returning that error. Uses async iteration instead of
798
+ * recursion to avoid stack overflow on deep chains.
799
+ *
800
+ * @example
801
+ * ```ts
802
+ * const fetchData = (id: number): Promise<Result<{ id: number }, string>> =>
803
+ * Promise.resolve(Result.Ok({ id }));
804
+ * const result = await Result.asyncGen(async function* () {
805
+ * const a = yield* Result.Ok(1);
806
+ * const dataResult = yield* await fetchData(a);
807
+ * return a + dataResult.id;
808
+ * });
809
+ * // Result<number, never>
810
+ * ```
811
+ */
812
+ static asyncGen<Eff extends Result<any, any>, T>(this: void, genFn: () => AsyncGenerator<Eff, T, any>): Promise<Result<T, ExtractError<Eff>>>;
813
+ /**
814
+ * Async generator-based syntax for chaining Result operations (with adapter).
815
+ * Uses an adapter function ($) for improved type inference.
816
+ * Supports both Result<T, E> and Promise<Result<T, E>> for flexibility.
817
+ * Settles promise-backed Results before checking for Err; raw rejections propagate.
818
+ *
819
+ * Short-circuits on first Err, returning that error. Uses async iteration instead of
820
+ * recursion to avoid stack overflow on deep chains.
821
+ *
822
+ * @example
823
+ * ```ts
824
+ * const fetchData = (id: number): Promise<Result<{ id: number }, string>> =>
825
+ * Promise.resolve(Result.Ok({ id }));
826
+ * const result = await Result.asyncGenAdapter(async function* ($) {
827
+ * const a = yield* $(Result.Ok(1));
828
+ * const data = yield* $(fetchData(a));
829
+ * return a + data.id;
830
+ * });
831
+ * // Result<number, never>
832
+ * ```
833
+ */
834
+ static asyncGenAdapter<Eff extends AsyncResultYieldWrap<any, any>, T>(this: void, genFn: (adapter: <A, E2>(result: Result<A, E2> | Promise<Result<A, E2>>) => AsyncResultYieldWrap<A, E2>) => AsyncGenerator<Eff, T, any>): Promise<Result<T, ExtractAsyncResultError<Eff>>>;
139
835
  }
140
- //#endregion
141
- export { CombineResults, Result, UnitResult, UnwrapResult };
836
+ export {};
142
837
  //# sourceMappingURL=result.d.mts.map